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
|
---|---|---|---|---|---|---|---|---|---|
9a3d41aa05d26fa97a96dae99ebeee1584a82c74
|
core/imt/src/TThreadExecutor.cxx
|
core/imt/src/TThreadExecutor.cxx
|
#include "ROOT/TThreadExecutor.hxx"
#if !defined(_MSC_VER)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include "tbb/tbb.h"
#if !defined(_MSC_VER)
#pragma GCC diagnostic pop
#endif
//////////////////////////////////////////////////////////////////////////
///
/// \class ROOT::TThreadExecutor
/// \ingroup Parallelism
/// \brief This class provides a simple interface to execute the same task
/// multiple times in parallel, possibly with different arguments every
/// time. This mimics the behaviour of python's pool.Map method.
///
/// ### ROOT::TThreadExecutor::Map
/// This class inherits its interfaces from ROOT::TExecutor\n.
/// The two possible usages of the Map method are:\n
/// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments
/// * Map(F func, T& args): func is executed on each element of the collection of arguments args
///
/// For either signature, func is executed as many times as needed by a pool of
/// nThreads threads; It defaults to the number of cores.\n
/// A collection containing the result of each execution is returned.\n
/// **Note:** the user is responsible for the deletion of any object that might
/// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never
/// deletes what it returns, it simply forgets it.\n
///
/// \param func
/// \parblock
/// a lambda expression, an std::function, a loaded macro, a
/// functor class or a function that takes zero arguments (for the first signature)
/// or one (for the second signature).
/// \endparblock
/// \param args
/// \parblock
/// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature.
/// An integer only for the first.
/// \endparblock
/// **Note:** in cases where the function to be executed takes more than
/// zero/one argument but all are fixed except zero/one, the function can be wrapped
/// in a lambda or via std::bind to give it the right signature.\n
///
/// #### Return value:
/// An std::vector. The elements in the container
/// will be the objects returned by func.
///
///
/// #### Examples:
///
/// ~~~{.cpp}
/// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10);
/// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3});
/// ~~~
///
/// ### ROOT::TThreadExecutor::MapReduce
/// This set of methods behaves exactly like Map, but takes an additional
/// function as a third argument. This function is applied to the set of
/// objects returned by the corresponding Map execution to "squash" them
/// to a single object. This function should be independent of the size of
/// the vector returned by Map due to optimization of the number of chunks.
///
/// If this function is a binary operator, the "squashing" will be performed in parallel.
/// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n
/// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in.
/// This may be useful to avoid the overhead introduced when running really short tasks.
///
/// #### Examples:
/// ~~~{.cpp}
/// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); })
/// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects);
/// ~~~
///
//////////////////////////////////////////////////////////////////////////
/*
VERY IMPORTANT NOTE ABOUT WORK ISOLATION
We enclose the parallel_for and parallel_reduce invocations in a
task_arena::isolate because we want to prevent a thread to start executing an
outer task when the task it's running spawned subtasks, e.g. with a parallel_for,
and is waiting on inner tasks to be completed.
While this change has a negligible performance impact, it has benefits for
several applications, for example big parallelised HEP frameworks and
RDataFrame analyses.
- For HEP Frameworks, without work isolation, it can happen that a huge
framework task is pulled by a yielding ROOT task.
This causes to delay the processing of the event which is interrupted by the
long task.
For example, work isolation avoids that during the wait due to the parallel
flushing of baskets, a very long simulation task is pulled in by the idle task.
- For RDataFrame analyses we want to guarantee that each entry is processed from
the beginning to the end without TBB interrupting it to pull in other work items.
As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions
and transformations guarantee that each entry is processed from the beginning to
the end without being interrupted by the processing of outer tasks.
*/
namespace ROOT {
namespace Internal {
/// A helper function to implement the TThreadExecutor::ParallelReduce methods
template<typename T>
static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc)
{
using BRange_t = tbb::blocked_range<decltype(objs.begin())>;
auto pred = [redfunc](BRange_t const & range, T init) {
return std::accumulate(range.begin(), range.end(), init, redfunc);
};
BRange_t objRange(objs.begin(), objs.end());
return tbb::this_task_arena::isolate([&]{
return tbb::parallel_reduce(objRange, T{}, pred, redfunc);
});
}
} // End NS Internal
} // End NS ROOT
namespace ROOT {
//////////////////////////////////////////////////////////////////////////
/// Class constructor.
/// If the scheduler is active (e.g. because another TThreadExecutor is in flight, or ROOT::EnableImplicitMT() was
/// called), work with the current pool of threads.
/// If not, initialize the pool of threads, spawning nThreads. nThreads' default value, 0, initializes the
/// pool with as many logical threads as are available in the system (see NLogicalCores in RTaskArenaWrapper.cxx).
///
/// At construction time, TThreadExecutor automatically enables ROOT's thread-safety locks as per calling
/// ROOT::EnableThreadSafety().
TThreadExecutor::TThreadExecutor(UInt_t nThreads)
{
fTaskArenaW = ROOT::Internal::GetGlobalTaskArena(nThreads);
}
void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step, const std::function<void(unsigned int i)> &f)
{
fTaskArenaW->Access().execute([&]{
tbb::this_task_arena::isolate([&]{
tbb::parallel_for(start, end, step, f);
});
});
}
double TThreadExecutor::ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc)
{
return fTaskArenaW->Access().execute([&] { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); });
}
float TThreadExecutor::ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc)
{
return fTaskArenaW->Access().execute([&] { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); });
}
unsigned TThreadExecutor::GetPoolSize(){
return fTaskArenaW->TaskArenaSize();
}
}
|
#include "ROOT/TThreadExecutor.hxx"
#if !defined(_MSC_VER)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#include "tbb/tbb.h"
#if !defined(_MSC_VER)
#pragma GCC diagnostic pop
#endif
//////////////////////////////////////////////////////////////////////////
///
/// \class ROOT::TThreadExecutor
/// \ingroup Parallelism
/// \brief This class provides a simple interface to execute the same task
/// multiple times in parallel, possibly with different arguments every
/// time. This mimics the behaviour of python's pool.Map method.
///
/// ### ROOT::TThreadExecutor::Map
/// This class inherits its interfaces from ROOT::TExecutor\n.
/// The two possible usages of the Map method are:\n
/// * Map(F func, unsigned nTimes): func is executed nTimes with no arguments
/// * Map(F func, T& args): func is executed on each element of the collection of arguments args
///
/// For either signature, func is executed as many times as needed by a pool of
/// nThreads threads; It defaults to the number of cores.\n
/// A collection containing the result of each execution is returned.\n
/// **Note:** the user is responsible for the deletion of any object that might
/// be created upon execution of func, returned objects included: ROOT::TThreadExecutor never
/// deletes what it returns, it simply forgets it.\n
///
/// \param func
/// \parblock
/// a lambda expression, an std::function, a loaded macro, a
/// functor class or a function that takes zero arguments (for the first signature)
/// or one (for the second signature).
/// \endparblock
/// \param args
/// \parblock
/// a standard vector, a ROOT::TSeq of integer type or an initializer list for the second signature.
/// An integer only for the first.
/// \endparblock
/// **Note:** in cases where the function to be executed takes more than
/// zero/one argument but all are fixed except zero/one, the function can be wrapped
/// in a lambda or via std::bind to give it the right signature.\n
///
/// #### Return value:
/// An std::vector. The elements in the container
/// will be the objects returned by func.
///
///
/// #### Examples:
///
/// ~~~{.cpp}
/// root[] ROOT::TThreadExecutor pool; auto hists = pool.Map(CreateHisto, 10);
/// root[] ROOT::TThreadExecutor pool(2); auto squares = pool.Map([](int a) { return a*a; }, {1,2,3});
/// ~~~
///
/// ### ROOT::TThreadExecutor::MapReduce
/// This set of methods behaves exactly like Map, but takes an additional
/// function as a third argument. This function is applied to the set of
/// objects returned by the corresponding Map execution to "squash" them
/// to a single object. This function should be independent of the size of
/// the vector returned by Map due to optimization of the number of chunks.
///
/// If this function is a binary operator, the "squashing" will be performed in parallel.
/// This is exclusive to ROOT::TThreadExecutor and not any other ROOT::TExecutor-derived classes.\n
/// An integer can be passed as the fourth argument indicating the number of chunks we want to divide our work in.
/// This may be useful to avoid the overhead introduced when running really short tasks.
///
/// #### Examples:
/// ~~~{.cpp}
/// root[] ROOT::TThreadExecutor pool; auto ten = pool.MapReduce([]() { return 1; }, 10, [](std::vector<int> v) { return std::accumulate(v.begin(), v.end(), 0); })
/// root[] ROOT::TThreadExecutor pool; auto hist = pool.MapReduce(CreateAndFillHists, 10, PoolUtils::ReduceObjects);
/// ~~~
///
//////////////////////////////////////////////////////////////////////////
/*
VERY IMPORTANT NOTE ABOUT WORK ISOLATION
We enclose the parallel_for and parallel_reduce invocations in a
task_arena::isolate because we want to prevent a thread to start executing an
outer task when the task it's running spawned subtasks, e.g. with a parallel_for,
and is waiting on inner tasks to be completed.
While this change has a negligible performance impact, it has benefits for
several applications, for example big parallelised HEP frameworks and
RDataFrame analyses.
- For HEP Frameworks, without work isolation, it can happen that a huge
framework task is pulled by a yielding ROOT task.
This causes to delay the processing of the event which is interrupted by the
long task.
For example, work isolation avoids that during the wait due to the parallel
flushing of baskets, a very long simulation task is pulled in by the idle task.
- For RDataFrame analyses we want to guarantee that each entry is processed from
the beginning to the end without TBB interrupting it to pull in other work items.
As a corollary, the usage of ROOT (or TBB in work isolation mode) in actions
and transformations guarantee that each entry is processed from the beginning to
the end without being interrupted by the processing of outer tasks.
*/
namespace ROOT {
namespace Internal {
/// A helper function to implement the TThreadExecutor::ParallelReduce methods
template<typename T>
static T ParallelReduceHelper(const std::vector<T> &objs, const std::function<T(T a, T b)> &redfunc)
{
using BRange_t = tbb::blocked_range<decltype(objs.begin())>;
auto pred = [redfunc](BRange_t const & range, T init) {
return std::accumulate(range.begin(), range.end(), init, redfunc);
};
BRange_t objRange(objs.begin(), objs.end());
return tbb::this_task_arena::isolate([&] {
return tbb::parallel_reduce(objRange, T{}, pred, redfunc);
});
}
} // End NS Internal
//////////////////////////////////////////////////////////////////////////
/// Class constructor.
/// If the scheduler is active (e.g. because another TThreadExecutor is in flight, or ROOT::EnableImplicitMT() was
/// called), work with the current pool of threads.
/// If not, initialize the pool of threads, spawning nThreads. nThreads' default value, 0, initializes the
/// pool with as many logical threads as are available in the system (see NLogicalCores in RTaskArenaWrapper.cxx).
///
/// At construction time, TThreadExecutor automatically enables ROOT's thread-safety locks as per calling
/// ROOT::EnableThreadSafety().
TThreadExecutor::TThreadExecutor(UInt_t nThreads)
{
fTaskArenaW = ROOT::Internal::GetGlobalTaskArena(nThreads);
}
void TThreadExecutor::ParallelFor(unsigned int start, unsigned int end, unsigned step,
const std::function<void(unsigned int i)> &f)
{
fTaskArenaW->Access().execute([&] {
tbb::this_task_arena::isolate([&] {
tbb::parallel_for(start, end, step, f);
});
});
}
double TThreadExecutor::ParallelReduce(const std::vector<double> &objs,
const std::function<double(double a, double b)> &redfunc)
{
return fTaskArenaW->Access().execute([&] { return ROOT::Internal::ParallelReduceHelper<double>(objs, redfunc); });
}
float TThreadExecutor::ParallelReduce(const std::vector<float> &objs,
const std::function<float(float a, float b)> &redfunc)
{
return fTaskArenaW->Access().execute([&] { return ROOT::Internal::ParallelReduceHelper<float>(objs, redfunc); });
}
unsigned TThreadExecutor::GetPoolSize()
{
return fTaskArenaW->TaskArenaSize();
}
} // namespace ROOT
|
fix indentation
|
fix indentation
|
C++
|
lgpl-2.1
|
olifre/root,karies/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,olifre/root,karies/root,karies/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,karies/root,root-mirror/root,karies/root,olifre/root,karies/root,karies/root,root-mirror/root,karies/root,karies/root,olifre/root,root-mirror/root
|
a3cc199fc9a4c805ae8a532ac5755168e8a058e9
|
brotli/enc/prefix.cc
|
brotli/enc/prefix.cc
|
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Functions for encoding of integers into prefix codes the amount of extra
// bits, and the actual values of the extra bits.
#include "./prefix.h"
#include "./fast_log.h"
namespace brotli {
// Represents the range of values belonging to a prefix code:
// [offset, offset + 2^nbits)
struct PrefixCodeRange {
int offset;
int nbits;
};
static const PrefixCodeRange kBlockLengthPrefixCode[kNumBlockLenPrefixes] = {
{ 1, 2}, { 5, 2}, { 9, 2}, { 13, 2},
{ 17, 3}, { 25, 3}, { 33, 3}, { 41, 3},
{ 49, 4}, { 65, 4}, { 81, 4}, { 97, 4},
{ 113, 5}, { 145, 5}, { 177, 5}, { 209, 5},
{ 241, 6}, { 305, 6}, { 369, 7}, { 497, 8},
{ 753, 9}, { 1265, 10}, {2289, 11}, {4337, 12},
{8433, 13}, {16625, 24}
};
static const PrefixCodeRange kInsertLengthPrefixCode[kNumInsertLenPrefixes] = {
{ 0, 0}, { 1, 0}, { 2, 0}, { 3, 0},
{ 4, 0}, { 5, 0}, { 6, 1}, { 8, 1},
{ 10, 2}, { 14, 2}, { 18, 3}, { 26, 3},
{ 34, 4}, { 50, 4}, { 66, 5}, { 98, 5},
{ 130, 6}, { 194, 7}, { 322, 8}, { 578, 9},
{1090, 10}, {2114, 12}, {6210, 14}, {22594, 24},
};
static const PrefixCodeRange kCopyLengthPrefixCode[kNumCopyLenPrefixes] = {
{ 2, 0}, { 3, 0}, { 4, 0}, { 5, 0},
{ 6, 0}, { 7, 0}, { 8, 0}, { 9, 0},
{ 10, 1}, { 12, 1}, { 14, 2}, { 18, 2},
{ 22, 3}, { 30, 3}, { 38, 4}, { 54, 4},
{ 70, 5}, { 102, 5}, { 134, 6}, { 198, 7},
{326, 8}, { 582, 9}, {1094, 10}, {2118, 24},
};
static const int kInsertAndCopyRangeLut[9] = {
0, 1, 4, 2, 3, 6, 5, 7, 8,
};
static const int kInsertRangeLut[9] = {
0, 0, 1, 1, 0, 2, 1, 2, 2,
};
static const int kCopyRangeLut[9] = {
0, 1, 0, 1, 2, 0, 2, 1, 2,
};
int InsertLengthPrefix(int length) {
for (int i = 0; i < kNumInsertLenPrefixes; ++i) {
const PrefixCodeRange& range = kInsertLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int CopyLengthPrefix(int length) {
for (int i = 0; i < kNumCopyLenPrefixes; ++i) {
const PrefixCodeRange& range = kCopyLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int CommandPrefix(int insert_length, int copy_length) {
if (copy_length == 0) {
copy_length = 3;
}
int insert_prefix = InsertLengthPrefix(insert_length);
int copy_prefix = CopyLengthPrefix(copy_length);
int range_idx = 3 * (insert_prefix >> 3) + (copy_prefix >> 3);
return ((kInsertAndCopyRangeLut[range_idx] << 6) +
((insert_prefix & 7)) + ((copy_prefix & 7) << 3));
}
int InsertLengthExtraBits(int code) {
int insert_code = (kInsertRangeLut[code >> 6] << 3) + ((code >> 3) & 7);
return kInsertLengthPrefixCode[insert_code].nbits;
}
int InsertLengthOffset(int code) {
int insert_code = (kInsertRangeLut[code >> 6] << 3) + ((code >> 3) & 7);
return kInsertLengthPrefixCode[insert_code].offset;
}
int CopyLengthExtraBits(int code) {
int copy_code = (kCopyRangeLut[code >> 6] << 3) + (code & 7);
return kCopyLengthPrefixCode[copy_code].nbits;
}
int CopyLengthOffset(int code) {
int copy_code = (kCopyRangeLut[code >> 6] << 3) + (code & 7);
return kCopyLengthPrefixCode[copy_code].offset;
}
void PrefixEncodeCopyDistance(int distance_code,
int num_direct_codes,
int postfix_bits,
uint16_t* code,
int* nbits,
uint32_t* extra_bits) {
distance_code -= 1;
if (distance_code < kNumDistanceShortCodes + num_direct_codes) {
*code = distance_code;
*nbits = 0;
*extra_bits = 0;
return;
}
distance_code -= kNumDistanceShortCodes + num_direct_codes;
distance_code += (1 << (postfix_bits + 2));
int bucket = Log2Floor(distance_code) - 1;
int postfix_mask = (1 << postfix_bits) - 1;
int postfix = distance_code & postfix_mask;
int prefix = (distance_code >> bucket) & 1;
int offset = (2 + prefix) << bucket;
*nbits = bucket - postfix_bits;
*code = kNumDistanceShortCodes + num_direct_codes +
((2 * (*nbits - 1) + prefix) << postfix_bits) + postfix;
*extra_bits = (distance_code - offset) >> postfix_bits;
}
int BlockLengthPrefix(int length) {
for (int i = 0; i < kNumBlockLenPrefixes; ++i) {
const PrefixCodeRange& range = kBlockLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int BlockLengthExtraBits(int length_code) {
return kBlockLengthPrefixCode[length_code].nbits;
}
int BlockLengthOffset(int length_code) {
return kBlockLengthPrefixCode[length_code].offset;
}
} // namespace brotli
|
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Functions for encoding of integers into prefix codes the amount of extra
// bits, and the actual values of the extra bits.
#include "./prefix.h"
#include "./fast_log.h"
namespace brotli {
// Represents the range of values belonging to a prefix code:
// [offset, offset + 2^nbits)
struct PrefixCodeRange {
int offset;
int nbits;
};
static const PrefixCodeRange kBlockLengthPrefixCode[kNumBlockLenPrefixes] = {
{ 1, 2}, { 5, 2}, { 9, 2}, { 13, 2},
{ 17, 3}, { 25, 3}, { 33, 3}, { 41, 3},
{ 49, 4}, { 65, 4}, { 81, 4}, { 97, 4},
{ 113, 5}, { 145, 5}, { 177, 5}, { 209, 5},
{ 241, 6}, { 305, 6}, { 369, 7}, { 497, 8},
{ 753, 9}, { 1265, 10}, {2289, 11}, {4337, 12},
{8433, 13}, {16625, 24}
};
static const PrefixCodeRange kInsertLengthPrefixCode[kNumInsertLenPrefixes] = {
{ 0, 0}, { 1, 0}, { 2, 0}, { 3, 0},
{ 4, 0}, { 5, 0}, { 6, 1}, { 8, 1},
{ 10, 2}, { 14, 2}, { 18, 3}, { 26, 3},
{ 34, 4}, { 50, 4}, { 66, 5}, { 98, 5},
{ 130, 6}, { 194, 7}, { 322, 8}, { 578, 9},
{1090, 10}, {2114, 12}, {6210, 14}, {22594, 24},
};
static const PrefixCodeRange kCopyLengthPrefixCode[kNumCopyLenPrefixes] = {
{ 2, 0}, { 3, 0}, { 4, 0}, { 5, 0},
{ 6, 0}, { 7, 0}, { 8, 0}, { 9, 0},
{ 10, 1}, { 12, 1}, { 14, 2}, { 18, 2},
{ 22, 3}, { 30, 3}, { 38, 4}, { 54, 4},
{ 70, 5}, { 102, 5}, { 134, 6}, { 198, 7},
{326, 8}, { 582, 9}, {1094, 10}, {2118, 24},
};
static const int kInsertAndCopyRangeLut[9] = {
0, 1, 4, 2, 3, 6, 5, 7, 8,
};
static const int kInsertRangeLut[9] = {
0, 0, 1, 1, 0, 2, 1, 2, 2,
};
static const int kCopyRangeLut[9] = {
0, 1, 0, 1, 2, 0, 2, 1, 2,
};
int InsertLengthPrefix(int length) {
for (int i = 0; i < kNumInsertLenPrefixes; ++i) {
const PrefixCodeRange& range = kInsertLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int CopyLengthPrefix(int length) {
for (int i = 0; i < kNumCopyLenPrefixes; ++i) {
const PrefixCodeRange& range = kCopyLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int CommandPrefix(int insert_length, int copy_length) {
if (copy_length == 0) {
copy_length = 3;
}
int insert_prefix = InsertLengthPrefix(insert_length);
int copy_prefix = CopyLengthPrefix(copy_length);
int range_idx = 3 * (insert_prefix >> 3) + (copy_prefix >> 3);
return ((kInsertAndCopyRangeLut[range_idx] << 6) +
((insert_prefix & 7) << 3) + (copy_prefix & 7));
}
int InsertLengthExtraBits(int code) {
int insert_code = (kInsertRangeLut[code >> 6] << 3) + ((code >> 3) & 7);
return kInsertLengthPrefixCode[insert_code].nbits;
}
int InsertLengthOffset(int code) {
int insert_code = (kInsertRangeLut[code >> 6] << 3) + ((code >> 3) & 7);
return kInsertLengthPrefixCode[insert_code].offset;
}
int CopyLengthExtraBits(int code) {
int copy_code = (kCopyRangeLut[code >> 6] << 3) + (code & 7);
return kCopyLengthPrefixCode[copy_code].nbits;
}
int CopyLengthOffset(int code) {
int copy_code = (kCopyRangeLut[code >> 6] << 3) + (code & 7);
return kCopyLengthPrefixCode[copy_code].offset;
}
void PrefixEncodeCopyDistance(int distance_code,
int num_direct_codes,
int postfix_bits,
uint16_t* code,
int* nbits,
uint32_t* extra_bits) {
distance_code -= 1;
if (distance_code < kNumDistanceShortCodes + num_direct_codes) {
*code = distance_code;
*nbits = 0;
*extra_bits = 0;
return;
}
distance_code -= kNumDistanceShortCodes + num_direct_codes;
distance_code += (1 << (postfix_bits + 2));
int bucket = Log2Floor(distance_code) - 1;
int postfix_mask = (1 << postfix_bits) - 1;
int postfix = distance_code & postfix_mask;
int prefix = (distance_code >> bucket) & 1;
int offset = (2 + prefix) << bucket;
*nbits = bucket - postfix_bits;
*code = kNumDistanceShortCodes + num_direct_codes +
((2 * (*nbits - 1) + prefix) << postfix_bits) + postfix;
*extra_bits = (distance_code - offset) >> postfix_bits;
}
int BlockLengthPrefix(int length) {
for (int i = 0; i < kNumBlockLenPrefixes; ++i) {
const PrefixCodeRange& range = kBlockLengthPrefixCode[i];
if (length >= range.offset && length < range.offset + (1 << range.nbits)) {
return i;
}
}
return -1;
}
int BlockLengthExtraBits(int length_code) {
return kBlockLengthPrefixCode[length_code].nbits;
}
int BlockLengthOffset(int length_code) {
return kBlockLengthPrefixCode[length_code].offset;
}
} // namespace brotli
|
revert change to command coding (merge with change later)
|
revert change to command coding (merge with change later)
|
C++
|
bsd-3-clause
|
robryk/font-compression-reference,robryk/font-compression-reference,robryk/font-compression-reference
|
954c1a1e8e35b545c261d1105dcab8c6710a7c0f
|
core/meta/src/TSchemaRuleSet.cxx
|
core/meta/src/TSchemaRuleSet.cxx
|
// @(#)root/core:$Id$
// author: Lukasz Janyst <[email protected]>
#include "TSchemaRuleSet.h"
#include "TSchemaRule.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TClass.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TVirtualCollectionProxy.h"
#include "TClassEdit.h"
ClassImp(TSchemaRule)
using namespace ROOT;
//------------------------------------------------------------------------------
TSchemaRuleSet::TSchemaRuleSet(): fPersistentRules( 0 ), fRemainingRules( 0 ),
fAllRules( 0 ), fVersion(-3), fCheckSum( 0 )
{
// Default constructor.
fPersistentRules = new TObjArray();
fRemainingRules = new TObjArray();
fAllRules = new TObjArray();
fAllRules->SetOwner( kTRUE );
}
//------------------------------------------------------------------------------
TSchemaRuleSet::~TSchemaRuleSet()
{
// Destructor.
delete fPersistentRules;
delete fRemainingRules;
delete fAllRules;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::ls(Option_t *) const
{
// The ls function lists the contents of a class on stdout. Ls output
// is typically much less verbose then Dump().
TROOT::IndentLevel();
cout << "TSchemaRuleSet for " << fClassName << ":\n";
TROOT::IncreaseDirLevel();
TObject *object = 0;
TIter next(fPersistentRules);
while ((object = next())) {
object->ls(fClassName);
}
TROOT::DecreaseDirLevel();
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::AddRules( TSchemaRuleSet* /* rules */, EConsistencyCheck /* checkConsistency */, TString * /* errmsg */ )
{
return kFALSE;
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::AddRule( TSchemaRule* rule, EConsistencyCheck checkConsistency, TString *errmsg )
{
// The consistency check always fails if the TClass object was not set!
// if checkConsistency is:
// kNoCheck: no check is done, register the rule as is
// kCheckConflict: check only for conflicting rules
// kCheckAll: check for conflict and check for rule about members that are not in the current class layout.
// return kTRUE if the layout is accepted, in which case we take ownership of
// the rule object.
// return kFALSE if the rule failed one of the test, the rule now needs to be deleted by the caller.
//---------------------------------------------------------------------------
// Cannot verify the consistency if the TClass object is not present
//---------------------------------------------------------------------------
if( (checkConsistency != kNoCheck) && !fClass )
return kFALSE;
if( !rule->IsValid() )
return kFALSE;
//---------------------------------------------------------------------------
// If we don't check the consistency then we should just add the object
//---------------------------------------------------------------------------
if( checkConsistency == kNoCheck ) {
if( rule->GetEmbed() )
fPersistentRules->Add( rule );
else
fRemainingRules->Add( rule );
fAllRules->Add( rule );
return kTRUE;
}
//---------------------------------------------------------------------------
// Check if all of the target data members specified in the rule are
// present int the target class
//---------------------------------------------------------------------------
TObject* obj;
// Check only if we have some information about the class, otherwise we have
// nothing to check against
if( rule->GetTarget() && !(fClass->TestBit(TClass::kIsEmulation) && (fClass->GetStreamerInfos()==0 || fClass->GetStreamerInfos()->GetEntries()==0)) ) {
TObjArrayIter titer( rule->GetTarget() );
while( (obj = titer.Next()) ) {
TObjString* str = (TObjString*)obj;
if( !fClass->GetDataMember( str->GetString() ) && !fClass->GetBaseClass( str->GetString() ) ) {
if (checkConsistency == kCheckAll) {
if (errmsg) {
errmsg->Form("the target member (%s) is unknown",str->GetString().Data());
}
return kFALSE;
} else {
// We ignore the rules that do not apply ...
delete rule;
return kTRUE;
}
}
}
}
//---------------------------------------------------------------------------
// Check if there is a rule conflicting with this one
//---------------------------------------------------------------------------
const TObjArray* rules = FindRules( rule->GetSourceClass() );
TObjArrayIter it( rules );
TSchemaRule *r;
while( (obj = it.Next()) ) {
r = (TSchemaRule *) obj;
if( rule->Conflicts( r ) ) {
delete rules;
if ( *r == *rule) {
// The rules are duplicate from each other,
// just ignore the new ones.
if (errmsg) {
*errmsg = "it conflicts with one of the other rules";
}
delete rule;
return kTRUE;
}
if (errmsg) {
*errmsg = "The existing rule is:\n ";
r->AsString(*errmsg,"s");
*errmsg += "\nand the ignored rule is:\n ";
rule->AsString(*errmsg);
*errmsg += ".\n";
}
return kFALSE;
}
}
delete rules;
//---------------------------------------------------------------------------
// No conflicts - insert the rules
//---------------------------------------------------------------------------
if( rule->GetEmbed() )
fPersistentRules->Add( rule );
else
fRemainingRules->Add( rule );
fAllRules->Add( rule );
return kTRUE;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::AsString(TString &out) const
{
// Fill the string 'out' with the string representation of the rule.
TObjArrayIter it( fAllRules );
TSchemaRule *rule;
while( (rule = (TSchemaRule*)it.Next()) ) {
rule->AsString(out);
out += "\n";
}
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::HasRuleWithSourceClass( const TString &source ) const
{
// Return True if we have any rule whose source class is 'source'.
TObjArrayIter it( fAllRules );
TObject *obj;
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source )
return kTRUE;
}
// There was no explicit rule, let's see we have implicit rules.
if (fClass->GetCollectionProxy()) {
if (fClass->GetCollectionProxy()->GetValueClass() == 0) {
if (fClass->GetCollectionProxy()->GetCollectionType() == TClassEdit::kVector
|| (fClass->GetCollectionProxy()->GetProperties() & TVirtualCollectionProxy::kIsEmulated)) {
// We have a numeric collection, let see if the target is
// also a numeric collection (humm just a vector for now)
TClass *src = TClass::GetClass(source);
if (src && src->GetCollectionProxy() &&
src->GetCollectionProxy()->HasPointers() == fClass->GetCollectionProxy()->HasPointers()) {
TVirtualCollectionProxy *proxy = src->GetCollectionProxy();
if (proxy->GetValueClass() == 0) {
return kTRUE;
}
}
}
} else {
TClass *vTargetClass = fClass->GetCollectionProxy()->GetValueClass();
TClass *src = TClass::GetClass(source);
if (vTargetClass->GetSchemaRules()) {
if (src && src->GetCollectionProxy() &&
src->GetCollectionProxy()->HasPointers() == fClass->GetCollectionProxy()->HasPointers()) {
TClass *vSourceClass = src->GetCollectionProxy()->GetValueClass();
if (vSourceClass) {
return vTargetClass->GetSchemaRules()->HasRuleWithSourceClass( vSourceClass->GetName() );
}
}
}
}
}
return kFALSE;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::FindRules( const TString &source ) const
{
// Return all the rules that are about the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TObjArray* arr = new TObjArray();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source )
arr->Add( rule );
}
// Le't's see we have implicit rules.
if (fClass->GetCollectionProxy()) {
if (fClass->GetCollectionProxy()->GetValueClass() == 0
&& (fClass->GetCollectionProxy()->GetCollectionType() == TClassEdit::kVector
|| (fClass->GetCollectionProxy()->GetProperties() & TVirtualCollectionProxy::kIsEmulated))) {
// We have a numeric collection, let see if the target is
// also a numeric collection (humm just a vector for now)
TClass *src = TClass::GetClass(source);
if (src && src->GetCollectionProxy()) {
TVirtualCollectionProxy *proxy = src->GetCollectionProxy();
if (proxy->GetValueClass() == 0) {
// ... would need to check if we already have
// the rule (or any rule?)
}
}
}
}
return arr;
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, Int_t version ) const
{
// Return all the rules that applies to the specified version of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && rule->TestVersion( version ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, UInt_t checksum ) const
{
// Return all the rules that applies to the specified checksum of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && rule->TestChecksum( checksum ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, Int_t version, UInt_t checksum ) const
{
// Return all the rules that applies to the specified version OR checksum of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && ( rule->TestVersion( version ) || rule->TestChecksum( checksum ) ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
TClass* TSchemaRuleSet::GetClass()
{
return fClass;
}
//------------------------------------------------------------------------------
UInt_t TSchemaRuleSet::GetClassCheckSum() const
{
if (fCheckSum == 0 && fClass) {
const_cast<TSchemaRuleSet*>(this)->fCheckSum = fClass->GetCheckSum();
}
return fCheckSum;
}
//------------------------------------------------------------------------------
TString TSchemaRuleSet::GetClassName() const
{
return fClassName;
}
//------------------------------------------------------------------------------
Int_t TSchemaRuleSet::GetClassVersion() const
{
return fVersion;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::GetRules() const
{
return fAllRules;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::GetPersistentRules() const
{
return fPersistentRules;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::RemoveRule( TSchemaRule* rule )
{
// Remove given rule from the set - the rule is not being deleted!
fPersistentRules->Remove( rule );
fRemainingRules->Remove( rule );
fAllRules->Remove( rule );
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::RemoveRules( TObjArray* rules )
{
// remove given array of rules from the set - the rules are not being deleted!
TObject* obj;
TObjArrayIter it( rules );
while( (obj = it.Next()) ) {
fPersistentRules->Remove( obj );
fRemainingRules->Remove( obj );
fAllRules->Remove( obj );
}
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::SetClass( TClass* cls )
{
// Set the TClass associated with this rule set.
fClass = cls;
fClassName = cls->GetName();
fVersion = cls->GetClassVersion();
}
//------------------------------------------------------------------------------
const TSchemaRule* TSchemaMatch::GetRuleWithSource( const TString& name ) const
{
// Return the rule that has 'name' as a source.
for( Int_t i = 0; i < GetEntries(); ++i ) {
TSchemaRule* rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasSource( name ) ) return rule;
}
return 0;
}
//------------------------------------------------------------------------------
const TSchemaRule* TSchemaMatch::GetRuleWithTarget( const TString& name ) const
{
// Return the rule that has 'name' as a target.
for( Int_t i=0; i<GetEntries(); ++i) {
ROOT::TSchemaRule *rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasTarget( name ) ) return rule;
}
return 0;
}
//------------------------------------------------------------------------------
Bool_t TSchemaMatch::HasRuleWithSource( const TString& name, Bool_t needingAlloc ) const
{
// Return true if the set of rules has at least one rule that has the data
// member named 'name' as a source.
// If needingAlloc is true, only the rule that requires the data member to
// be cached will be taken in consideration.
for( Int_t i = 0; i < GetEntries(); ++i ) {
TSchemaRule* rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasSource( name ) ) {
if (needingAlloc) {
const TObjArray *targets = rule->GetTarget();
if (targets && (targets->GetEntries() > 1 || targets->GetEntries()==0) ) {
return kTRUE;
}
if (targets && name != targets->UncheckedAt(0)->GetName() ) {
return kTRUE;
}
// If the rule has the same source and target and does not
// have any actions, then it does not need allocation.
if (rule->GetReadFunctionPointer() || rule->GetReadRawFunctionPointer()) {
return kTRUE;
}
} else {
return kTRUE;
}
}
}
return kFALSE;
}
//------------------------------------------------------------------------------
Bool_t TSchemaMatch::HasRuleWithTarget( const TString& name, Bool_t willset ) const
{
// Return true if the set of rules has at least one rule that has the data
// member named 'name' as a target.
// If willset is true, only the rule that will set the value of the data member.
for( Int_t i=0; i<GetEntries(); ++i) {
ROOT::TSchemaRule *rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasTarget( name ) ) {
if (willset) {
const TObjArray *targets = rule->GetTarget();
if (targets && (targets->GetEntries() > 1 || targets->GetEntries()==0) ) {
return kTRUE;
}
const TObjArray *sources = rule->GetSource();
if (sources && (sources->GetEntries() > 1 || sources->GetEntries()==0) ) {
return kTRUE;
}
if (sources && name != sources->UncheckedAt(0)->GetName() ) {
return kTRUE;
}
// If the rule has the same source and target and does not
// have any actions, then it will not directly set the value.
if (rule->GetReadFunctionPointer() || rule->GetReadRawFunctionPointer()) {
return kTRUE;
}
} else {
return kTRUE;
}
}
}
return kFALSE;
}
//______________________________________________________________________________
void TSchemaRuleSet::Streamer(TBuffer &R__b)
{
// Stream an object of class ROOT::TSchemaRuleSet.
if (R__b.IsReading()) {
R__b.ReadClassBuffer(ROOT::TSchemaRuleSet::Class(),this);
fAllRules->Clear();
fAllRules->AddAll(fPersistentRules);
} else {
GetClassCheckSum();
R__b.WriteClassBuffer(ROOT::TSchemaRuleSet::Class(),this);
}
}
|
// @(#)root/core:$Id$
// author: Lukasz Janyst <[email protected]>
#include "TSchemaRuleSet.h"
#include "TSchemaRule.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TClass.h"
#include "TROOT.h"
#include "Riostream.h"
#include "TVirtualCollectionProxy.h"
#include "TClassEdit.h"
ClassImp(TSchemaRule)
using namespace ROOT;
//------------------------------------------------------------------------------
TSchemaRuleSet::TSchemaRuleSet(): fPersistentRules( 0 ), fRemainingRules( 0 ),
fAllRules( 0 ), fVersion(-3), fCheckSum( 0 )
{
// Default constructor.
fPersistentRules = new TObjArray();
fRemainingRules = new TObjArray();
fAllRules = new TObjArray();
fAllRules->SetOwner( kTRUE );
}
//------------------------------------------------------------------------------
TSchemaRuleSet::~TSchemaRuleSet()
{
// Destructor.
delete fPersistentRules;
delete fRemainingRules;
delete fAllRules;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::ls(Option_t *) const
{
// The ls function lists the contents of a class on stdout. Ls output
// is typically much less verbose then Dump().
TROOT::IndentLevel();
cout << "TSchemaRuleSet for " << fClassName << ":\n";
TROOT::IncreaseDirLevel();
TObject *object = 0;
TIter next(fPersistentRules);
while ((object = next())) {
object->ls(fClassName);
}
TROOT::DecreaseDirLevel();
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::AddRules( TSchemaRuleSet* /* rules */, EConsistencyCheck /* checkConsistency */, TString * /* errmsg */ )
{
return kFALSE;
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::AddRule( TSchemaRule* rule, EConsistencyCheck checkConsistency, TString *errmsg )
{
// The consistency check always fails if the TClass object was not set!
// if checkConsistency is:
// kNoCheck: no check is done, register the rule as is
// kCheckConflict: check only for conflicting rules
// kCheckAll: check for conflict and check for rule about members that are not in the current class layout.
// return kTRUE if the layout is accepted, in which case we take ownership of
// the rule object.
// return kFALSE if the rule failed one of the test, the rule now needs to be deleted by the caller.
//---------------------------------------------------------------------------
// Cannot verify the consistency if the TClass object is not present
//---------------------------------------------------------------------------
if( (checkConsistency != kNoCheck) && !fClass )
return kFALSE;
if( !rule->IsValid() )
return kFALSE;
//---------------------------------------------------------------------------
// If we don't check the consistency then we should just add the object
//---------------------------------------------------------------------------
if( checkConsistency == kNoCheck ) {
if( rule->GetEmbed() )
fPersistentRules->Add( rule );
else
fRemainingRules->Add( rule );
fAllRules->Add( rule );
return kTRUE;
}
//---------------------------------------------------------------------------
// Check if all of the target data members specified in the rule are
// present int the target class
//---------------------------------------------------------------------------
TObject* obj;
// Check only if we have some information about the class, otherwise we have
// nothing to check against
if( rule->GetTarget() && !(fClass->TestBit(TClass::kIsEmulation) && (fClass->GetStreamerInfos()==0 || fClass->GetStreamerInfos()->GetEntries()==0)) ) {
TObjArrayIter titer( rule->GetTarget() );
while( (obj = titer.Next()) ) {
TObjString* str = (TObjString*)obj;
if( !fClass->GetDataMember( str->GetString() ) && !fClass->GetBaseClass( str->GetString() ) ) {
if (checkConsistency == kCheckAll) {
if (errmsg) {
errmsg->Form("the target member (%s) is unknown",str->GetString().Data());
}
return kFALSE;
} else {
// We ignore the rules that do not apply ...
delete rule;
return kTRUE;
}
}
}
}
//---------------------------------------------------------------------------
// Check if there is a rule conflicting with this one
//---------------------------------------------------------------------------
const TObjArray* rules = FindRules( rule->GetSourceClass() );
TObjArrayIter it( rules );
TSchemaRule *r;
while( (obj = it.Next()) ) {
r = (TSchemaRule *) obj;
if( rule->Conflicts( r ) ) {
delete rules;
if ( *r == *rule) {
// The rules are duplicate from each other,
// just ignore the new ones.
if (errmsg) {
*errmsg = "it conflicts with one of the other rules";
}
delete rule;
return kTRUE;
}
if (errmsg) {
*errmsg = "The existing rule is:\n ";
r->AsString(*errmsg,"s");
*errmsg += "\nand the ignored rule is:\n ";
rule->AsString(*errmsg);
*errmsg += ".\n";
}
return kFALSE;
}
}
delete rules;
//---------------------------------------------------------------------------
// No conflicts - insert the rules
//---------------------------------------------------------------------------
if( rule->GetEmbed() )
fPersistentRules->Add( rule );
else
fRemainingRules->Add( rule );
fAllRules->Add( rule );
return kTRUE;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::AsString(TString &out) const
{
// Fill the string 'out' with the string representation of the rule.
TObjArrayIter it( fAllRules );
TSchemaRule *rule;
while( (rule = (TSchemaRule*)it.Next()) ) {
rule->AsString(out);
out += "\n";
}
}
//------------------------------------------------------------------------------
Bool_t TSchemaRuleSet::HasRuleWithSourceClass( const TString &source ) const
{
// Return True if we have any rule whose source class is 'source'.
TObjArrayIter it( fAllRules );
TObject *obj;
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source )
return kTRUE;
}
// There was no explicit rule, let's see we have implicit rules.
if (fClass->GetCollectionProxy()) {
if (fClass->GetCollectionProxy()->GetValueClass() == 0) {
// We have a numeric collection, let see if the target is
// also a numeric collection.
TClass *src = TClass::GetClass(source);
if (src && src->GetCollectionProxy() &&
src->GetCollectionProxy()->HasPointers() == fClass->GetCollectionProxy()->HasPointers()) {
TVirtualCollectionProxy *proxy = src->GetCollectionProxy();
if (proxy->GetValueClass() == 0) {
return kTRUE;
}
}
} else {
TClass *vTargetClass = fClass->GetCollectionProxy()->GetValueClass();
TClass *src = TClass::GetClass(source);
if (vTargetClass->GetSchemaRules()) {
if (src && src->GetCollectionProxy() &&
src->GetCollectionProxy()->HasPointers() == fClass->GetCollectionProxy()->HasPointers()) {
TClass *vSourceClass = src->GetCollectionProxy()->GetValueClass();
if (vSourceClass) {
return vTargetClass->GetSchemaRules()->HasRuleWithSourceClass( vSourceClass->GetName() );
}
}
}
}
}
return kFALSE;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::FindRules( const TString &source ) const
{
// Return all the rules that are about the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TObjArray* arr = new TObjArray();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source )
arr->Add( rule );
}
// Le't's see we have implicit rules.
if (fClass->GetCollectionProxy()) {
if (fClass->GetCollectionProxy()->GetValueClass() == 0
&& (fClass->GetCollectionProxy()->GetCollectionType() == TClassEdit::kVector
|| (fClass->GetCollectionProxy()->GetProperties() & TVirtualCollectionProxy::kIsEmulated))) {
// We have a numeric collection, let see if the target is
// also a numeric collection (humm just a vector for now)
TClass *src = TClass::GetClass(source);
if (src && src->GetCollectionProxy()) {
TVirtualCollectionProxy *proxy = src->GetCollectionProxy();
if (proxy->GetValueClass() == 0) {
// ... would need to check if we already have
// the rule (or any rule?)
}
}
}
}
return arr;
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, Int_t version ) const
{
// Return all the rules that applies to the specified version of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && rule->TestVersion( version ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, UInt_t checksum ) const
{
// Return all the rules that applies to the specified checksum of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && rule->TestChecksum( checksum ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
const TSchemaMatch* TSchemaRuleSet::FindRules( const TString &source, Int_t version, UInt_t checksum ) const
{
// Return all the rules that applies to the specified version OR checksum of the given 'source' class.
// User has to delete the returned array
TObject* obj;
TObjArrayIter it( fAllRules );
TSchemaMatch* arr = new TSchemaMatch();
arr->SetOwner( kFALSE );
while( (obj = it.Next()) ) {
TSchemaRule* rule = (TSchemaRule*)obj;
if( rule->GetSourceClass() == source && ( rule->TestVersion( version ) || rule->TestChecksum( checksum ) ) )
arr->Add( rule );
}
if( arr->GetEntriesFast() )
return arr;
else {
delete arr;
return 0;
}
}
//------------------------------------------------------------------------------
TClass* TSchemaRuleSet::GetClass()
{
return fClass;
}
//------------------------------------------------------------------------------
UInt_t TSchemaRuleSet::GetClassCheckSum() const
{
if (fCheckSum == 0 && fClass) {
const_cast<TSchemaRuleSet*>(this)->fCheckSum = fClass->GetCheckSum();
}
return fCheckSum;
}
//------------------------------------------------------------------------------
TString TSchemaRuleSet::GetClassName() const
{
return fClassName;
}
//------------------------------------------------------------------------------
Int_t TSchemaRuleSet::GetClassVersion() const
{
return fVersion;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::GetRules() const
{
return fAllRules;
}
//------------------------------------------------------------------------------
const TObjArray* TSchemaRuleSet::GetPersistentRules() const
{
return fPersistentRules;
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::RemoveRule( TSchemaRule* rule )
{
// Remove given rule from the set - the rule is not being deleted!
fPersistentRules->Remove( rule );
fRemainingRules->Remove( rule );
fAllRules->Remove( rule );
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::RemoveRules( TObjArray* rules )
{
// remove given array of rules from the set - the rules are not being deleted!
TObject* obj;
TObjArrayIter it( rules );
while( (obj = it.Next()) ) {
fPersistentRules->Remove( obj );
fRemainingRules->Remove( obj );
fAllRules->Remove( obj );
}
}
//------------------------------------------------------------------------------
void TSchemaRuleSet::SetClass( TClass* cls )
{
// Set the TClass associated with this rule set.
fClass = cls;
fClassName = cls->GetName();
fVersion = cls->GetClassVersion();
}
//------------------------------------------------------------------------------
const TSchemaRule* TSchemaMatch::GetRuleWithSource( const TString& name ) const
{
// Return the rule that has 'name' as a source.
for( Int_t i = 0; i < GetEntries(); ++i ) {
TSchemaRule* rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasSource( name ) ) return rule;
}
return 0;
}
//------------------------------------------------------------------------------
const TSchemaRule* TSchemaMatch::GetRuleWithTarget( const TString& name ) const
{
// Return the rule that has 'name' as a target.
for( Int_t i=0; i<GetEntries(); ++i) {
ROOT::TSchemaRule *rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasTarget( name ) ) return rule;
}
return 0;
}
//------------------------------------------------------------------------------
Bool_t TSchemaMatch::HasRuleWithSource( const TString& name, Bool_t needingAlloc ) const
{
// Return true if the set of rules has at least one rule that has the data
// member named 'name' as a source.
// If needingAlloc is true, only the rule that requires the data member to
// be cached will be taken in consideration.
for( Int_t i = 0; i < GetEntries(); ++i ) {
TSchemaRule* rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasSource( name ) ) {
if (needingAlloc) {
const TObjArray *targets = rule->GetTarget();
if (targets && (targets->GetEntries() > 1 || targets->GetEntries()==0) ) {
return kTRUE;
}
if (targets && name != targets->UncheckedAt(0)->GetName() ) {
return kTRUE;
}
// If the rule has the same source and target and does not
// have any actions, then it does not need allocation.
if (rule->GetReadFunctionPointer() || rule->GetReadRawFunctionPointer()) {
return kTRUE;
}
} else {
return kTRUE;
}
}
}
return kFALSE;
}
//------------------------------------------------------------------------------
Bool_t TSchemaMatch::HasRuleWithTarget( const TString& name, Bool_t willset ) const
{
// Return true if the set of rules has at least one rule that has the data
// member named 'name' as a target.
// If willset is true, only the rule that will set the value of the data member.
for( Int_t i=0; i<GetEntries(); ++i) {
ROOT::TSchemaRule *rule = (ROOT::TSchemaRule*)At(i);
if( rule->HasTarget( name ) ) {
if (willset) {
const TObjArray *targets = rule->GetTarget();
if (targets && (targets->GetEntries() > 1 || targets->GetEntries()==0) ) {
return kTRUE;
}
const TObjArray *sources = rule->GetSource();
if (sources && (sources->GetEntries() > 1 || sources->GetEntries()==0) ) {
return kTRUE;
}
if (sources && name != sources->UncheckedAt(0)->GetName() ) {
return kTRUE;
}
// If the rule has the same source and target and does not
// have any actions, then it will not directly set the value.
if (rule->GetReadFunctionPointer() || rule->GetReadRawFunctionPointer()) {
return kTRUE;
}
} else {
return kTRUE;
}
}
}
return kFALSE;
}
//______________________________________________________________________________
void TSchemaRuleSet::Streamer(TBuffer &R__b)
{
// Stream an object of class ROOT::TSchemaRuleSet.
if (R__b.IsReading()) {
R__b.ReadClassBuffer(ROOT::TSchemaRuleSet::Class(),this);
fAllRules->Clear();
fAllRules->AddAll(fPersistentRules);
} else {
GetClassCheckSum();
R__b.WriteClassBuffer(ROOT::TSchemaRuleSet::Class(),this);
}
}
|
Allow the implicit conversion from any type of numerical STL collection to any other type of numerical STL collection (e.g. vector<int> to list<float>)
|
Allow the implicit conversion from any type of numerical STL collection to any other type of numerical STL collection (e.g. vector<int> to list<float>)
git-svn-id: 9d02132d8e1217b86764d694e1605987040d84e5@49003 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
Dr15Jones/root,strykejern/TTreeReader,ffurano/root5,ffurano/root5,tc3t/qoot,tc3t/qoot,tc3t/qoot,kirbyherm/root-r-tools,strykejern/TTreeReader,tc3t/qoot,strykejern/TTreeReader,ffurano/root5,kirbyherm/root-r-tools,kirbyherm/root-r-tools,ffurano/root5,Dr15Jones/root,ffurano/root5,Dr15Jones/root,strykejern/TTreeReader,Dr15Jones/root,ffurano/root5,kirbyherm/root-r-tools,tc3t/qoot,ffurano/root5,Dr15Jones/root,strykejern/TTreeReader,tc3t/qoot,Dr15Jones/root,strykejern/TTreeReader,Dr15Jones/root,kirbyherm/root-r-tools,kirbyherm/root-r-tools,tc3t/qoot,kirbyherm/root-r-tools,tc3t/qoot,tc3t/qoot,tc3t/qoot,strykejern/TTreeReader
|
fcecfc065c901feb56db9ab19e03af471a2652ad
|
vhdlpp/vtype_stream.cc
|
vhdlpp/vtype_stream.cc
|
/*
* Copyright (c) 2011 Stephen Williams ([email protected])
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "vtype.h"
# include <typeinfo>
# include <cassert>
using namespace std;
void VType::write_to_stream(ostream&fd) const
{
fd << "/* UNKNOWN TYPE: " << typeid(*this).name() << " */";
}
void VTypeArray::write_to_stream(ostream&fd) const
{
// Special case: std_logic_vector
if (etype_ == primitive_STDLOGIC) {
fd << "std_logic_vector";
if (ranges_.size() > 0) {
assert(ranges_.size() < 2);
fd << " (" << ranges_[0].msb()
<< " downto " << ranges_[0].lsb() << ") ";
}
return;
}
fd << "array ";
if (ranges_.size() > 0) {
assert(ranges_.size() < 2);
fd << "(" << ranges_[0].msb()
<< " downto " << ranges_[0].lsb() << ") ";
}
fd << "of ";
etype_->write_to_stream(fd);
}
void VTypePrimitive::write_to_stream(ostream&fd) const
{
switch (type_) {
case INTEGER:
fd << "integer";
break;
case STDLOGIC:
fd << "std_logic";
break;
default:
assert(0);
fd << "/* PRIMITIVE: " << type_ << " */";
break;
}
}
|
/*
* Copyright (c) 2011 Stephen Williams ([email protected])
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "vtype.h"
# include <typeinfo>
# include <cassert>
using namespace std;
void VType::write_to_stream(ostream&fd) const
{
fd << "/* UNKNOWN TYPE: " << typeid(*this).name() << " */";
}
void VTypeArray::write_to_stream(ostream&fd) const
{
// Special case: std_logic_vector
if (etype_ == primitive_STDLOGIC) {
fd << "std_logic_vector";
if (ranges_.size() > 0) {
assert(ranges_.size() < 2);
fd << " (" << ranges_[0].msb()
<< " downto " << ranges_[0].lsb() << ") ";
}
return;
}
fd << "array ";
if (ranges_.size() > 0) {
assert(ranges_.size() < 2);
fd << "(" << ranges_[0].msb()
<< " downto " << ranges_[0].lsb() << ") ";
}
fd << "of ";
etype_->write_to_stream(fd);
}
void VTypePrimitive::write_to_stream(ostream&fd) const
{
switch (type_) {
case BIT:
fd << "bit";
break;
case INTEGER:
fd << "integer";
break;
case STDLOGIC:
fd << "std_logic";
break;
default:
assert(0);
fd << "/* PRIMITIVE: " << type_ << " */";
break;
}
}
|
Handle bit types in package library stream.
|
Handle bit types in package library stream.
|
C++
|
lgpl-2.1
|
CastMi/iverilog,CastMi/iverilog,CastMi/iverilog,themperek/iverilog,themperek/iverilog,themperek/iverilog
|
601ba4e4f8ebf4841d25ea9babf20011fa554295
|
src/ecru-config.cc
|
src/ecru-config.cc
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include "Hook.h"
#include "Config.h"
#include "ecru.h"
using namespace std;
void usage()
{
cerr << "usage: ecru-config variable_path" << endl;
cerr << "usage: ecru-config [-l|-s path]" << endl;
cerr << "usage: ecru-config [-v|-h]" << endl;
cerr << "usage: ecru-config -h [pre|post]" << endl;
exit(1);
}
void listConfigProfiles() {
//cout << "hello world" << endl;
Config *config = new Config();
string currentConfigFilename = config->getCurrentConfigFilename();
vector<string> configFiles = config->listConfigFiles();
for (unsigned int i = 0; i < configFiles.size(); i++) {
//cout.width(2);
if (configFiles[i] == currentConfigFilename) {
cout << "* ";
} else {
cout << " ";
}
cout << configFiles[i];
cout << endl;
}
delete config;
}
void setCurrentConfigFilename(string filename)
{
Config *config = new Config();
config->setCurrentConfigFilename(filename);
}
int main(int argc, char** argv) {
int ch;
bool generate = false;
string username;
string hpassword;
string hookType;
while ((ch = getopt(argc, argv, "gh:lp:s:u:v")) != -1) {
switch (ch) {
case 'g':
generate = true;
break;
case 'h':
hookType = string(optarg);
if ((hookType != "post") &&
(hookType != "pre")) {
usage();
exit(1);
}
break;
case 'l':
listConfigProfiles();
exit(0);
break;
case 'p':
hpassword = string(optarg);
break;
case 's':
setCurrentConfigFilename(optarg);
exit(0);
break;
case 'u':
username = string(optarg);
break;
case 'v':
ecru::version();
exit(0);
default:
usage();
}
}
argc -= optind;
argv += optind;
if (generate == true) {
cout << "Generating ecru configuration..." << endl;
if (username.length() == 0) {
cout << "Enter username: ";
cin >> username;
}
if (hpassword.length() == 0) {
cout << "Enter md5 hash of the password: ";
cin >> hpassword;
}
string configPath = Config::generate(username, hpassword);
cout << "Config file placed to: " << configPath << endl;
cout << "To install it, type: cp -r " << configPath << " ~/.ecru" << endl;
} else if (hookType.length() > 0) {
Hook *hook = new Hook();
vector<string> hooks;
if (hookType == "pre") {
hooks = hook->getPreHooks();
} else {
hooks = hook->getPostHooks();
}
for (unsigned int i = 0; i < hooks.size(); i++) {
cout << hooks[i] << endl;
}
} else {
if (argc < 1)
usage();
Config *config = new Config();
try {
cout << config->queryConfigProperty(argv[0]) << endl;
} catch (libconfig::SettingNotFoundException& ex) {
cerr << "Setting '" << argv[0];
cerr << "' was not found.";
cerr << endl;
exit(1);
}
}
return 0;
}
|
#include <iostream>
#include <cstdlib>
#include <vector>
#include "Hook.h"
#include "Config.h"
#include "ecru.h"
using namespace std;
void usage()
{
cerr << "usage: ecru-config variable_path" << endl;
cerr << "usage: ecru-config [-l|-s path]" << endl;
cerr << "usage: ecru-config -v" << endl;
cerr << "usage: ecru-config -h [pre|post]" << endl;
exit(1);
}
void listConfigProfiles() {
//cout << "hello world" << endl;
Config *config = new Config();
string currentConfigFilename = config->getCurrentConfigFilename();
vector<string> configFiles = config->listConfigFiles();
for (unsigned int i = 0; i < configFiles.size(); i++) {
//cout.width(2);
if (configFiles[i] == currentConfigFilename) {
cout << "* ";
} else {
cout << " ";
}
cout << configFiles[i];
cout << endl;
}
delete config;
}
void setCurrentConfigFilename(string filename)
{
Config *config = new Config();
config->setCurrentConfigFilename(filename);
}
int main(int argc, char** argv) {
int ch;
bool generate = false;
string username;
string hpassword;
string hookType;
while ((ch = getopt(argc, argv, "gh:lp:s:u:v")) != -1) {
switch (ch) {
case 'g':
generate = true;
break;
case 'h':
hookType = string(optarg);
if ((hookType != "post") &&
(hookType != "pre")) {
usage();
exit(1);
}
break;
case 'l':
listConfigProfiles();
exit(0);
break;
case 'p':
hpassword = string(optarg);
break;
case 's':
setCurrentConfigFilename(optarg);
exit(0);
break;
case 'u':
username = string(optarg);
break;
case 'v':
ecru::version();
exit(0);
default:
usage();
}
}
argc -= optind;
argv += optind;
if (generate == true) {
cout << "Generating ecru configuration..." << endl;
if (username.length() == 0) {
cout << "Enter username: ";
cin >> username;
}
if (hpassword.length() == 0) {
cout << "Enter md5 hash of the password: ";
cin >> hpassword;
}
string configPath = Config::generate(username, hpassword);
cout << "Config file placed to: " << configPath << endl;
cout << "To install it, type: cp -r " << configPath << " ~/.ecru" << endl;
} else if (hookType.length() > 0) {
Hook *hook = new Hook();
vector<string> hooks;
if (hookType == "pre") {
hooks = hook->getPreHooks();
} else {
hooks = hook->getPostHooks();
}
for (unsigned int i = 0; i < hooks.size(); i++) {
cout << hooks[i] << endl;
}
} else {
if (argc < 1)
usage();
Config *config = new Config();
try {
cout << config->queryConfigProperty(argv[0]) << endl;
} catch (libconfig::SettingNotFoundException& ex) {
cerr << "Setting '" << argv[0];
cerr << "' was not found.";
cerr << endl;
exit(1);
}
}
return 0;
}
|
Fix usage() output.
|
Fix usage() output.
|
C++
|
bsd-2-clause
|
novel/ecru,novel/ecru,novel/ecru
|
cbf13504fbbb391d3f3dd7937934606189c55d7c
|
Library/Sources/Stroika/Foundation/Execution/Logger.cpp
|
Library/Sources/Stroika/Foundation/Execution/Logger.cpp
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qHas_Syslog
#include <syslog.h>
#endif
#include "../Characters/Format.h"
#include "../Debug/Trace.h"
#include "Process.h"
#include "Logger.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
******************************** Execution::Logger *****************************
********************************************************************************
*/
Logger Logger::sThe_;
Logger::Logger ()
: fAppender_ ()
, fMinLogLevel_ (Priority::eInfo)
{
}
void Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)
{
fAppender_ = rep;
}
void Logger::Log_ (Priority logLevel, const String& format, va_list argList)
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp.get () != nullptr) {
tmp->Log (logLevel, Characters::FormatV (format.c_str (), argList));
}
}
/*
********************************************************************************
************************** Execution::IAppenderRep *****************************
********************************************************************************
*/
Logger::IAppenderRep::~IAppenderRep ()
{
}
#if qHas_Syslog
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
namespace {
TString mkMsg_ (const String& applicationName)
{
return Characters::Format (TSTR ("%s[%d]"), applicationName.AsTString ().c_str (), GetCurrentProcessID ());
}
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); // not sure what facility to pass?
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, facility);
}
Logger::SysLogAppender::~SysLogAppender ()
{
closelog ();
}
void Logger::SysLogAppender::Log (Priority logLevel, const String& message)
{
DbgTrace (L"%s", message.c_str ());
syslog (static_cast<int> (logLevel), "%s", message.AsTString ().c_str ());
}
#endif
Logger::FileAppender::FileAppender (const String& fileName)
{
AssertNotImplemented ();
}
void Logger::FileAppender::Log (Priority logLevel, const String& message)
{
AssertNotImplemented ();
}
#if qPlatform_Windows
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
Logger::WindowsEventLogAppender::WindowsEventLogAppender ()
{
}
void Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)
{
/*
* VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO
*/
const TCHAR kEventSourceName[] = _T ("xxxtest");
WORD eventType = EVENTLOG_ERROR_TYPE;
switch (logLevel) {
case Priority::eInfo:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eNotice:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eWarning:
eventType = EVENTLOG_WARNING_TYPE;
break;
case Priority::eError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eAlertError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eEmergency:
eventType = EVENTLOG_ERROR_TYPE;
break;
}
#define CATEGORY_Normal 0x00000001L
WORD eventCategoryID = CATEGORY_Normal;
// See SPR#565 for wierdness - where I cannot really get these paid attention to
// by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS
#define EVENT_Message 0x00000064L
const DWORD kEventID = EVENT_Message;
HANDLE hEventSource = RegisterEventSource (NULL, kEventSourceName);
Verify (hEventSource != NULL);
wstring tmp = message.As<wstring> ();
const wchar_t* msg = tmp.c_str ();
Verify (::ReportEvent (
hEventSource,
eventType,
eventCategoryID,
kEventID,
NULL,
(WORD)1,
0,
&msg,
NULL
)
);
Verify (::DeregisterEventSource (hEventSource));
}
#endif
|
/*
* Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved
*/
#include "../StroikaPreComp.h"
#if qHas_Syslog
#include <syslog.h>
#endif
#include "../Characters/Format.h"
#include "../Debug/Trace.h"
#include "Process.h"
#include "Logger.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
******************************** Execution::Logger *****************************
********************************************************************************
*/
Logger Logger::sThe_;
Logger::Logger ()
: fAppender_ ()
, fMinLogLevel_ (Priority::eInfo)
{
}
void Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)
{
fAppender_ = rep;
}
void Logger::Log_ (Priority logLevel, const String& format, va_list argList)
{
shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; // avoid races and critical sections
if (tmp.get () != nullptr) {
tmp->Log (logLevel, Characters::FormatV (format.c_str (), argList));
}
}
/*
********************************************************************************
************************** Execution::IAppenderRep *****************************
********************************************************************************
*/
Logger::IAppenderRep::~IAppenderRep ()
{
}
#if qHas_Syslog
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
namespace {
TString mkMsg_ (const String& applicationName)
{
return Characters::Format (TSTR ("%s[%d]"), applicationName.AsTString ().c_str (), GetCurrentProcessID ());
}
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); // not sure what facility to pass?
}
Logger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)
: fApplicationName_ (mkMsg_ (applicationName))
{
openlog (fApplicationName_.c_str (), 0, facility);
}
Logger::SysLogAppender::~SysLogAppender ()
{
closelog ();
}
void Logger::SysLogAppender::Log (Priority logLevel, const String& message)
{
DbgTrace (L"%s", message.c_str ());
syslog (static_cast<int> (logLevel), "%s", message.AsTString ().c_str ());
}
#endif
Logger::FileAppender::FileAppender (const String& fileName)
{
AssertNotImplemented ();
}
void Logger::FileAppender::Log (Priority logLevel, const String& message)
{
AssertNotImplemented ();
}
#if qPlatform_Windows
/*
********************************************************************************
************************ Execution::SysLogAppender *****************************
********************************************************************************
*/
Logger::WindowsEventLogAppender::WindowsEventLogAppender ()
{
}
void Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)
{
/*
* VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO
*/
const TCHAR kEventSourceName[] = _T ("xxxtest");
WORD eventType = EVENTLOG_ERROR_TYPE;
switch (logLevel) {
case Priority::eInfo:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eNotice:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
case Priority::eWarning:
eventType = EVENTLOG_WARNING_TYPE;
break;
case Priority::eError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eAlertError:
eventType = EVENTLOG_ERROR_TYPE;
break;
case Priority::eEmergency:
eventType = EVENTLOG_ERROR_TYPE;
break;
}
#define CATEGORY_Normal 0x00000001L
WORD eventCategoryID = CATEGORY_Normal;
// See SPR#565 for wierdness - where I cannot really get these paid attention to
// by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS
#define EVENT_Message 0x00000064L
const DWORD kEventID = EVENT_Message;
HANDLE hEventSource = RegisterEventSource (NULL, kEventSourceName);
Verify (hEventSource != NULL);
TString tmp = message.AsTString ();
const Characters::TChar* msg = tmp.c_str ();
Verify (::ReportEvent (
hEventSource,
eventType,
eventCategoryID,
kEventID,
NULL,
(WORD)1,
0,
&msg,
NULL
)
);
Verify (::DeregisterEventSource (hEventSource));
}
#endif
|
fix tstring issue
|
fix tstring issue
|
C++
|
mit
|
SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika,SophistSolutions/Stroika
|
f88c024b2fb6cd840e83313919af71bdb86ca386
|
src/ethernetII.cpp
|
src/ethernetII.cpp
|
/*
* Copyright (c) 2017, Matias Fontanini
* 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.
*
* 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 <cstring>
#include <tins/macros.h>
#ifndef _WIN32
#if defined(BSD) || defined(__FreeBSD_kernel__)
#include <net/if_dl.h>
#else
#include <netpacket/packet.h>
#endif
#include <netinet/in.h>
#include <net/ethernet.h>
#endif
#include <tins/ethernetII.h>
#include <tins/config.h>
#include <tins/packet_sender.h>
#include <tins/pppoe.h>
#include <tins/constants.h>
#include <tins/exceptions.h>
#include <tins/memory_helpers.h>
#include <tins/detail/pdu_helpers.h>
using Tins::Memory::InputMemoryStream;
using Tins::Memory::OutputMemoryStream;
namespace Tins {
const EthernetII::address_type EthernetII::BROADCAST("ff:ff:ff:ff:ff:ff");
PDU::metadata EthernetII::extract_metadata(const uint8_t *buffer, uint32_t total_sz) {
if (TINS_UNLIKELY(total_sz < sizeof(ethernet_header))) {
throw malformed_packet();
}
const ethernet_header* header = (const ethernet_header*)buffer;
PDUType next_type = Internals::ether_type_to_pdu_flag(
static_cast<Constants::Ethernet::e>(Endian::be_to_host(header->payload_type)));
return metadata(sizeof(ethernet_header), pdu_flag, next_type);
}
EthernetII::EthernetII(const address_type& dst_hw_addr,
const address_type& src_hw_addr)
: header_() {
dst_addr(dst_hw_addr);
src_addr(src_hw_addr);
}
EthernetII::EthernetII(const uint8_t* buffer, uint32_t total_sz) {
InputMemoryStream stream(buffer, total_sz);
stream.read(header_);
// If there's any size left
if (stream) {
inner_pdu(
Internals::pdu_from_flag(
(Constants::Ethernet::e)payload_type(),
stream.pointer(),
stream.size()
)
);
}
}
void EthernetII::dst_addr(const address_type& new_dst_addr) {
new_dst_addr.copy(header_.dst_mac);
}
void EthernetII::src_addr(const address_type& new_src_addr) {
new_src_addr.copy(header_.src_mac);
}
void EthernetII::payload_type(uint16_t new_payload_type) {
header_.payload_type = Endian::host_to_be(new_payload_type);
}
uint32_t EthernetII::header_size() const {
return sizeof(header_);
}
uint32_t EthernetII::trailer_size() const {
int32_t padding = 60 - sizeof(header_); // EthernetII min size is 60, padding is sometimes needed
if (inner_pdu()) {
padding -= inner_pdu()->size();
padding = padding > 0 ? padding : 0;
}
return padding;
}
void EthernetII::send(PacketSender& sender, const NetworkInterface& iface) {
if (!iface) {
throw invalid_interface();
}
#if defined(TINS_HAVE_PACKET_SENDER_PCAP_SENDPACKET) || defined(BSD) || defined(__FreeBSD_kernel__)
// Sending using pcap_sendpacket/BSD bpf packet mode is the same here
sender.send_l2(*this, 0, 0, iface);
#elif defined(_WIN32)
// On Windows we can only send l2 PDUs using pcap_sendpacket
throw feature_disabled();
#else
// Default GNU/Linux behaviour
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = Endian::host_to_be<uint16_t>(PF_PACKET);
addr.sll_protocol = Endian::host_to_be<uint16_t>(ETH_P_ALL);
addr.sll_halen = address_type::address_size;
addr.sll_ifindex = iface.id();
memcpy(&(addr.sll_addr), header_.dst_mac, address_type::address_size);
sender.send_l2(*this, (struct sockaddr*)&addr, (uint32_t)sizeof(addr), iface);
#endif
}
bool EthernetII::matches_response(const uint8_t* ptr, uint32_t total_sz) const {
if (total_sz < sizeof(header_)) {
return false;
}
const ethernet_header* eth_ptr = (const ethernet_header*)ptr;
if (address_type(header_.src_mac) == address_type(eth_ptr->dst_mac)) {
if (address_type(header_.src_mac) == address_type(eth_ptr->dst_mac) ||
!dst_addr().is_unicast()) {
return inner_pdu() ?
inner_pdu()->matches_response(ptr + sizeof(header_), total_sz - sizeof(header_)) :
true;
}
}
return false;
}
void EthernetII::write_serialization(uint8_t* buffer, uint32_t total_sz) {
OutputMemoryStream stream(buffer, total_sz);
if (inner_pdu()) {
Constants::Ethernet::e flag;
const PDUType type = inner_pdu()->pdu_type();
// Dirty trick to sucessfully tag PPPoE session/discovery packets
if (type == PDU::PPPOE) {
const PPPoE* pppoe = static_cast<const PPPoE*>(inner_pdu());
flag = (pppoe->code() == 0) ? Constants::Ethernet::PPPOES
: Constants::Ethernet::PPPOED;
}
else {
flag = Internals::pdu_flag_to_ether_type(type);
}
if (flag != Constants::Ethernet::UNKNOWN) {
payload_type(static_cast<uint16_t>(flag));
}
}
else {
payload_type(Constants::Ethernet::UNKNOWN);
}
stream.write(header_);
const uint32_t trailer = trailer_size();
if (trailer) {
if (inner_pdu()) {
stream.skip(inner_pdu()->size());
}
stream.fill(trailer, 0);
}
}
#ifndef _WIN32
PDU* EthernetII::recv_response(PacketSender& sender, const NetworkInterface& iface) {
#if !defined(BSD) && !defined(__FreeBSD_kernel__)
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = Endian::host_to_be<uint16_t>(PF_PACKET);
addr.sll_protocol = Endian::host_to_be<uint16_t>(ETH_P_ALL);
addr.sll_halen = address_type::address_size;
addr.sll_ifindex = iface.id();
memcpy(&(addr.sll_addr), header_.dst_mac, address_type::address_size);
return sender.recv_l2(*this, (struct sockaddr*)&addr, (uint32_t)sizeof(addr));
#else
return sender.recv_l2(*this, 0, 0, iface);
#endif
}
#endif // _WIN32
} // Tins
|
/*
* Copyright (c) 2017, Matias Fontanini
* 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.
*
* 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 <cstring>
#include <tins/macros.h>
#ifndef _WIN32
#if defined(BSD) || defined(__FreeBSD_kernel__)
#include <net/if_dl.h>
#else
#include <netpacket/packet.h>
#endif
#include <netinet/in.h>
#include <net/ethernet.h>
#endif
#include <tins/ethernetII.h>
#include <tins/config.h>
#include <tins/packet_sender.h>
#include <tins/pppoe.h>
#include <tins/constants.h>
#include <tins/exceptions.h>
#include <tins/memory_helpers.h>
#include <tins/detail/pdu_helpers.h>
using Tins::Memory::InputMemoryStream;
using Tins::Memory::OutputMemoryStream;
namespace Tins {
const EthernetII::address_type EthernetII::BROADCAST("ff:ff:ff:ff:ff:ff");
PDU::metadata EthernetII::extract_metadata(const uint8_t *buffer, uint32_t total_sz) {
if (TINS_UNLIKELY(total_sz < sizeof(ethernet_header))) {
throw malformed_packet();
}
const ethernet_header* header = (const ethernet_header*)buffer;
PDUType next_type = Internals::ether_type_to_pdu_flag(
static_cast<Constants::Ethernet::e>(Endian::be_to_host(header->payload_type)));
return metadata(sizeof(ethernet_header), pdu_flag, next_type);
}
EthernetII::EthernetII(const address_type& dst_hw_addr,
const address_type& src_hw_addr)
: header_() {
dst_addr(dst_hw_addr);
src_addr(src_hw_addr);
}
EthernetII::EthernetII(const uint8_t* buffer, uint32_t total_sz) {
InputMemoryStream stream(buffer, total_sz);
stream.read(header_);
// If there's any size left
if (stream) {
inner_pdu(
Internals::pdu_from_flag(
(Constants::Ethernet::e)payload_type(),
stream.pointer(),
stream.size()
)
);
}
}
void EthernetII::dst_addr(const address_type& new_dst_addr) {
new_dst_addr.copy(header_.dst_mac);
}
void EthernetII::src_addr(const address_type& new_src_addr) {
new_src_addr.copy(header_.src_mac);
}
void EthernetII::payload_type(uint16_t new_payload_type) {
header_.payload_type = Endian::host_to_be(new_payload_type);
}
uint32_t EthernetII::header_size() const {
return sizeof(header_);
}
uint32_t EthernetII::trailer_size() const {
int32_t padding = 60 - sizeof(header_); // EthernetII min size is 60, padding is sometimes needed
if (inner_pdu()) {
padding -= inner_pdu()->size();
padding = padding > 0 ? padding : 0;
}
return padding;
}
void EthernetII::send(PacketSender& sender, const NetworkInterface& iface) {
if (!iface) {
throw invalid_interface();
}
#if defined(TINS_HAVE_PACKET_SENDER_PCAP_SENDPACKET) || defined(BSD) || defined(__FreeBSD_kernel__)
// Sending using pcap_sendpacket/BSD bpf packet mode is the same here
sender.send_l2(*this, 0, 0, iface);
#elif defined(_WIN32)
// On Windows we can only send l2 PDUs using pcap_sendpacket
throw feature_disabled();
#else
// Default GNU/Linux behaviour
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = Endian::host_to_be<uint16_t>(PF_PACKET);
addr.sll_protocol = Endian::host_to_be<uint16_t>(ETH_P_ALL);
addr.sll_halen = address_type::address_size;
addr.sll_ifindex = iface.id();
memcpy(&(addr.sll_addr), header_.dst_mac, address_type::address_size);
sender.send_l2(*this, (struct sockaddr*)&addr, (uint32_t)sizeof(addr), iface);
#endif
}
bool EthernetII::matches_response(const uint8_t* ptr, uint32_t total_sz) const {
if (total_sz < sizeof(header_)) {
return false;
}
const ethernet_header* eth_ptr = (const ethernet_header*)ptr;
if (address_type(header_.src_mac) == address_type(eth_ptr->dst_mac)) {
if (address_type(header_.src_mac) == address_type(eth_ptr->dst_mac) ||
!dst_addr().is_unicast()) {
return inner_pdu() ?
inner_pdu()->matches_response(ptr + sizeof(header_), total_sz - sizeof(header_)) :
true;
}
}
return false;
}
void EthernetII::write_serialization(uint8_t* buffer, uint32_t total_sz) {
OutputMemoryStream stream(buffer, total_sz);
if (inner_pdu()) {
Constants::Ethernet::e flag;
const PDUType type = inner_pdu()->pdu_type();
// Dirty trick to successfully tag PPPoE session/discovery packets
if (type == PDU::PPPOE) {
const PPPoE* pppoe = static_cast<const PPPoE*>(inner_pdu());
flag = (pppoe->code() == 0) ? Constants::Ethernet::PPPOES
: Constants::Ethernet::PPPOED;
}
else {
flag = Internals::pdu_flag_to_ether_type(type);
}
if (flag != Constants::Ethernet::UNKNOWN) {
payload_type(static_cast<uint16_t>(flag));
}
}
else {
payload_type(Constants::Ethernet::UNKNOWN);
}
stream.write(header_);
const uint32_t trailer = trailer_size();
if (trailer) {
if (inner_pdu()) {
stream.skip(inner_pdu()->size());
}
stream.fill(trailer, 0);
}
}
#ifndef _WIN32
PDU* EthernetII::recv_response(PacketSender& sender, const NetworkInterface& iface) {
#if !defined(BSD) && !defined(__FreeBSD_kernel__)
struct sockaddr_ll addr;
memset(&addr, 0, sizeof(struct sockaddr_ll));
addr.sll_family = Endian::host_to_be<uint16_t>(PF_PACKET);
addr.sll_protocol = Endian::host_to_be<uint16_t>(ETH_P_ALL);
addr.sll_halen = address_type::address_size;
addr.sll_ifindex = iface.id();
memcpy(&(addr.sll_addr), header_.dst_mac, address_type::address_size);
return sender.recv_l2(*this, (struct sockaddr*)&addr, (uint32_t)sizeof(addr));
#else
return sender.recv_l2(*this, 0, 0, iface);
#endif
}
#endif // _WIN32
} // Tins
|
Fix minor typo in comment. (#261)
|
Fix minor typo in comment. (#261)
|
C++
|
bsd-2-clause
|
UlfWetzker/libtins,mfontanini/libtins,UlfWetzker/libtins,mfontanini/libtins
|
bd0349c8597bb1e74204587119e0b66a899f8819
|
src/event/Base.hxx
|
src/event/Base.hxx
|
/*
* C++ wrappers for libevent.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef EVENT_BASE_HXX
#define EVENT_BASE_HXX
#include <event.h>
class EventBase {
struct event_base *event_base;
public:
EventBase():event_base(::event_init()) {}
~EventBase() {
::event_base_free(event_base);
}
EventBase(const EventBase &other) = delete;
EventBase &operator=(const EventBase &other) = delete;
struct event_base *Get() {
return event_base;
}
void Reinit() {
event_reinit(event_base);
}
void Dispatch() {
::event_base_dispatch(event_base);
}
bool LoopOnce(bool non_block=false) {
int flags = EVLOOP_ONCE;
if (non_block)
flags |= EVLOOP_NONBLOCK;
return ::event_loop(flags) == 0;
}
void Break() {
::event_base_loopbreak(event_base);
}
};
#endif
|
/*
* C++ wrappers for libevent.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef EVENT_BASE_HXX
#define EVENT_BASE_HXX
#include <event.h>
class EventBase {
struct event_base *event_base;
public:
EventBase():event_base(::event_init()) {}
~EventBase() {
::event_base_free(event_base);
}
EventBase(const EventBase &other) = delete;
EventBase &operator=(const EventBase &other) = delete;
struct event_base *Get() {
return event_base;
}
void Reinit() {
event_reinit(event_base);
}
void Dispatch() {
::event_base_dispatch(event_base);
}
bool LoopOnce(bool non_block=false) {
int flags = EVLOOP_ONCE;
if (non_block)
flags |= EVLOOP_NONBLOCK;
return ::event_loop(flags) == 0;
}
void Break() {
::event_base_loopbreak(event_base);
}
void DumpEvents(FILE *file) {
event_base_dump_events(event_base, file);
}
};
#endif
|
add method DumpEvents()
|
event/Base: add method DumpEvents()
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
0c3848732ee33cf14a80129f6cf7ee84d51c8bfb
|
src/cpu/base.hh
|
src/cpu/base.hh
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
#ifndef __CPU_BASE_HH__
#define __CPU_BASE_HH__
#include <vector>
#include "arch/isa_traits.hh"
#include "base/statistics.hh"
#include "config/full_system.hh"
#include "sim/eventq.hh"
#include "sim/insttracer.hh"
#include "mem/mem_object.hh"
#if FULL_SYSTEM
#include "arch/interrupts.hh"
#endif
class BaseCPUParams;
class BranchPred;
class CheckerCPU;
class ThreadContext;
class System;
class Port;
namespace TheISA
{
class Predecoder;
}
class CPUProgressEvent : public Event
{
protected:
Tick interval;
Counter lastNumInst;
BaseCPU *cpu;
public:
CPUProgressEvent(BaseCPU *_cpu, Tick ival);
void process();
virtual const char *description() const;
};
class BaseCPU : public MemObject
{
protected:
// CPU's clock period in terms of the number of ticks of curTime.
Tick clock;
// @todo remove me after debugging with legion done
Tick instCnt;
public:
// Tick currentTick;
inline Tick frequency() const { return Clock::Frequency / clock; }
inline Tick ticks(int numCycles) const { return clock * numCycles; }
inline Tick curCycle() const { return curTick / clock; }
inline Tick tickToCycles(Tick val) const { return val / clock; }
// @todo remove me after debugging with legion done
Tick instCount() { return instCnt; }
/** The next cycle the CPU should be scheduled, given a cache
* access or quiesce event returning on this cycle. This function
* may return curTick if the CPU should run on the current cycle.
*/
Tick nextCycle();
/** The next cycle the CPU should be scheduled, given a cache
* access or quiesce event returning on the given Tick. This
* function may return curTick if the CPU should run on the
* current cycle.
* @param begin_tick The tick that the event is completing on.
*/
Tick nextCycle(Tick begin_tick);
#if FULL_SYSTEM
protected:
// uint64_t interrupts[TheISA::NumInterruptLevels];
// uint64_t intstatus;
TheISA::Interrupts interrupts;
public:
virtual void post_interrupt(int int_num, int index);
virtual void clear_interrupt(int int_num, int index);
virtual void clear_interrupts();
virtual uint64_t get_interrupts(int int_num);
bool check_interrupts(ThreadContext * tc) const
{ return interrupts.check_interrupts(tc); }
class ProfileEvent : public Event
{
private:
BaseCPU *cpu;
Tick interval;
public:
ProfileEvent(BaseCPU *cpu, Tick interval);
void process();
};
ProfileEvent *profileEvent;
#endif
protected:
std::vector<ThreadContext *> threadContexts;
std::vector<TheISA::Predecoder *> predecoders;
Trace::InstTracer * tracer;
public:
/// Provide access to the tracer pointer
Trace::InstTracer * getTracer() { return tracer; }
/// Notify the CPU that the indicated context is now active. The
/// delay parameter indicates the number of ticks to wait before
/// executing (typically 0 or 1).
virtual void activateContext(int thread_num, int delay) {}
/// Notify the CPU that the indicated context is now suspended.
virtual void suspendContext(int thread_num) {}
/// Notify the CPU that the indicated context is now deallocated.
virtual void deallocateContext(int thread_num) {}
/// Notify the CPU that the indicated context is now halted.
virtual void haltContext(int thread_num) {}
/// Given a Thread Context pointer return the thread num
int findContext(ThreadContext *tc);
/// Given a thread num get tho thread context for it
ThreadContext *getContext(int tn) { return threadContexts[tn]; }
public:
typedef BaseCPUParams Params;
const Params *params() const
{ return reinterpret_cast<const Params *>(_params); }
BaseCPU(Params *params);
virtual ~BaseCPU();
virtual void init();
virtual void startup();
virtual void regStats();
virtual void activateWhenReady(int tid) {};
void registerThreadContexts();
/// Prepare for another CPU to take over execution. When it is
/// is ready (drained pipe) it signals the sampler.
virtual void switchOut();
/// Take over execution from the given CPU. Used for warm-up and
/// sampling.
virtual void takeOverFrom(BaseCPU *, Port *ic, Port *dc);
/**
* Number of threads we're actually simulating (<= SMT_MAX_THREADS).
* This is a constant for the duration of the simulation.
*/
int number_of_threads;
TheISA::CoreSpecific coreParams; //ISA-Specific Params That Set Up State in Core
/**
* Vector of per-thread instruction-based event queues. Used for
* scheduling events based on number of instructions committed by
* a particular thread.
*/
EventQueue **comInstEventQueue;
/**
* Vector of per-thread load-based event queues. Used for
* scheduling events based on number of loads committed by
*a particular thread.
*/
EventQueue **comLoadEventQueue;
System *system;
Tick phase;
#if FULL_SYSTEM
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
#endif
/**
* Return pointer to CPU's branch predictor (NULL if none).
* @return Branch predictor pointer.
*/
virtual BranchPred *getBranchPred() { return NULL; };
virtual Counter totalInstructions() const { return 0; }
// Function tracing
private:
bool functionTracingEnabled;
std::ostream *functionTraceStream;
Addr currentFunctionStart;
Addr currentFunctionEnd;
Tick functionEntryTick;
void enableFunctionTrace();
void traceFunctionsInternal(Addr pc);
protected:
void traceFunctions(Addr pc)
{
if (functionTracingEnabled)
traceFunctionsInternal(pc);
}
private:
static std::vector<BaseCPU *> cpuList; //!< Static global cpu list
public:
static int numSimulatedCPUs() { return cpuList.size(); }
static Counter numSimulatedInstructions()
{
Counter total = 0;
int size = cpuList.size();
for (int i = 0; i < size; ++i)
total += cpuList[i]->totalInstructions();
return total;
}
public:
// Number of CPU cycles simulated
Stats::Scalar<> numCycles;
};
#endif // __CPU_BASE_HH__
|
/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
#ifndef __CPU_BASE_HH__
#define __CPU_BASE_HH__
#include <vector>
#include "arch/isa_traits.hh"
#include "base/statistics.hh"
#include "config/full_system.hh"
#include "sim/eventq.hh"
#include "sim/insttracer.hh"
#include "mem/mem_object.hh"
#if FULL_SYSTEM
#include "arch/interrupts.hh"
#endif
class BaseCPUParams;
class BranchPred;
class CheckerCPU;
class ThreadContext;
class System;
class Port;
namespace TheISA
{
class Predecoder;
}
class CPUProgressEvent : public Event
{
protected:
Tick interval;
Counter lastNumInst;
BaseCPU *cpu;
public:
CPUProgressEvent(BaseCPU *_cpu, Tick ival);
void process();
virtual const char *description() const;
};
class BaseCPU : public MemObject
{
protected:
// CPU's clock period in terms of the number of ticks of curTime.
Tick clock;
// @todo remove me after debugging with legion done
Tick instCnt;
public:
// Tick currentTick;
inline Tick frequency() const { return Clock::Frequency / clock; }
inline Tick ticks(int numCycles) const { return clock * numCycles; }
inline Tick curCycle() const { return curTick / clock; }
inline Tick tickToCycles(Tick val) const { return val / clock; }
// @todo remove me after debugging with legion done
Tick instCount() { return instCnt; }
/** The next cycle the CPU should be scheduled, given a cache
* access or quiesce event returning on this cycle. This function
* may return curTick if the CPU should run on the current cycle.
*/
Tick nextCycle();
/** The next cycle the CPU should be scheduled, given a cache
* access or quiesce event returning on the given Tick. This
* function may return curTick if the CPU should run on the
* current cycle.
* @param begin_tick The tick that the event is completing on.
*/
Tick nextCycle(Tick begin_tick);
#if FULL_SYSTEM
protected:
// uint64_t interrupts[TheISA::NumInterruptLevels];
// uint64_t intstatus;
TheISA::Interrupts interrupts;
public:
TheISA::Interrupts *
getInterruptController()
{
return &interrupts;
}
virtual void post_interrupt(int int_num, int index);
virtual void clear_interrupt(int int_num, int index);
virtual void clear_interrupts();
virtual uint64_t get_interrupts(int int_num);
bool check_interrupts(ThreadContext * tc) const
{ return interrupts.check_interrupts(tc); }
class ProfileEvent : public Event
{
private:
BaseCPU *cpu;
Tick interval;
public:
ProfileEvent(BaseCPU *cpu, Tick interval);
void process();
};
ProfileEvent *profileEvent;
#endif
protected:
std::vector<ThreadContext *> threadContexts;
std::vector<TheISA::Predecoder *> predecoders;
Trace::InstTracer * tracer;
public:
/// Provide access to the tracer pointer
Trace::InstTracer * getTracer() { return tracer; }
/// Notify the CPU that the indicated context is now active. The
/// delay parameter indicates the number of ticks to wait before
/// executing (typically 0 or 1).
virtual void activateContext(int thread_num, int delay) {}
/// Notify the CPU that the indicated context is now suspended.
virtual void suspendContext(int thread_num) {}
/// Notify the CPU that the indicated context is now deallocated.
virtual void deallocateContext(int thread_num) {}
/// Notify the CPU that the indicated context is now halted.
virtual void haltContext(int thread_num) {}
/// Given a Thread Context pointer return the thread num
int findContext(ThreadContext *tc);
/// Given a thread num get tho thread context for it
ThreadContext *getContext(int tn) { return threadContexts[tn]; }
public:
typedef BaseCPUParams Params;
const Params *params() const
{ return reinterpret_cast<const Params *>(_params); }
BaseCPU(Params *params);
virtual ~BaseCPU();
virtual void init();
virtual void startup();
virtual void regStats();
virtual void activateWhenReady(int tid) {};
void registerThreadContexts();
/// Prepare for another CPU to take over execution. When it is
/// is ready (drained pipe) it signals the sampler.
virtual void switchOut();
/// Take over execution from the given CPU. Used for warm-up and
/// sampling.
virtual void takeOverFrom(BaseCPU *, Port *ic, Port *dc);
/**
* Number of threads we're actually simulating (<= SMT_MAX_THREADS).
* This is a constant for the duration of the simulation.
*/
int number_of_threads;
TheISA::CoreSpecific coreParams; //ISA-Specific Params That Set Up State in Core
/**
* Vector of per-thread instruction-based event queues. Used for
* scheduling events based on number of instructions committed by
* a particular thread.
*/
EventQueue **comInstEventQueue;
/**
* Vector of per-thread load-based event queues. Used for
* scheduling events based on number of loads committed by
*a particular thread.
*/
EventQueue **comLoadEventQueue;
System *system;
Tick phase;
#if FULL_SYSTEM
/**
* Serialize this object to the given output stream.
* @param os The stream to serialize to.
*/
virtual void serialize(std::ostream &os);
/**
* Reconstruct the state of this object from a checkpoint.
* @param cp The checkpoint use.
* @param section The section name of this object
*/
virtual void unserialize(Checkpoint *cp, const std::string §ion);
#endif
/**
* Return pointer to CPU's branch predictor (NULL if none).
* @return Branch predictor pointer.
*/
virtual BranchPred *getBranchPred() { return NULL; };
virtual Counter totalInstructions() const { return 0; }
// Function tracing
private:
bool functionTracingEnabled;
std::ostream *functionTraceStream;
Addr currentFunctionStart;
Addr currentFunctionEnd;
Tick functionEntryTick;
void enableFunctionTrace();
void traceFunctionsInternal(Addr pc);
protected:
void traceFunctions(Addr pc)
{
if (functionTracingEnabled)
traceFunctionsInternal(pc);
}
private:
static std::vector<BaseCPU *> cpuList; //!< Static global cpu list
public:
static int numSimulatedCPUs() { return cpuList.size(); }
static Counter numSimulatedInstructions()
{
Counter total = 0;
int size = cpuList.size();
for (int i = 0; i < size; ++i)
total += cpuList[i]->totalInstructions();
return total;
}
public:
// Number of CPU cycles simulated
Stats::Scalar<> numCycles;
};
#endif // __CPU_BASE_HH__
|
Add a getInterruptController function
|
CPU: Add a getInterruptController function
|
C++
|
bsd-3-clause
|
gedare/gem5,KuroeKurose/gem5,kaiyuanl/gem5,aclifton/cpeg853-gem5,rjschof/gem5,samueldotj/TeeRISC-Simulator,austinharris/gem5-riscv,cancro7/gem5,samueldotj/TeeRISC-Simulator,SanchayanMaity/gem5,powerjg/gem5-ci-test,KuroeKurose/gem5,aclifton/cpeg853-gem5,markoshorro/gem5,aclifton/cpeg853-gem5,yb-kim/gemV,TUD-OS/gem5-dtu,qizenguf/MLC-STT,markoshorro/gem5,sobercoder/gem5,yb-kim/gemV,yb-kim/gemV,qizenguf/MLC-STT,SanchayanMaity/gem5,kaiyuanl/gem5,HwisooSo/gemV-update,qizenguf/MLC-STT,SanchayanMaity/gem5,austinharris/gem5-riscv,cancro7/gem5,HwisooSo/gemV-update,sobercoder/gem5,cancro7/gem5,zlfben/gem5,HwisooSo/gemV-update,yb-kim/gemV,zlfben/gem5,SanchayanMaity/gem5,gem5/gem5,joerocklin/gem5,markoshorro/gem5,rjschof/gem5,TUD-OS/gem5-dtu,samueldotj/TeeRISC-Simulator,rallylee/gem5,Weil0ng/gem5,briancoutinho0905/2dsampling,briancoutinho0905/2dsampling,kaiyuanl/gem5,SanchayanMaity/gem5,austinharris/gem5-riscv,TUD-OS/gem5-dtu,HwisooSo/gemV-update,rallylee/gem5,qizenguf/MLC-STT,sobercoder/gem5,yb-kim/gemV,rjschof/gem5,Weil0ng/gem5,briancoutinho0905/2dsampling,zlfben/gem5,rallylee/gem5,rjschof/gem5,yb-kim/gemV,qizenguf/MLC-STT,austinharris/gem5-riscv,gedare/gem5,rallylee/gem5,austinharris/gem5-riscv,TUD-OS/gem5-dtu,joerocklin/gem5,cancro7/gem5,aclifton/cpeg853-gem5,briancoutinho0905/2dsampling,gem5/gem5,KuroeKurose/gem5,sobercoder/gem5,SanchayanMaity/gem5,samueldotj/TeeRISC-Simulator,rjschof/gem5,sobercoder/gem5,gem5/gem5,briancoutinho0905/2dsampling,austinharris/gem5-riscv,gedare/gem5,joerocklin/gem5,markoshorro/gem5,TUD-OS/gem5-dtu,powerjg/gem5-ci-test,markoshorro/gem5,rallylee/gem5,cancro7/gem5,aclifton/cpeg853-gem5,Weil0ng/gem5,joerocklin/gem5,yb-kim/gemV,qizenguf/MLC-STT,HwisooSo/gemV-update,powerjg/gem5-ci-test,gedare/gem5,gedare/gem5,KuroeKurose/gem5,zlfben/gem5,sobercoder/gem5,powerjg/gem5-ci-test,powerjg/gem5-ci-test,TUD-OS/gem5-dtu,gem5/gem5,aclifton/cpeg853-gem5,joerocklin/gem5,HwisooSo/gemV-update,kaiyuanl/gem5,KuroeKurose/gem5,yb-kim/gemV,KuroeKurose/gem5,rjschof/gem5,samueldotj/TeeRISC-Simulator,Weil0ng/gem5,HwisooSo/gemV-update,kaiyuanl/gem5,joerocklin/gem5,cancro7/gem5,gem5/gem5,austinharris/gem5-riscv,powerjg/gem5-ci-test,joerocklin/gem5,rallylee/gem5,briancoutinho0905/2dsampling,gem5/gem5,SanchayanMaity/gem5,kaiyuanl/gem5,zlfben/gem5,Weil0ng/gem5,markoshorro/gem5,cancro7/gem5,powerjg/gem5-ci-test,kaiyuanl/gem5,Weil0ng/gem5,samueldotj/TeeRISC-Simulator,aclifton/cpeg853-gem5,TUD-OS/gem5-dtu,briancoutinho0905/2dsampling,rjschof/gem5,sobercoder/gem5,rallylee/gem5,gedare/gem5,zlfben/gem5,joerocklin/gem5,samueldotj/TeeRISC-Simulator,gedare/gem5,qizenguf/MLC-STT,gem5/gem5,zlfben/gem5,markoshorro/gem5,Weil0ng/gem5,KuroeKurose/gem5
|
aa64a62c439d80eb0f306350bf50e5c97f49c383
|
src/SMDS/SMDS_VolumeOfNodes.cxx
|
src/SMDS/SMDS_VolumeOfNodes.cxx
|
// SMESH SMDS : implementaion of Salome mesh data structure
//
// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.opencascade.org/SALOME/ or email : [email protected]
#include "utilities.h"
#include "SMDS_VolumeOfNodes.hxx"
#include "SMDS_MeshNode.hxx"
///////////////////////////////////////////////////////////////////////////////
/// Create an hexahedron. node 1,2,3,4 and 5,6,7,8 are quadrangle and
/// 5,1 and 7,3 are an edges.
///////////////////////////////////////////////////////////////////////////////
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5,
SMDS_MeshNode * node6,
SMDS_MeshNode * node7,
SMDS_MeshNode * node8)
{
myNodes.resize(8);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
myNodes[5]=node6;
myNodes[6]=node7;
myNodes[7]=node8;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4)
{
myNodes.resize(4);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5)
{
myNodes.resize(5);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5,
SMDS_MeshNode * node6)
{
myNodes.resize(6);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
myNodes[5]=node6;
}
//=======================================================================
//function : Print
//purpose :
//=======================================================================
void SMDS_VolumeOfNodes::Print(ostream & OS) const
{
OS << "volume <" << GetID() << "> : ";
int i;
for (i = 0; i < 7; ++i) OS << myNodes[i] << ",";
OS << myNodes[7]<< ") " << endl;
}
int SMDS_VolumeOfNodes::NbFaces() const
{
switch(NbNodes())
{
case 4: return 4;
case 5: return 5;
case 6: return 5;
case 8: return 6;
default: MESSAGE("invalid number of nodes");
}
}
int SMDS_VolumeOfNodes::NbNodes() const
{
return myNodes.size();
}
int SMDS_VolumeOfNodes::NbEdges() const
{
switch(NbNodes())
{
case 4: return 6;
case 5: return 8;
case 6: return 9;
case 8: return 12;
default: MESSAGE("invalid number of nodes");
}
}
SMDS_Iterator<const SMDS_MeshElement *> * SMDS_VolumeOfNodes::
elementsIterator(SMDSAbs_ElementType type) const
{
class MyIterator:public SMDS_Iterator<const SMDS_MeshElement*>
{
const vector<const SMDS_MeshNode*>& mySet;
int index;
public:
MyIterator(const vector<const SMDS_MeshNode*>& s):mySet(s),index(0)
{}
bool more()
{
return index<mySet.size();
}
const SMDS_MeshElement* next()
{
index++;
return mySet[index-1];
}
};
switch(type)
{
case SMDSAbs_Volume:return SMDS_MeshElement::elementsIterator(SMDSAbs_Volume);
case SMDSAbs_Node:return new MyIterator(myNodes);
default: MESSAGE("ERROR : Iterator not implemented");
}
}
SMDSAbs_ElementType SMDS_VolumeOfNodes::GetType() const
{
return SMDSAbs_Volume;
}
|
// SMESH SMDS : implementaion of Salome mesh data structure
//
// Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.opencascade.org/SALOME/ or email : [email protected]
#include "utilities.h"
#include "SMDS_VolumeOfNodes.hxx"
#include "SMDS_MeshNode.hxx"
///////////////////////////////////////////////////////////////////////////////
/// Create an hexahedron. node 1,2,3,4 and 5,6,7,8 are quadrangle and
/// 5,1 and 7,3 are an edges.
///////////////////////////////////////////////////////////////////////////////
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5,
SMDS_MeshNode * node6,
SMDS_MeshNode * node7,
SMDS_MeshNode * node8)
{
myNodes.resize(8);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
myNodes[5]=node6;
myNodes[6]=node7;
myNodes[7]=node8;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4)
{
myNodes.resize(4);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5)
{
myNodes.resize(5);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
}
SMDS_VolumeOfNodes::SMDS_VolumeOfNodes(
SMDS_MeshNode * node1,
SMDS_MeshNode * node2,
SMDS_MeshNode * node3,
SMDS_MeshNode * node4,
SMDS_MeshNode * node5,
SMDS_MeshNode * node6)
{
myNodes.resize(6);
myNodes[0]=node1;
myNodes[1]=node2;
myNodes[2]=node3;
myNodes[3]=node4;
myNodes[4]=node5;
myNodes[5]=node6;
}
//=======================================================================
//function : Print
//purpose :
//=======================================================================
void SMDS_VolumeOfNodes::Print(ostream & OS) const
{
OS << "volume <" << GetID() << "> : ";
int i;
for (i = 0; i < NbNodes(); ++i) OS << myNodes[i] << ",";
OS << myNodes[NbNodes()-1]<< ") " << endl;
}
int SMDS_VolumeOfNodes::NbFaces() const
{
switch(NbNodes())
{
case 4: return 4;
case 5: return 5;
case 6: return 5;
case 8: return 6;
default: MESSAGE("invalid number of nodes");
}
}
int SMDS_VolumeOfNodes::NbNodes() const
{
return myNodes.size();
}
int SMDS_VolumeOfNodes::NbEdges() const
{
switch(NbNodes())
{
case 4: return 6;
case 5: return 8;
case 6: return 9;
case 8: return 12;
default: MESSAGE("invalid number of nodes");
}
}
SMDS_Iterator<const SMDS_MeshElement *> * SMDS_VolumeOfNodes::
elementsIterator(SMDSAbs_ElementType type) const
{
class MyIterator:public SMDS_Iterator<const SMDS_MeshElement*>
{
const vector<const SMDS_MeshNode*>& mySet;
int index;
public:
MyIterator(const vector<const SMDS_MeshNode*>& s):mySet(s),index(0)
{}
bool more()
{
return index<mySet.size();
}
const SMDS_MeshElement* next()
{
index++;
return mySet[index-1];
}
};
switch(type)
{
case SMDSAbs_Volume:return SMDS_MeshElement::elementsIterator(SMDSAbs_Volume);
case SMDSAbs_Node:return new MyIterator(myNodes);
default: MESSAGE("ERROR : Iterator not implemented");
}
}
SMDSAbs_ElementType SMDS_VolumeOfNodes::GetType() const
{
return SMDSAbs_Volume;
}
|
Fix bug. Was always printing 8 nodes
|
Fix bug. Was always printing 8 nodes
|
C++
|
lgpl-2.1
|
FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh
|
a9e6c487d500130c035c971e718a140b65d66e37
|
src/datalog.cpp
|
src/datalog.cpp
|
#include <pangolin/datalog.h>
#include <limits>
#include <fstream>
#include <iomanip>
#include <stdexcept>
#include <algorithm>
#include <iostream>
namespace pangolin
{
void DataLogBlock::AddSamples(size_t num_samples, size_t dimensions, const float* data_dim_major )
{
if(nextBlock) {
// If next block exists, add to it instead
nextBlock->AddSamples(num_samples, dimensions, data_dim_major);
}else{
if(dimensions > dim) {
// If dimensions is too high for this block, start a new bigger one
nextBlock = new DataLogBlock(dimensions, max_samples, start_id + samples);
}else{
// Try to copy samples to this block
const size_t samples_to_copy = std::min(num_samples, SampleSpaceLeft());
if(dimensions == dim) {
// Copy entire block all together
std::copy(data_dim_major, data_dim_major + samples_to_copy*dim, sample_buffer+samples*dim);
samples += samples_to_copy;
data_dim_major += samples_to_copy*dim;
}else{
// Copy sample at a time, filling with NaN's where needed.
float* dst = sample_buffer;
for(size_t i=0; i< samples_to_copy; ++i) {
std::copy(data_dim_major, data_dim_major + dimensions, dst);
for(size_t ii = dimensions; ii < dim; ++ii) {
dst[ii] = std::numeric_limits<float>::quiet_NaN();
}
dst += dimensions;
data_dim_major += dimensions;
}
samples += samples_to_copy;
}
// Copy remaining data to next block (this one is full)
if(samples_to_copy < num_samples) {
nextBlock = new DataLogBlock(dim, max_samples, start_id + Samples());
nextBlock->AddSamples(num_samples-samples_to_copy, dimensions, data_dim_major);
}
}
}
}
DataLog::DataLog(unsigned int buffer_size)
: block_samples_alloc(buffer_size), block0(0), blockn(0), record_stats(false)
{
}
DataLog::~DataLog()
{
Clear();
}
void DataLog::SetLabels(const std::vector<std::string> & new_labels)
{
// Create new labels if needed
for( unsigned int i= labels.size(); i < new_labels.size(); ++i )
labels.push_back( std::string() );
// Add data to existing plots
for( unsigned int i=0; i<labels.size(); ++i )
labels[i] = new_labels[i];
}
void DataLog::Log(unsigned int dimension, const float* vals, unsigned int samples )
{
if(!block0) {
// Create first block
block0 = new DataLogBlock(dimension, block_samples_alloc, 0);
blockn = block0;
}
if(record_stats) {
while(stats.size() < dimension) {
stats.push_back( DimensionStats() );
}
for(unsigned int d=0; d<dimension; ++d) {
DimensionStats& ds = stats[d];
for(unsigned int s=0; s<samples; ++s) {
const float v = vals[s*dimension+d];
ds.isMonotonic = ds.isMonotonic && (v >= ds.max);
ds.sum += v;
ds.sum_sq += v*v;
ds.min = std::min(ds.min, v);
ds.max = std::max(ds.max, v);
}
}
}
blockn->AddSamples(samples,dimension,vals);
}
void DataLog::Log(float v)
{
const float vs[] = {v};
Log(1,vs);
}
void DataLog::Log(float v1, float v2)
{
const float vs[] = {v1,v2};
Log(2,vs);
}
void DataLog::Log(float v1, float v2, float v3)
{
const float vs[] = {v1,v2,v3};
Log(3,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4)
{
const float vs[] = {v1,v2,v3,v4};
Log(4,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5)
{
const float vs[] = {v1,v2,v3,v4,v5};
Log(5,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6)
{
const float vs[] = {v1,v2,v3,v4,v5,v6};
Log(6,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7};
Log(7,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8};
Log(8,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8,v9};
Log(9,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8,v9,v10};
Log(10,vs);
}
void DataLog::Log(const std::vector<float> & vals)
{
Log(vals.size(), &vals[0]);
}
void DataLog::Clear()
{
if(block0) {
block0->ClearLinked();
blockn = block0;
}
stats.clear();
}
void DataLog::Save(std::string filename)
{
// TODO: Implement
throw std::runtime_error("Method not implemented");
}
const DataLogBlock* DataLog::FirstBlock() const
{
return block0;
}
const DataLogBlock* DataLog::LastBlock() const
{
return blockn;
}
const DimensionStats& DataLog::Stats(size_t dim) const
{
return stats[dim];
}
unsigned int DataLog::Samples() const
{
if(blockn) {
return blockn->StartId() + blockn->Samples();
}
return 0;
}
const float* DataLog::Sample(int n) const
{
if(block0) {
return block0->Sample(n);
}else{
return 0;
}
}
}
|
#include <pangolin/datalog.h>
#include <limits>
#include <fstream>
#include <iomanip>
#include <stdexcept>
#include <algorithm>
#include <iostream>
namespace pangolin
{
void DataLogBlock::AddSamples(size_t num_samples, size_t dimensions, const float* data_dim_major )
{
if(nextBlock) {
// If next block exists, add to it instead
nextBlock->AddSamples(num_samples, dimensions, data_dim_major);
}else{
if(dimensions > dim) {
// If dimensions is too high for this block, start a new bigger one
nextBlock = new DataLogBlock(dimensions, max_samples, start_id + samples);
}else{
// Try to copy samples to this block
const size_t samples_to_copy = std::min(num_samples, SampleSpaceLeft());
if(dimensions == dim) {
// Copy entire block all together
std::copy(data_dim_major, data_dim_major + samples_to_copy*dim, sample_buffer+samples*dim);
samples += samples_to_copy;
data_dim_major += samples_to_copy*dim;
}else{
// Copy sample at a time, filling with NaN's where needed.
float* dst = sample_buffer;
for(size_t i=0; i< samples_to_copy; ++i) {
std::copy(data_dim_major, data_dim_major + dimensions, dst);
for(size_t ii = dimensions; ii < dim; ++ii) {
dst[ii] = std::numeric_limits<float>::quiet_NaN();
}
dst += dimensions;
data_dim_major += dimensions;
}
samples += samples_to_copy;
}
// Copy remaining data to next block (this one is full)
if(samples_to_copy < num_samples) {
nextBlock = new DataLogBlock(dim, max_samples, start_id + Samples());
nextBlock->AddSamples(num_samples-samples_to_copy, dimensions, data_dim_major);
}
}
}
}
DataLog::DataLog(unsigned int buffer_size)
: block_samples_alloc(buffer_size), block0(0), blockn(0), record_stats(false)
{
}
DataLog::~DataLog()
{
Clear();
}
void DataLog::SetLabels(const std::vector<std::string> & new_labels)
{
// Create new labels if needed
for( unsigned int i= labels.size(); i < new_labels.size(); ++i )
labels.push_back( std::string() );
// Add data to existing plots
for( unsigned int i=0; i<labels.size(); ++i )
labels[i] = new_labels[i];
}
void DataLog::Log(unsigned int dimension, const float* vals, unsigned int samples )
{
if(!block0) {
// Create first block
block0 = new DataLogBlock(dimension, block_samples_alloc, 0);
blockn = block0;
}
if(record_stats) {
while(stats.size() < dimension) {
stats.push_back( DimensionStats() );
}
for(unsigned int d=0; d<dimension; ++d) {
DimensionStats& ds = stats[d];
for(unsigned int s=0; s<samples; ++s) {
const float v = vals[s*dimension+d];
ds.isMonotonic = ds.isMonotonic && (v >= ds.max);
ds.sum += v;
ds.sum_sq += v*v;
ds.min = std::min(ds.min, v);
ds.max = std::max(ds.max, v);
}
}
}
blockn->AddSamples(samples,dimension,vals);
// Update pointer to most recent block.
while(blockn->NextBlock()) {
blockn = blockn->NextBlock();
}
}
void DataLog::Log(float v)
{
const float vs[] = {v};
Log(1,vs);
}
void DataLog::Log(float v1, float v2)
{
const float vs[] = {v1,v2};
Log(2,vs);
}
void DataLog::Log(float v1, float v2, float v3)
{
const float vs[] = {v1,v2,v3};
Log(3,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4)
{
const float vs[] = {v1,v2,v3,v4};
Log(4,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5)
{
const float vs[] = {v1,v2,v3,v4,v5};
Log(5,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6)
{
const float vs[] = {v1,v2,v3,v4,v5,v6};
Log(6,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7};
Log(7,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8};
Log(8,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8,v9};
Log(9,vs);
}
void DataLog::Log(float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10)
{
const float vs[] = {v1,v2,v3,v4,v5,v6,v7,v8,v9,v10};
Log(10,vs);
}
void DataLog::Log(const std::vector<float> & vals)
{
Log(vals.size(), &vals[0]);
}
void DataLog::Clear()
{
if(block0) {
block0->ClearLinked();
blockn = block0;
}
stats.clear();
}
void DataLog::Save(std::string filename)
{
// TODO: Implement
throw std::runtime_error("Method not implemented");
}
const DataLogBlock* DataLog::FirstBlock() const
{
return block0;
}
const DataLogBlock* DataLog::LastBlock() const
{
return blockn;
}
const DimensionStats& DataLog::Stats(size_t dim) const
{
return stats[dim];
}
unsigned int DataLog::Samples() const
{
if(blockn) {
return blockn->StartId() + blockn->Samples();
}
return 0;
}
const float* DataLog::Sample(int n) const
{
if(block0) {
return block0->Sample(n);
}else{
return 0;
}
}
}
|
Fix tracking freeze.
|
Plotter: Fix tracking freeze.
|
C++
|
mit
|
mp3guy/Pangolin,visigoth/Pangolin,tschmidt23/Pangolin,stevenlovegrove/Pangolin,stevenlovegrove/Pangolin,stevenlovegrove/Pangolin,randi120/Pangolin,visigoth/Pangolin,wxdzju/Pangolin,janjachnik/Pangolin,tschmidt23/Pangolin,tschmidt23/Pangolin,mp3guy/Pangolin,renzodenardi/Pangolin,pinglin/Pangolin,randi120/Pangolin,wxdzju/Pangolin,arpg/Pangolin,renzodenardi/Pangolin,pinglin/Pangolin,janjachnik/Pangolin,mp3guy/Pangolin,arpg/Pangolin
|
7e12647be17cba468fc56fffde3093d4c524452e
|
OpenSim/Simulation/OpenSense/InverseKinematicsStudy.cpp
|
OpenSim/Simulation/OpenSense/InverseKinematicsStudy.cpp
|
#include "InverseKinematicsStudy.h"
#include "OpenSenseUtilities.h"
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/TimeSeriesTable.h>
#include <OpenSim/Common/TableSource.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Common/TRCFileAdapter.h>
#include <OpenSim/Common/Reporter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include <OpenSim/Simulation/OrientationsReference.h>
#include "ExperimentalMarker.h"
#include "ExperimentalFrame.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
InverseKinematicsStudy::InverseKinematicsStudy()
{
constructProperties();
}
InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile)
: Object(setupFile, true)
{
constructProperties();
updateFromXMLDocument();
}
InverseKinematicsStudy::~InverseKinematicsStudy()
{
}
void InverseKinematicsStudy::constructProperties()
{
constructProperty_accuracy(1e-6);
constructProperty_constraint_weight(Infinity);
Array<double> range{ Infinity, 2};
constructProperty_time_range(range);
constructProperty_base_imu_label("");
constructProperty_base_heading_axis("z");
constructProperty_model_file_name("");
constructProperty_marker_file_name("");
constructProperty_orientations_file_name("");
constructProperty_results_directory("");
}
void InverseKinematicsStudy::
previewExperimentalData(const TimeSeriesTableVec3& markers,
const TimeSeriesTable_<SimTK::Rotation>& orientations) const
{
Model previewWorld;
// Load the marker data into a TableSource that has markers
// as its output which each markers occupying its own channel
TableSourceVec3* markersSource = new TableSourceVec3(markers);
// Add the markersSource Component to the model
previewWorld.addComponent(markersSource);
// Get the underlying Table backing the the marker Source so we
// know how many markers we have and their names
const auto& markerData = markersSource->getTable();
auto& times = markerData.getIndependentColumn();
auto startEnd = getTimeRangeInUse(times);
// Create an ExperimentalMarker Component for every column in the markerData
for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) {
auto marker = new ExperimentalMarker();
marker->setName(markerData.getColumnLabel(i));
// markers are owned by the model
previewWorld.addComponent(marker);
// the time varying location of the marker comes from the markersSource
// Component
marker->updInput("location_in_ground").connect(
markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i)));
}
previewWorld.setUseVisualizer(true);
SimTK::State& state = previewWorld.initSystem();
state.updTime() = times[0];
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
char c;
std::cout << "press any key to visualize experimental marker data ..." << std::endl;
std::cin >> c;
for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) {
std::cout << "time: " << times[j] << "s" << std::endl;
state.setTime(times[j]);
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
}
}
void InverseKinematicsStudy::
runInverseKinematicsWithOrientationsFromFile(Model& model,
const std::string& orientationsFileName,
bool visualizeResults)
{
// Add a reporter to get IK computed coordinate values out
TableReporter* ikReporter = new TableReporter();
ikReporter->setName("ik_reporter");
auto coordinates = model.updComponentList<Coordinate>();
// Hookup reporter inputs to the individual coordinate outputs
// and lock coordinates that are translational since they cannot be
for (auto& coord : coordinates) {
ikReporter->updInput("inputs").connect(
coord.getOutput("value"), coord.getName());
if(coord.getMotionType() == Coordinate::Translational) {
coord.setDefaultLocked(true);
}
}
model.addComponent(ikReporter);
TimeSeriesTable_<SimTK::Quaternion> quatTable =
STOFileAdapter_<SimTK::Quaternion>::readFile(orientationsFileName);
std::cout << "Loading orientations as quaternions from "
<< orientationsFileName << std::endl;
auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn());
const auto axis_string = IO::Lowercase(get_base_heading_axis());
int axis = (axis_string == "x" ? 0 :
((axis_string == "y") ? 1 : 2) );
SimTK::CoordinateAxis heading{ axis };
cout << "Heading correction for base '" << get_base_imu_label()
<< "' along its '" << axis_string << "' axis." << endl;
TimeSeriesTable_<SimTK::Rotation> orientationsData =
OpenSenseUtilities::convertQuaternionsToRotations(quatTable,
startEnd, get_base_imu_label(), heading);
OrientationsReference oRefs(orientationsData);
MarkersReference mRefs{};
SimTK::Array_<CoordinateReference> coordinateReferences;
// visualize for debugging
if (visualizeResults)
model.setUseVisualizer(true);
SimTK::State& s0 = model.initSystem();
double t0 = s0.getTime();
// create the solver given the input data
const double accuracy = 1e-4;
InverseKinematicsSolver ikSolver(model, mRefs, oRefs,
coordinateReferences);
ikSolver.setAccuracy(accuracy);
auto& times = oRefs.getTimes();
s0.updTime() = times[0];
ikSolver.assemble(s0);
if (visualizeResults) {
model.getVisualizer().show(s0);
model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true);
}
for (auto time : times) {
s0.updTime() = time;
ikSolver.track(s0);
if (visualizeResults)
model.getVisualizer().show(s0);
else
cout << "Solved frame at time: " << time << endl;
// realize to report to get reporter to pull values from model
model.realizeReport(s0);
}
auto report = ikReporter->getTable();
auto eix = orientationsFileName.rfind(".");
auto stix = orientationsFileName.rfind("/") + 1;
IO::makeDir(get_results_directory());
std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix);
std::string outputFile = get_results_directory() + "/" + outName;
// Convert to degrees to compare with marker-based IK
// but only for rotational coordinates
model.getSimbodyEngine().convertRadiansToDegrees(report);
report.updTableMetaData().setValueForKey<string>("name", outName);
report.updTableMetaData().setValueForKey<size_t>("nRows", report.getNumRows());
// getNumColumns returns the number of dependent columns, but Storage expects time
report.updTableMetaData().setValueForKey<size_t>("nColumns", report.getNumColumns()+1);
report.updTableMetaData().setValueForKey<string>("inDegrees","yes");
STOFileAdapter_<double>::write(report, outputFile + ".mot");
std::cout << "Wrote IK with IMU tracking results to: '" <<
outputFile << "'." << std::endl;
}
// main driver
bool InverseKinematicsStudy::run(bool visualizeResults)
{
if (_model.empty()) {
_model.reset(new Model(get_model_file_name()));
}
runInverseKinematicsWithOrientationsFromFile(*_model,
get_orientations_file_name(),
visualizeResults);
return true;
}
SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse(
const std::vector<double>& times ) const
{
int nt = static_cast<int>(times.size());
int startIx = 0;
int endIx = nt-1;
for (int i = 0; i < nt; ++i) {
if (times[i] <= get_time_range(0)) {
startIx = i;
}
else {
break;
}
}
for (int i = nt - 1; i > 0; --i) {
if (times[i] >= get_time_range(1)) {
endIx= i;
}
else {
break;
}
}
SimTK::Array_<int> retArray;
retArray.push_back(startIx);
retArray.push_back(endIx);
return retArray;
}
TimeSeriesTable_<SimTK::Vec3>
InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile)
{
auto markers = TRCFileAdapter::readFile(markerFile);
std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers "
<< " and " << markers.getNumRows() << " rows of data." << std::endl;
if (markers.hasTableMetaDataKey("Units")) {
std::cout << markerFile << " has Units meta data." << std::endl;
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
if (value.getValue<std::string>() == "mm") {
std::cout << "Marker data in mm, converting to m." << std::endl;
for (size_t i = 0; i < markers.getNumRows(); ++i) {
markers.updRowAtIndex(i) *= 0.001;
}
markers.updTableMetaData().removeValueForKey("Units");
markers.updTableMetaData().setValueForKey<std::string>("Units", "m");
}
}
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
return markers;
}
|
#include "InverseKinematicsStudy.h"
#include "OpenSenseUtilities.h"
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/TimeSeriesTable.h>
#include <OpenSim/Common/TableSource.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Common/TRCFileAdapter.h>
#include <OpenSim/Common/Reporter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include <OpenSim/Simulation/OrientationsReference.h>
#include "ExperimentalMarker.h"
#include "ExperimentalFrame.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
InverseKinematicsStudy::InverseKinematicsStudy()
{
constructProperties();
}
InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile)
: Object(setupFile, true)
{
constructProperties();
updateFromXMLDocument();
}
InverseKinematicsStudy::~InverseKinematicsStudy()
{
}
void InverseKinematicsStudy::constructProperties()
{
constructProperty_accuracy(1e-6);
constructProperty_constraint_weight(Infinity);
Array<double> range{ Infinity, 2};
constructProperty_time_range(range);
constructProperty_base_imu_label("");
constructProperty_base_heading_axis("z");
constructProperty_model_file_name("");
constructProperty_marker_file_name("");
constructProperty_orientations_file_name("");
constructProperty_results_directory("");
}
void InverseKinematicsStudy::
previewExperimentalData(const TimeSeriesTableVec3& markers,
const TimeSeriesTable_<SimTK::Rotation>& orientations) const
{
Model previewWorld;
// Load the marker data into a TableSource that has markers
// as its output which each markers occupying its own channel
TableSourceVec3* markersSource = new TableSourceVec3(markers);
// Add the markersSource Component to the model
previewWorld.addComponent(markersSource);
// Get the underlying Table backing the the marker Source so we
// know how many markers we have and their names
const auto& markerData = markersSource->getTable();
auto& times = markerData.getIndependentColumn();
auto startEnd = getTimeRangeInUse(times);
// Create an ExperimentalMarker Component for every column in the markerData
for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) {
auto marker = new ExperimentalMarker();
marker->setName(markerData.getColumnLabel(i));
// markers are owned by the model
previewWorld.addComponent(marker);
// the time varying location of the marker comes from the markersSource
// Component
marker->updInput("location_in_ground").connect(
markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i)));
}
previewWorld.setUseVisualizer(true);
SimTK::State& state = previewWorld.initSystem();
state.updTime() = times[0];
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
char c;
std::cout << "press any key to visualize experimental marker data ..." << std::endl;
std::cin >> c;
for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) {
std::cout << "time: " << times[j] << "s" << std::endl;
state.setTime(times[j]);
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
}
}
void InverseKinematicsStudy::
runInverseKinematicsWithOrientationsFromFile(Model& model,
const std::string& orientationsFileName,
bool visualizeResults)
{
// Add a reporter to get IK computed coordinate values out
TableReporter* ikReporter = new TableReporter();
ikReporter->setName("ik_reporter");
auto coordinates = model.updComponentList<Coordinate>();
// Hookup reporter inputs to the individual coordinate outputs
// and lock coordinates that are translational since they cannot be
for (auto& coord : coordinates) {
ikReporter->updInput("inputs").connect(
coord.getOutput("value"), coord.getName());
if(coord.getMotionType() == Coordinate::Translational) {
coord.setDefaultLocked(true);
}
}
model.addComponent(ikReporter);
TimeSeriesTable_<SimTK::Quaternion> quatTable =
STOFileAdapter_<SimTK::Quaternion>::readFile(orientationsFileName);
std::cout << "Loading orientations as quaternions from "
<< orientationsFileName << std::endl;
auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn());
const auto axis_string = IO::Lowercase(get_base_heading_axis());
int axis = (axis_string == "x" ? 0 :
((axis_string == "y") ? 1 : 2) );
SimTK::CoordinateAxis heading{ axis };
cout << "Heading correction for base '" << get_base_imu_label()
<< "' along its '" << axis_string << "' axis." << endl;
TimeSeriesTable_<SimTK::Rotation> orientationsData =
OpenSenseUtilities::convertQuaternionsToRotations(quatTable,
startEnd, get_base_imu_label(), heading);
OrientationsReference oRefs(orientationsData);
MarkersReference mRefs{};
SimTK::Array_<CoordinateReference> coordinateReferences;
// visualize for debugging
if (visualizeResults)
model.setUseVisualizer(true);
SimTK::State& s0 = model.initSystem();
double t0 = s0.getTime();
// create the solver given the input data
const double accuracy = 1e-4;
InverseKinematicsSolver ikSolver(model, mRefs, oRefs,
coordinateReferences);
ikSolver.setAccuracy(accuracy);
auto& times = oRefs.getTimes();
s0.updTime() = times[0];
ikSolver.assemble(s0);
if (visualizeResults) {
model.getVisualizer().show(s0);
model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true);
}
for (auto time : times) {
s0.updTime() = time;
ikSolver.track(s0);
if (visualizeResults)
model.getVisualizer().show(s0);
else
cout << "Solved frame at time: " << time << endl;
// realize to report to get reporter to pull values from model
model.realizeReport(s0);
}
auto report = ikReporter->getTable();
auto eix = orientationsFileName.rfind(".");
auto stix = orientationsFileName.rfind("/") + 1;
IO::makeDir(get_results_directory());
std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix);
std::string outputFile = get_results_directory() + "/" + outName;
// Convert to degrees to compare with marker-based IK
// but only for rotational coordinates
model.getSimbodyEngine().convertRadiansToDegrees(report);
report.updTableMetaData().setValueForKey<string>("name", outName);
STOFileAdapter_<double>::write(report, outputFile + ".mot");
std::cout << "Wrote IK with IMU tracking results to: '" <<
outputFile << "'." << std::endl;
}
// main driver
bool InverseKinematicsStudy::run(bool visualizeResults)
{
if (_model.empty()) {
_model.reset(new Model(get_model_file_name()));
}
runInverseKinematicsWithOrientationsFromFile(*_model,
get_orientations_file_name(),
visualizeResults);
return true;
}
SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse(
const std::vector<double>& times ) const
{
int nt = static_cast<int>(times.size());
int startIx = 0;
int endIx = nt-1;
for (int i = 0; i < nt; ++i) {
if (times[i] <= get_time_range(0)) {
startIx = i;
}
else {
break;
}
}
for (int i = nt - 1; i > 0; --i) {
if (times[i] >= get_time_range(1)) {
endIx= i;
}
else {
break;
}
}
SimTK::Array_<int> retArray;
retArray.push_back(startIx);
retArray.push_back(endIx);
return retArray;
}
TimeSeriesTable_<SimTK::Vec3>
InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile)
{
auto markers = TRCFileAdapter::readFile(markerFile);
std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers "
<< " and " << markers.getNumRows() << " rows of data." << std::endl;
if (markers.hasTableMetaDataKey("Units")) {
std::cout << markerFile << " has Units meta data." << std::endl;
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
if (value.getValue<std::string>() == "mm") {
std::cout << "Marker data in mm, converting to m." << std::endl;
for (size_t i = 0; i < markers.getNumRows(); ++i) {
markers.updRowAtIndex(i) *= 0.001;
}
markers.updTableMetaData().removeValueForKey("Units");
markers.updTableMetaData().setValueForKey<std::string>("Units", "m");
}
}
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
return markers;
}
|
Remove unnecessary additions to the output table's metadata.
|
Remove unnecessary additions to the output table's metadata.
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
2facba08fa01d7025fcb897a435ea3ed9a789d3f
|
utils/command_line.hpp
|
utils/command_line.hpp
|
#pragma once
#include <algorithm>
#include <iomanip>
#include <list>
#include <sstream>
#include <string>
#include <vector>
namespace utils
{
class command_line
{
std::ostringstream _help;
std::list<std::string> _args;
public:
command_line(int argc, const char ** argv)
{
std::copy(argv + 1, argv + argc, std::inserter(_args, _args.end()));
}
std::string help()
{
return _help.str();
}
void check_unknown()
{
if (!_args.empty())
throw std::runtime_error("Command line argument \"" + *_args.begin()
+ "\" is not supported");
}
bool get_flag(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description)
{
auto it = find(short_syntax, long_syntax, description, "");
if (it == _args.end()) return false;
_args.erase(it);
return true;
}
std::string get_string(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
auto value = find(short_syntax, long_syntax, description, default_value);
if (value == _args.end()) return default_value;
auto flag = value++;
if (value == _args.end()) return default_value;
std::string result = *value;
_args.erase(flag);
_args.erase(value);
return result;
}
std::vector<std::string> get_strings(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value = "")
{
try
{
std::vector<std::string> values;
std::string _args = get_string(short_syntax, long_syntax, description, default_value);
for_each_token(_args, [&](std::string x)
{
values.push_back(x);
});
return values;
}
catch (...)
{
throw std::runtime_error("Command line argument " + long_syntax + " is invalid");
}
}
int get_integer(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
try
{
return std::stoi(get_string(short_syntax, long_syntax, description, default_value));
}
catch (...)
{
throw std::runtime_error("Command line argument " + long_syntax + " is invalid");
}
}
template <typename Value, typename Selector>
std::vector<Value> get_values(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value,
Selector selector)
{
std::vector<Value> values;
std::string _args = get_string(short_syntax, long_syntax, description, default_value);
for_each_token(_args, [&](std::string x)
{
values.push_back(selector(x));
});
return values;
}
std::vector<int> get_integers(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
return get_values<int>(short_syntax, long_syntax, description, default_value,
[](std::string s)
{
return std::stoi(s);
});
}
private:
std::list<std::string>::iterator find(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
_help << " " << std::left << std::setw(3) << short_syntax << std::setw(16) << long_syntax
<< description;
if (default_value.size() > 0) _help << " (default: " << default_value << ")";
_help << std::endl;
return std::find_if(_args.begin(), _args.end(), [&](const std::string & arg)
{
return arg == short_syntax || arg == long_syntax;
});
}
template <typename Function>
static void for_each_token(const std::string & input, Function fn)
{
if (input.empty()) return;
size_t start = 0;
for (;;)
{
const size_t stop = input.find(',', start);
std::string token = input.substr(start, stop - start);
try
{
fn(token);
}
catch (...)
{
throw std::runtime_error("Unexpected token: " + token);
}
if (stop == std::string::npos) break;
start = stop + 1u;
}
}
};
}
|
#pragma once
#include <algorithm>
#include <iterator>
#include <iomanip>
#include <list>
#include <sstream>
#include <string>
#include <vector>
namespace utils
{
class command_line
{
std::ostringstream _help;
std::list<std::string> _args;
public:
command_line(int argc, const char ** argv)
{
std::copy(argv + 1, argv + argc, std::inserter(_args, _args.end()));
}
std::string help()
{
return _help.str();
}
void check_unknown()
{
if (!_args.empty())
throw std::runtime_error("Command line argument \"" + *_args.begin()
+ "\" is not supported");
}
bool get_flag(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description)
{
auto it = find(short_syntax, long_syntax, description, "");
if (it == _args.end()) return false;
_args.erase(it);
return true;
}
std::string get_string(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
auto value = find(short_syntax, long_syntax, description, default_value);
if (value == _args.end()) return default_value;
auto flag = value++;
if (value == _args.end()) return default_value;
std::string result = *value;
_args.erase(flag);
_args.erase(value);
return result;
}
std::vector<std::string> get_strings(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value = "")
{
try
{
std::vector<std::string> values;
std::string _args = get_string(short_syntax, long_syntax, description, default_value);
for_each_token(_args, [&](std::string x)
{
values.push_back(x);
});
return values;
}
catch (...)
{
throw std::runtime_error("Command line argument " + long_syntax + " is invalid");
}
}
int get_integer(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
try
{
return std::stoi(get_string(short_syntax, long_syntax, description, default_value));
}
catch (...)
{
throw std::runtime_error("Command line argument " + long_syntax + " is invalid");
}
}
template <typename Value, typename Selector>
std::vector<Value> get_values(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value,
Selector selector)
{
std::vector<Value> values;
std::string _args = get_string(short_syntax, long_syntax, description, default_value);
for_each_token(_args, [&](std::string x)
{
values.push_back(selector(x));
});
return values;
}
std::vector<int> get_integers(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
return get_values<int>(short_syntax, long_syntax, description, default_value,
[](std::string s)
{
return std::stoi(s);
});
}
private:
std::list<std::string>::iterator find(const std::string & short_syntax,
const std::string & long_syntax,
const std::string & description,
const std::string & default_value)
{
_help << " " << std::left << std::setw(3) << short_syntax << std::setw(16) << long_syntax
<< description;
if (default_value.size() > 0) _help << " (default: " << default_value << ")";
_help << std::endl;
return std::find_if(_args.begin(), _args.end(), [&](const std::string & arg)
{
return arg == short_syntax || arg == long_syntax;
});
}
template <typename Function>
static void for_each_token(const std::string & input, Function fn)
{
if (input.empty()) return;
size_t start = 0;
for (;;)
{
const size_t stop = input.find(',', start);
std::string token = input.substr(start, stop - start);
try
{
fn(token);
}
catch (...)
{
throw std::runtime_error("Unexpected token: " + token);
}
if (stop == std::string::npos) break;
start = stop + 1u;
}
}
};
}
|
Add missing include.
|
Add missing include.
|
C++
|
bsd-2-clause
|
bureau14/qdb-benchmark,solatis/qdb-benchmark,bureau14/qdb-benchmark,solatis/qdb-benchmark,solatis/qdb-benchmark,solatis/qdb-benchmark,bureau14/qdb-benchmark,bureau14/qdb-benchmark
|
7c4a81f96cc4afb924bed3305475331ded0e5e35
|
src/render_engine/vulkan/auto_allocating_buffer.cpp
|
src/render_engine/vulkan/auto_allocating_buffer.cpp
|
/*!
* \author ddubois
* \date 12-Feb-18.
*/
#include "auto_allocating_buffer.hpp"
#include "../../util/logger.hpp"
#include "fmt/format.h"
namespace nova::renderer {
auto_buffer::auto_buffer(const std::string& name,
VmaAllocator allocator,
const VkBufferCreateInfo& create_info,
const uint64_t alignment,
const bool mapped = false)
: uniform_buffer(name, allocator, create_info, alignment, mapped) {
chunks.emplace_back(auto_buffer_chunk{VkDeviceSize(0), create_info.size});
}
auto_buffer::auto_buffer(auto_buffer&& old) noexcept : uniform_buffer(std::forward<uniform_buffer>(old)) {
chunks = std::move(old.chunks);
old.chunks.clear();
}
auto_buffer& auto_buffer::operator=(auto_buffer&& old) noexcept {
uniform_buffer::operator=(std::forward<uniform_buffer>(old));
chunks = std::move(old.chunks);
old.chunks.clear();
return *this;
}
VkDescriptorBufferInfo auto_buffer::allocate_space(uint64_t size) {
size = size > alignment ? size : alignment;
int32_t index_to_allocate_from = -1;
if(!chunks.empty()) {
// Iterate backwards so that inserting or deleting has a minimal cost
for(int32_t i = static_cast<int32_t>(chunks.size() - 1); i >= 0; --i) {
if(chunks[static_cast<uint32_t>(i)].range >= size) {
index_to_allocate_from = i;
}
}
}
VkDescriptorBufferInfo ret_val;
if(index_to_allocate_from == -1) {
// Whoops, couldn't find anything
const std::string msg = fmt::
format(fmt("No big enough slots in the buffer. There's {:d} slots. If there's a lot then you got some fragmentation"),
chunks.size());
NOVA_LOG(ERROR) << msg;
// Halt execution like a boss
throw std::runtime_error(msg);
}
auto& chunk_to_allocate_from = chunks[static_cast<uint32_t>(index_to_allocate_from)];
if(chunk_to_allocate_from.range == size) {
// Easy: unallocate the chunk, return the chunks
ret_val = VkDescriptorBufferInfo{buffer, chunk_to_allocate_from.offset, chunk_to_allocate_from.range};
chunks.erase(chunks.begin() + index_to_allocate_from);
// NOLINTNEXTLINE(cppcoreguidelines-avoid-goto)
goto end;
}
// The chunk is bigger than we need. Allocate at the beginning of it so our iteration algorithm finds the next
// free chunk nice and early, then shrink it
ret_val = VkDescriptorBufferInfo{buffer, chunk_to_allocate_from.offset, size};
chunk_to_allocate_from.offset += size;
chunk_to_allocate_from.range -= size;
end:
return ret_val;
}
void auto_buffer::free_allocation(const VkDescriptorBufferInfo& to_free) {
// This one will be hard...
// Properly we should try to find an allocated space of our size and merge the two allocations on either side of
// it... but that's marginally harder (maybe I'll do it) so let's just try to find the first slot it will fit
const auto to_free_end = to_free.offset + to_free.range;
auto& first_chunk = chunks[0];
auto& last_chunk = chunks[chunks.size() - 1];
if(chunks.empty()) {
chunks.emplace_back(auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
if(last_chunk.offset + last_chunk.range == to_free.offset) {
last_chunk.range += to_free.range;
return;
}
if(last_chunk.offset + last_chunk.range < to_free.offset) {
chunks.emplace_back(auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
if(to_free_end == first_chunk.offset) {
first_chunk.offset -= to_free.range;
first_chunk.range += to_free.range;
return;
}
if(to_free_end < first_chunk.offset) {
chunks.emplace(chunks.begin(), auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
for(auto i = chunks.size() - 1; i >= 1; i++) {
auto& behind_space = chunks[i - 1];
auto& ahead_space = chunks[i];
const auto behind_space_end = behind_space.offset + behind_space.range;
const auto space_between_allocs = space_between(behind_space, ahead_space);
// Do we fit nicely between the two things?
if(space_between_allocs == to_free.range) {
// combine these nerds
chunks[i - 1].range += to_free.range + ahead_space.range;
chunks.erase(chunks.begin() + static_cast<long>(i));
return;
}
// Do we fit up against one of the two things?
if(space_between_allocs > to_free.range) {
if(behind_space_end == to_free.offset) {
chunks[i - 1].range += to_free.range;
return;
}
if(to_free_end == ahead_space.offset) {
chunks[i].offset -= to_free.range;
chunks[i].range += to_free.range;
return;
}
chunks.emplace(chunks.begin() + static_cast<long>(i), auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
}
// We got here... without returning our allocation to the pool. Uhm... Did we double-allocate something? This is
// a bug in my allocator and not something that should happen during Nova so let's just crash
NOVA_LOG(FATAL) << "Could not return allocation {offset=" << to_free.offset << " range=" << to_free.range
<< "} which should not happen. There's probably a bug in the allocator and you need to debug it";
}
VkDeviceSize space_between(const auto_buffer_chunk& first, const auto_buffer_chunk& last) {
return last.offset - (first.offset + first.range);
}
} // namespace nova::renderer
|
/*!
* \author ddubois
* \date 12-Feb-18.
*/
#include "auto_allocating_buffer.hpp"
#include "../../util/logger.hpp"
#include "fmt/format.h"
namespace nova::renderer {
auto_buffer::auto_buffer(const std::string& name,
VmaAllocator allocator,
const VkBufferCreateInfo& create_info,
const uint64_t alignment,
const bool mapped = false)
: uniform_buffer(name, allocator, create_info, alignment, mapped) {
chunks.emplace_back(auto_buffer_chunk{VkDeviceSize(0), create_info.size});
}
auto_buffer::auto_buffer(auto_buffer&& old) noexcept : uniform_buffer(std::forward<uniform_buffer>(old)) {
chunks = std::move(old.chunks);
old.chunks.clear();
}
auto_buffer& auto_buffer::operator=(auto_buffer&& old) noexcept {
uniform_buffer::operator=(std::forward<uniform_buffer>(old));
chunks = std::move(old.chunks);
old.chunks.clear();
return *this;
}
VkDescriptorBufferInfo auto_buffer::allocate_space(uint64_t size) {
size = size > alignment ? size : alignment;
int32_t index_to_allocate_from = -1;
if(!chunks.empty()) {
// Iterate backwards so that inserting or deleting has a minimal cost
for(int32_t i = static_cast<int32_t>(chunks.size() - 1); i >= 0; --i) {
if(chunks[static_cast<uint32_t>(i)].range >= size) {
index_to_allocate_from = i;
}
}
}
VkDescriptorBufferInfo ret_val;
if(index_to_allocate_from == -1) {
// Whoops, couldn't find anything
const std::string msg = fmt::
format(fmt("No big enough slots in the buffer. There's {:d} slots. If there's a lot then you got some fragmentation"),
chunks.size());
NOVA_LOG(ERROR) << msg;
// Halt execution like a boss
throw std::runtime_error(msg);
}
auto& chunk_to_allocate_from = chunks[static_cast<uint32_t>(index_to_allocate_from)];
if(chunk_to_allocate_from.range == size) {
// Easy: unallocate the chunk, return the chunks
ret_val = VkDescriptorBufferInfo{buffer, chunk_to_allocate_from.offset, chunk_to_allocate_from.range};
chunks.erase(chunks.begin() + index_to_allocate_from);
return ret_val;
}
// The chunk is bigger than we need. Allocate at the beginning of it so our iteration algorithm finds the next
// free chunk nice and early, then shrink it
ret_val = VkDescriptorBufferInfo{buffer, chunk_to_allocate_from.offset, size};
chunk_to_allocate_from.offset += size;
chunk_to_allocate_from.range -= size;
return ret_val;
}
void auto_buffer::free_allocation(const VkDescriptorBufferInfo& to_free) {
// This one will be hard...
// Properly we should try to find an allocated space of our size and merge the two allocations on either side of
// it... but that's marginally harder (maybe I'll do it) so let's just try to find the first slot it will fit
const auto to_free_end = to_free.offset + to_free.range;
auto& first_chunk = chunks[0];
auto& last_chunk = chunks[chunks.size() - 1];
if(chunks.empty()) {
chunks.emplace_back(auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
if(last_chunk.offset + last_chunk.range == to_free.offset) {
last_chunk.range += to_free.range;
return;
}
if(last_chunk.offset + last_chunk.range < to_free.offset) {
chunks.emplace_back(auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
if(to_free_end == first_chunk.offset) {
first_chunk.offset -= to_free.range;
first_chunk.range += to_free.range;
return;
}
if(to_free_end < first_chunk.offset) {
chunks.emplace(chunks.begin(), auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
for(auto i = chunks.size() - 1; i >= 1; i++) {
auto& behind_space = chunks[i - 1];
auto& ahead_space = chunks[i];
const auto behind_space_end = behind_space.offset + behind_space.range;
const auto space_between_allocs = space_between(behind_space, ahead_space);
// Do we fit nicely between the two things?
if(space_between_allocs == to_free.range) {
// combine these nerds
chunks[i - 1].range += to_free.range + ahead_space.range;
chunks.erase(chunks.begin() + static_cast<long>(i));
return;
}
// Do we fit up against one of the two things?
if(space_between_allocs > to_free.range) {
if(behind_space_end == to_free.offset) {
chunks[i - 1].range += to_free.range;
return;
}
if(to_free_end == ahead_space.offset) {
chunks[i].offset -= to_free.range;
chunks[i].range += to_free.range;
return;
}
chunks.emplace(chunks.begin() + static_cast<long>(i), auto_buffer_chunk{to_free.offset, to_free.range});
return;
}
}
// We got here... without returning our allocation to the pool. Uhm... Did we double-allocate something? This is
// a bug in my allocator and not something that should happen during Nova so let's just crash
NOVA_LOG(FATAL) << "Could not return allocation {offset=" << to_free.offset << " range=" << to_free.range
<< "} which should not happen. There's probably a bug in the allocator and you need to debug it";
}
VkDeviceSize space_between(const auto_buffer_chunk& first, const auto_buffer_chunk& last) {
return last.offset - (first.offset + first.range);
}
} // namespace nova::renderer
|
Remove goto
|
Remove goto
|
C++
|
lgpl-2.1
|
DethRaid/vulkan-mod,DethRaid/vulkan-mod,DethRaid/vulkan-mod
|
2bd3824790cdf12863a1594c3a206370a4ad6557
|
src/Standard/Standard_Macro.hxx
|
src/Standard/Standard_Macro.hxx
|
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// Purpose: This file is intended to be the first file #included to any
// Open CASCADE source. It defines platform-specific pre-processor
// macros necessary for correct compilation of Open CASCADE code
#ifndef _Standard_Macro_HeaderFile
# define _Standard_Macro_HeaderFile
// Standard OCC macros: Handle(), STANDARD_TYPE()
# define Handle(ClassName) Handle_##ClassName
# define STANDARD_TYPE(aType) aType##_Type_()
#if defined(__cplusplus) && (__cplusplus >= 201100L)
// part of C++11 standard
#define Standard_OVERRIDE override
#elif defined(_MSC_VER) && (_MSC_VER >= 1700)
// MSVC extension since VS2012
#define Standard_OVERRIDE override
#else
#define Standard_OVERRIDE
#endif
//======================================================
// Windows-specific definitions
//======================================================
#if (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) || defined(__MINGW64__)) && !defined(WNT)
#define WNT
#endif
# if defined(_WIN32) && !defined(HAVE_NO_DLL)
# ifndef Standard_EXPORT
# define Standard_EXPORT __declspec( dllexport )
// For global variables :
# define Standard_EXPORTEXTERN __declspec( dllexport ) extern
# define Standard_EXPORTEXTERNC extern "C" __declspec( dllexport )
# endif /* Standard_EXPORT */
# ifndef Standard_IMPORT
# define Standard_IMPORT __declspec( dllimport ) extern
# define Standard_IMPORTC extern "C" __declspec( dllimport )
# endif /* Standard_IMPORT */
// We must be careful including windows.h: it is really poisonous stuff!
// The most annoying are #defines of many identifiers that you could use in
// normal code without knowing that Windows has its own knowledge of them...
// So lets protect ourselves by switching OFF as much as possible of this in advance.
// If someone needs more from windows.h, he is encouraged to #undef these symbols
// or include windows.h prior to any OCCT stuff.
// Note that we define each symbol to itself, so that it still can be used
// e.g. as name of variable, method etc.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN /* exclude extra Windows stuff */
#endif
#ifndef NOMINMAX
#define NOMINMAX /* avoid #define min() and max() */
#endif
#ifndef NOMSG
#define NOMSG NOMSG /* avoid #define SendMessage etc. */
#endif
#ifndef NODRAWTEXT
#define NODRAWTEXT NODRAWTEXT /* avoid #define DrawText etc. */
#endif
#ifndef NONLS
#define NONLS NONLS /* avoid #define CompareString etc. */
#endif
#ifndef NOGDI
#define NOGDI NOGDI /* avoid #define SetPrinter (winspool.h) etc. */
#endif
#ifndef NOSERVICE
#define NOSERVICE NOSERVICE
#endif
#ifndef NOKERNEL
#define NOKERNEL NOKERNEL
#endif
#ifndef NOUSER
#define NOUSER NOUSER
#endif
#ifndef NOMCX
#define NOMCX NOMCX
#endif
#ifndef NOIME
#define NOIME NOIME
#endif
# else /* WNT */
//======================================================
// UNIX definitions
//======================================================
# ifndef Standard_EXPORT
# define Standard_EXPORT
// For global variables :
# define Standard_EXPORTEXTERN extern
# define Standard_EXPORTEXTERNC extern "C"
# endif /* Standard_EXPORT */
# ifndef Standard_IMPORT
# define Standard_IMPORT extern
# define Standard_IMPORTC extern "C"
# endif /* Standard_IMPORT */
// Compatibility with old SUN compilers
// This preprocessor directive is a kludge to get around
// a bug in the Sun Workshop 5.0 compiler, it keeps the
// /usr/include/memory.h file from being #included
// with an incompatible extern "C" definition of memchr
// October 18, 2000 <[email protected]>
#if defined(__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT == 5)
#define _MEMORY_H
#endif
# endif /* WNT */
//======================================================
// Other
//======================================================
# ifndef __Standard_API
//# ifdef WNT
# if !defined(_WIN32) || defined(__Standard_DLL) || defined(__FSD_DLL) || defined(__MMgt_DLL) || defined(__OSD_DLL) || defined(__Plugin_DLL) || defined(__Quantity_DLL) || defined(__Resource_DLL) || defined(__SortTools_DLL) || defined(__StdFail_DLL) || defined(__Storage_DLL) || defined(__TColStd_DLL) || defined(__TCollection_DLL) || defined(__TShort_DLL) || defined(__Units_DLL) || defined(__UnitsAPI_DLL) || defined(__Dico_DLL) || defined(__Message_DLL)
# define __Standard_API Standard_EXPORT
# define __Standard_APIEXTERN Standard_EXPORTEXTERN
# ifdef __BORLANDC__
# define __Standard_APIEXTERNC Standard_EXPORTEXTERNC
# endif
# else
# define __Standard_API Standard_IMPORT
# define __Standard_APIEXTERN Standard_IMPORT
# ifdef __BORLANDC__
# define __Standard_APIEXTERNC Standard_IMPORTC
# endif
# endif // __Standard_DLL
//# else
//# define __Standard_API
//# endif // WNT
# endif // __Standard_API
#endif
|
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// Purpose: This file is intended to be the first file #included to any
// Open CASCADE source. It defines platform-specific pre-processor
// macros necessary for correct compilation of Open CASCADE code
#ifndef _Standard_Macro_HeaderFile
# define _Standard_Macro_HeaderFile
// Standard OCC macros: Handle(), STANDARD_TYPE()
# define Handle(ClassName) Handle_##ClassName
# define STANDARD_TYPE(aType) aType##_Type_()
#if defined(__cplusplus) && (__cplusplus >= 201100L)
// part of C++11 standard
#define Standard_OVERRIDE override
#elif defined(_MSC_VER) && (_MSC_VER >= 1700)
// MSVC extension since VS2012
#define Standard_OVERRIDE override
#else
#define Standard_OVERRIDE
#endif
//======================================================
// Windows-specific definitions
//======================================================
#if (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) || defined(__MINGW64__)) && !defined(WNT)
#define WNT
#endif
# if defined(_WIN32)
// We must be careful including windows.h: it is really poisonous stuff!
// The most annoying are #defines of many identifiers that you could use in
// normal code without knowing that Windows has its own knowledge of them...
// So lets protect ourselves by switching OFF as much as possible of this in advance.
// If someone needs more from windows.h, he is encouraged to #undef these symbols
// or include windows.h prior to any OCCT stuff.
// Note that we define each symbol to itself, so that it still can be used
// e.g. as name of variable, method etc.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN /* exclude extra Windows stuff */
#endif
#ifndef NOMINMAX
#define NOMINMAX /* avoid #define min() and max() */
#endif
#ifndef NOMSG
#define NOMSG NOMSG /* avoid #define SendMessage etc. */
#endif
#ifndef NODRAWTEXT
#define NODRAWTEXT NODRAWTEXT /* avoid #define DrawText etc. */
#endif
#ifndef NONLS
#define NONLS NONLS /* avoid #define CompareString etc. */
#endif
#ifndef NOGDI
#define NOGDI NOGDI /* avoid #define SetPrinter (winspool.h) etc. */
#endif
#ifndef NOSERVICE
#define NOSERVICE NOSERVICE
#endif
#ifndef NOKERNEL
#define NOKERNEL NOKERNEL
#endif
#ifndef NOUSER
#define NOUSER NOUSER
#endif
#ifndef NOMCX
#define NOMCX NOMCX
#endif
#ifndef NOIME
#define NOIME NOIME
#endif
#endif
# if defined(_WIN32) && !defined(HAVE_NO_DLL)
# ifndef Standard_EXPORT
# define Standard_EXPORT __declspec( dllexport )
// For global variables :
# define Standard_EXPORTEXTERN __declspec( dllexport ) extern
# define Standard_EXPORTEXTERNC extern "C" __declspec( dllexport )
# endif /* Standard_EXPORT */
# ifndef Standard_IMPORT
# define Standard_IMPORT __declspec( dllimport ) extern
# define Standard_IMPORTC extern "C" __declspec( dllimport )
# endif /* Standard_IMPORT */
# else /* WNT */
//======================================================
// UNIX definitions
//======================================================
# ifndef Standard_EXPORT
# define Standard_EXPORT
// For global variables :
# define Standard_EXPORTEXTERN extern
# define Standard_EXPORTEXTERNC extern "C"
# endif /* Standard_EXPORT */
# ifndef Standard_IMPORT
# define Standard_IMPORT extern
# define Standard_IMPORTC extern "C"
# endif /* Standard_IMPORT */
// Compatibility with old SUN compilers
// This preprocessor directive is a kludge to get around
// a bug in the Sun Workshop 5.0 compiler, it keeps the
// /usr/include/memory.h file from being #included
// with an incompatible extern "C" definition of memchr
// October 18, 2000 <[email protected]>
#if defined(__SUNPRO_CC_COMPAT) && (__SUNPRO_CC_COMPAT == 5)
#define _MEMORY_H
#endif
# endif /* WNT */
//======================================================
// Other
//======================================================
# ifndef __Standard_API
//# ifdef WNT
# if !defined(_WIN32) || defined(__Standard_DLL) || defined(__FSD_DLL) || defined(__MMgt_DLL) || defined(__OSD_DLL) || defined(__Plugin_DLL) || defined(__Quantity_DLL) || defined(__Resource_DLL) || defined(__SortTools_DLL) || defined(__StdFail_DLL) || defined(__Storage_DLL) || defined(__TColStd_DLL) || defined(__TCollection_DLL) || defined(__TShort_DLL) || defined(__Units_DLL) || defined(__UnitsAPI_DLL) || defined(__Dico_DLL) || defined(__Message_DLL)
# define __Standard_API Standard_EXPORT
# define __Standard_APIEXTERN Standard_EXPORTEXTERN
# ifdef __BORLANDC__
# define __Standard_APIEXTERNC Standard_EXPORTEXTERNC
# endif
# else
# define __Standard_API Standard_IMPORT
# define __Standard_APIEXTERN Standard_IMPORT
# ifdef __BORLANDC__
# define __Standard_APIEXTERNC Standard_IMPORTC
# endif
# endif // __Standard_DLL
//# else
//# define __Standard_API
//# endif // WNT
# endif // __Standard_API
#endif
|
Fix standard_macro.hxx so it allow static building on MSVC
|
Fix standard_macro.hxx so it allow static building on MSVC
|
C++
|
lgpl-2.1
|
BenoitPerrot/oce,tpaviot/oce,tpaviot/oce,BenoitPerrot/oce,tpaviot/oce,tpaviot/oce,tpaviot/oce,BenoitPerrot/oce,BenoitPerrot/oce,BenoitPerrot/oce
|
a2b95f7e29e416c768f184bd9076a9b941bb8c15
|
You-DataStore-Tests/internal/operations_test.cpp
|
You-DataStore-Tests/internal/operations_test.cpp
|
#include "stdafx.h"
#include <CppUnitTest.h>
#include "../mocks.h"
#include "internal/operations/erase_operation.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/serialization_operation.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
/// Mock xml_document for \ref DataStoreOperationsTest
static pugi::xml_document mockDocument;
/// Unit Test Class for DataStore class
TEST_CLASS(DataStoreOperationsTest) {
public:
static void initializeMockDocument() {
mockDocument.reset();
pugi::xml_node node = mockDocument.append_child(L"task");
node.append_attribute(L"id").set_value(L"0");
}
TEST_METHOD(serializeOperation) {
pugi::xml_document document;
pugi::xml_node taskNode = document.append_child();
Internal::SerializationOperation::serialize(task1, taskNode);
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(deserializeOperation) {
pugi::xml_document document;
pugi::xml_node taskNode = document.append_child();
taskNode.append_child(L"elementName").
append_child(pugi::xml_node_type::node_pcdata).set_value(L"pcdata");
SerializedTask task =
Internal::SerializationOperation::deserialize(taskNode);
Assert::AreEqual(L"pcdata", task.at(L"elementName").c_str());
}
TEST_METHOD(postWithNewId) {
pugi::xml_document document;
Assert::IsTrue(document.first_child().empty());
Internal::PostOperation post(0, task1);
bool status = post.run(document);
Assert::IsTrue(status);
// Check the content
pugi::xml_node taskNode = document.child(L"task");
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(postWithUsedId) {
initializeMockDocument();
Internal::PostOperation post(0, task1);
bool status = post.run(mockDocument);
Assert::IsFalse(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::IsTrue(taskNode.first_child().empty());
}
TEST_METHOD(putWithExistingId) {
initializeMockDocument();
Internal::PutOperation put(0, task1);
bool status = put.run(mockDocument);
Assert::IsTrue(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(putNonExistentId) {
initializeMockDocument();
Internal::PutOperation put(1, task1);
bool status = put.run(mockDocument);
Assert::IsFalse(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::AreEqual(L"0", taskNode.attribute(L"id").value());
}
TEST_METHOD(eraseExistingId) {
initializeMockDocument();
Internal::EraseOperation erase(0);
bool status = erase.run(mockDocument);
Assert::IsTrue(status);
Assert::IsTrue(mockDocument.first_child().empty());
}
TEST_METHOD(eraseNonExistentId) {
initializeMockDocument();
Internal::EraseOperation erase(1);
bool status = erase.run(mockDocument);
Assert::IsFalse(status);
Assert::IsFalse(mockDocument.first_child().empty());
}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
|
#include "stdafx.h"
#include <CppUnitTest.h>
#include "../mocks.h"
#include "internal/operations/erase_operation.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/operations/serialization_operation.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace DataStore {
namespace UnitTests {
/// Mock xml_document for \ref DataStoreOperationsTest
static pugi::xml_document mockDocument;
/// Unit Test Class for DataStore class
TEST_CLASS(DataStoreOperationsTest) {
public:
/// Create a mock xml_document containing a task with content
/// as specified in \ref task1
TEST_METHOD_INITIALIZE(initializeMockDocument) {
mockDocument.reset();
pugi::xml_node node = mockDocument.append_child(L"task");
node.append_attribute(L"id").set_value(L"0");
node.append_child(TASK_ID.c_str()).
append_child(pugi::xml_node_type::node_pcdata).
set_value(task1.at(TASK_ID).c_str());
node.append_child(DESCRIPTION.c_str()).
append_child(pugi::xml_node_type::node_pcdata).
set_value(task1.at(DESCRIPTION).c_str());
node.append_child(DEADLINE.c_str()).
append_child(pugi::xml_node_type::node_pcdata).
set_value(task1.at(DEADLINE).c_str());
node.append_child(PRIORITY.c_str()).
append_child(pugi::xml_node_type::node_pcdata).
set_value(task1.at(PRIORITY).c_str());
node.append_child(DEPENDENCIES.c_str()).
append_child(pugi::xml_node_type::node_pcdata).
set_value(task1.at(DEPENDENCIES).c_str());
}
TEST_METHOD(serializeOperation) {
pugi::xml_document document;
pugi::xml_node taskNode = document.append_child();
Internal::SerializationOperation::serialize(task1, taskNode);
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(deserializeOperation) {
pugi::xml_document document;
pugi::xml_node taskNode = document.append_child();
taskNode.append_child(L"elementName").
append_child(pugi::xml_node_type::node_pcdata).set_value(L"pcdata");
SerializedTask task =
Internal::SerializationOperation::deserialize(taskNode);
Assert::AreEqual(L"pcdata", task.at(L"elementName").c_str());
}
TEST_METHOD(postWithNewId) {
pugi::xml_document document;
Assert::IsTrue(document.first_child().empty());
Internal::PostOperation post(0, task1);
bool status = post.run(document);
Assert::IsTrue(status);
// Check the content
pugi::xml_node taskNode = document.child(L"task");
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(postWithUsedId) {
initializeMockDocument();
Internal::PostOperation post(0, task1);
bool status = post.run(mockDocument);
Assert::IsFalse(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::IsTrue(taskNode.first_child().empty());
}
TEST_METHOD(putWithExistingId) {
initializeMockDocument();
Internal::PutOperation put(0, task1);
bool status = put.run(mockDocument);
Assert::IsTrue(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::AreEqual(task1.at(TASK_ID).c_str(),
taskNode.child(TASK_ID.c_str()).child_value());
Assert::AreEqual(task1.at(DESCRIPTION).c_str(),
taskNode.child(DESCRIPTION.c_str()).child_value());
Assert::AreEqual(task1.at(DEADLINE).c_str(),
taskNode.child(DEADLINE.c_str()).child_value());
Assert::AreEqual(task1.at(PRIORITY).c_str(),
taskNode.child(PRIORITY.c_str()).child_value());
Assert::AreEqual(task1.at(DEPENDENCIES).c_str(),
taskNode.child(DEPENDENCIES.c_str()).child_value());
}
TEST_METHOD(putNonExistentId) {
initializeMockDocument();
Internal::PutOperation put(1, task1);
bool status = put.run(mockDocument);
Assert::IsFalse(status);
// Check the content
pugi::xml_node taskNode = mockDocument.child(L"task");
Assert::AreEqual(L"0", taskNode.attribute(L"id").value());
}
TEST_METHOD(eraseExistingId) {
initializeMockDocument();
Internal::EraseOperation erase(0);
bool status = erase.run(mockDocument);
Assert::IsTrue(status);
Assert::IsTrue(mockDocument.first_child().empty());
}
TEST_METHOD(eraseNonExistentId) {
initializeMockDocument();
Internal::EraseOperation erase(1);
bool status = erase.run(mockDocument);
Assert::IsFalse(status);
Assert::IsFalse(mockDocument.first_child().empty());
}
};
} // namespace UnitTests
} // namespace DataStore
} // namespace You
|
Use TEST_METHOD_INITIALIZE macro
|
Use TEST_METHOD_INITIALIZE macro
|
C++
|
mit
|
cs2103aug2014-w10-1c/main,cs2103aug2014-w10-1c/main
|
defc755f2ea52463f3b2a8388fed5f9142bd316a
|
Source/HeliumRain/UI/Components/FlareTradeRouteInfo.cpp
|
Source/HeliumRain/UI/Components/FlareTradeRouteInfo.cpp
|
#include "FlareTradeRouteInfo.h"
#include "../../Flare.h"
#include "../../Game/FlareCompany.h"
#include "../../Game/FlareTradeRoute.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#include "../../Game/FlareGame.h"
#define LOCTEXT_NAMESPACE "FlareTradeRouteInfo"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareTradeRouteInfo::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SBox)
.WidthOverride(Theme.ContentWidth)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Trade routes title
+ SVerticalBox::Slot()
.Padding(Theme.TitlePadding)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("Trade routes", "Trade routes"))
.TextStyle(&Theme.SubTitleFont)
]
// New trade route button
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(SFlareButton)
.Width(8)
.Text(LOCTEXT("NewTradeRouteButton", "Add new trade route"))
.HelpText(LOCTEXT("NewTradeRouteInfo", "Create a new trade route and edit it. You need an available fleet to create a new trade route."))
.Icon(FFlareStyleSet::GetIcon("New"))
.OnClicked(this, &SFlareTradeRouteInfo::OnNewTradeRouteClicked)
.IsDisabled(this, &SFlareTradeRouteInfo::IsNewTradeRouteDisabled)
]
// Trade route list
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.AutoHeight()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
+ SScrollBox::Slot()
[
SAssignNew(TradeRouteList, SVerticalBox)
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareTradeRouteInfo::UpdateTradeRouteList()
{
Clear();
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
TArray<UFlareTradeRoute*>& TradeRoutes = MenuManager->GetPC()->GetCompany()->GetCompanyTradeRoutes();
for (int RouteIndex = 0; RouteIndex < TradeRoutes.Num(); RouteIndex++)
{
UFlareTradeRoute* TradeRoute = TradeRoutes[RouteIndex];
FText TradeRouteName = FText::Format(LOCTEXT("TradeRouteNameFormat", "{0}{1}"),
TradeRoute->GetTradeRouteName(),
(TradeRoute->IsPaused() ? LOCTEXT("FleetTradeRoutePausedFormat", " (Paused)") : FText()));
// Add line
TradeRouteList->AddSlot()
.AutoHeight()
.HAlign(HAlign_Right)
.Padding(Theme.SmallContentPadding)
[
SNew(SVerticalBox)
// Buttons
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Inspect
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Width(7)
.Text(TradeRouteName)
.HelpText(FText(LOCTEXT("InspectHelp", "Edit this trade route")))
.OnClicked(this, &SFlareTradeRouteInfo::OnInspectTradeRouteClicked, TradeRoute)
]
// Remove
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Transparent(true)
.Text(FText())
.HelpText(LOCTEXT("RemoveTradeRouteHelp", "Remove this trade route"))
.Icon(FFlareStyleSet::GetIcon("Stop"))
.OnClicked(this, &SFlareTradeRouteInfo::OnDeleteTradeRoute, TradeRoute)
.Width(1)
]
]
// Infos
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
[
SNew(SRichTextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTradeRouteInfo::GetDetailText, TradeRoute)
.WrapTextAt(Theme.ContentWidth / 2)
.DecoratorStyleSet(&FFlareStyleSet::Get())
]
];
}
}
void SFlareTradeRouteInfo::Clear()
{
TradeRouteList->ClearChildren();
}
FText SFlareTradeRouteInfo::GetDetailText(UFlareTradeRoute* TradeRoute) const
{
FCHECK(TradeRoute);
const FFlareTradeRouteSave* TradeRouteData = TradeRoute->Save();
FCHECK(TradeRouteData);
// Get data
int32 TotalOperations = TradeRouteData->StatsOperationSuccessCount + TradeRouteData->StatsOperationFailCount;
int32 SuccessPercentage = (TotalOperations > 0) ? (FMath::RoundToInt(100.0f * TradeRouteData->StatsOperationSuccessCount / float(TotalOperations))) : 0;
int32 CreditsGain = (TradeRouteData->StatsDays > 0) ? (FMath::RoundToInt(0.01f * float(TradeRouteData->StatsMoneySell - TradeRouteData->StatsMoneyBuy) / float(TradeRouteData->StatsDays))) : 0;
// Format result
if (CreditsGain > 0)
{
return FText::Format(LOCTEXT("TradeRouteDetailsGain", " <TradeText>{0} credits per day, {1}% OK</>"),
FText::AsNumber(CreditsGain),
FText::AsNumber(SuccessPercentage));
}
else
{
return FText::Format(LOCTEXT("TradeRouteDetailsLoss", " <WarningText>{0} credits per day</>, {1}% OK"),
FText::AsNumber(CreditsGain),
FText::AsNumber(SuccessPercentage));
}
}
bool SFlareTradeRouteInfo::IsNewTradeRouteDisabled() const
{
int32 FleetCount = 0;
TArray<UFlareFleet*>& Fleets = MenuManager->GetGame()->GetPC()->GetCompany()->GetCompanyFleets();
for (int FleetIndex = 0; FleetIndex < Fleets.Num(); FleetIndex++)
{
if (!Fleets[FleetIndex]->GetCurrentTradeRoute() && Fleets[FleetIndex] != MenuManager->GetPC()->GetPlayerFleet())
{
FleetCount++;
}
}
return (FleetCount == 0);
}
void SFlareTradeRouteInfo::OnNewTradeRouteClicked()
{
UFlareTradeRoute* TradeRoute = MenuManager->GetPC()->GetCompany()->CreateTradeRoute(LOCTEXT("UntitledRoute", "Untitled Route"));
FCHECK(TradeRoute);
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareTradeRouteInfo::OnInspectTradeRouteClicked(UFlareTradeRoute* TradeRoute)
{
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareTradeRouteInfo::OnDeleteTradeRoute(UFlareTradeRoute* TradeRoute)
{
MenuManager->Confirm(LOCTEXT("AreYouSure", "ARE YOU SURE ?"),
LOCTEXT("ConfirmDeleteTR", "Do you really want to remove this trade route ?"),
FSimpleDelegate::CreateSP(this, &SFlareTradeRouteInfo::OnDeleteTradeRouteConfirmed, TradeRoute));
}
void SFlareTradeRouteInfo::OnDeleteTradeRouteConfirmed(UFlareTradeRoute* TradeRoute)
{
FCHECK(TradeRoute);
TradeRoute->Dissolve();
UpdateTradeRouteList();
}
#undef LOCTEXT_NAMESPACE
|
#include "FlareTradeRouteInfo.h"
#include "../../Flare.h"
#include "../../Game/FlareCompany.h"
#include "../../Game/FlareTradeRoute.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"
#include "../../Game/FlareGame.h"
#define LOCTEXT_NAMESPACE "FlareTradeRouteInfo"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareTradeRouteInfo::Construct(const FArguments& InArgs)
{
// Data
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
[
SNew(SBox)
.WidthOverride(Theme.ContentWidth)
.HAlign(HAlign_Fill)
[
SNew(SVerticalBox)
// Trade routes title
+ SVerticalBox::Slot()
.Padding(Theme.TitlePadding)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("Trade routes", "Trade routes"))
.TextStyle(&Theme.SubTitleFont)
]
// New trade route button
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(SFlareButton)
.Width(8)
.Text(LOCTEXT("NewTradeRouteButton", "Add new trade route"))
.HelpText(LOCTEXT("NewTradeRouteInfo", "Create a new trade route and edit it. You need an available fleet to create a new trade route."))
.Icon(FFlareStyleSet::GetIcon("New"))
.OnClicked(this, &SFlareTradeRouteInfo::OnNewTradeRouteClicked)
.IsDisabled(this, &SFlareTradeRouteInfo::IsNewTradeRouteDisabled)
]
// Trade route list
+ SVerticalBox::Slot()
.HAlign(HAlign_Left)
.AutoHeight()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
+ SScrollBox::Slot()
[
SAssignNew(TradeRouteList, SVerticalBox)
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareTradeRouteInfo::UpdateTradeRouteList()
{
Clear();
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
TArray<UFlareTradeRoute*>& TradeRoutes = MenuManager->GetPC()->GetCompany()->GetCompanyTradeRoutes();
for (int RouteIndex = 0; RouteIndex < TradeRoutes.Num(); RouteIndex++)
{
UFlareTradeRoute* TradeRoute = TradeRoutes[RouteIndex];
FText TradeRouteName = FText::Format(LOCTEXT("TradeRouteNameFormat", "{0}{1}"),
TradeRoute->GetTradeRouteName(),
(TradeRoute->IsPaused() ? LOCTEXT("FleetTradeRoutePausedFormat", " (Paused)") : FText()));
// Add line
TradeRouteList->AddSlot()
.AutoHeight()
.HAlign(HAlign_Right)
.Padding(Theme.ContentPadding)
[
SNew(SVerticalBox)
// Buttons
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
// Inspect
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Width(7)
.Text(TradeRouteName)
.HelpText(FText(LOCTEXT("InspectHelp", "Edit this trade route")))
.OnClicked(this, &SFlareTradeRouteInfo::OnInspectTradeRouteClicked, TradeRoute)
]
// Remove
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Transparent(true)
.Text(FText())
.HelpText(LOCTEXT("RemoveTradeRouteHelp", "Remove this trade route"))
.Icon(FFlareStyleSet::GetIcon("Stop"))
.OnClicked(this, &SFlareTradeRouteInfo::OnDeleteTradeRoute, TradeRoute)
.Width(1)
]
]
// Infos
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.SmallContentPadding)
[
SNew(SRichTextBlock)
.TextStyle(&Theme.TextFont)
.Text(this, &SFlareTradeRouteInfo::GetDetailText, TradeRoute)
.WrapTextAt(Theme.ContentWidth / 2)
.DecoratorStyleSet(&FFlareStyleSet::Get())
]
];
}
}
void SFlareTradeRouteInfo::Clear()
{
TradeRouteList->ClearChildren();
}
FText SFlareTradeRouteInfo::GetDetailText(UFlareTradeRoute* TradeRoute) const
{
FCHECK(TradeRoute);
const FFlareTradeRouteSave* TradeRouteData = TradeRoute->Save();
FCHECK(TradeRouteData);
// Get data
int32 TotalOperations = TradeRouteData->StatsOperationSuccessCount + TradeRouteData->StatsOperationFailCount;
int32 SuccessPercentage = (TotalOperations > 0) ? (FMath::RoundToInt(100.0f * TradeRouteData->StatsOperationSuccessCount / float(TotalOperations))) : 0;
int32 CreditsGain = (TradeRouteData->StatsDays > 0) ? (FMath::RoundToInt(0.01f * float(TradeRouteData->StatsMoneySell - TradeRouteData->StatsMoneyBuy) / float(TradeRouteData->StatsDays))) : 0;
// Format result
if (CreditsGain > 0)
{
return FText::Format(LOCTEXT("TradeRouteDetailsGain", " <TradeText>{0} credits per day, {1}% OK</>"),
FText::AsNumber(CreditsGain),
FText::AsNumber(SuccessPercentage));
}
else
{
return FText::Format(LOCTEXT("TradeRouteDetailsLoss", " <WarningText>{0} credits per day</>, {1}% OK"),
FText::AsNumber(CreditsGain),
FText::AsNumber(SuccessPercentage));
}
}
bool SFlareTradeRouteInfo::IsNewTradeRouteDisabled() const
{
int32 FleetCount = 0;
TArray<UFlareFleet*>& Fleets = MenuManager->GetGame()->GetPC()->GetCompany()->GetCompanyFleets();
for (int FleetIndex = 0; FleetIndex < Fleets.Num(); FleetIndex++)
{
if (!Fleets[FleetIndex]->GetCurrentTradeRoute() && Fleets[FleetIndex] != MenuManager->GetPC()->GetPlayerFleet())
{
FleetCount++;
}
}
return (FleetCount == 0);
}
void SFlareTradeRouteInfo::OnNewTradeRouteClicked()
{
UFlareTradeRoute* TradeRoute = MenuManager->GetPC()->GetCompany()->CreateTradeRoute(LOCTEXT("UntitledRoute", "Untitled Route"));
FCHECK(TradeRoute);
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareTradeRouteInfo::OnInspectTradeRouteClicked(UFlareTradeRoute* TradeRoute)
{
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareTradeRouteInfo::OnDeleteTradeRoute(UFlareTradeRoute* TradeRoute)
{
MenuManager->Confirm(LOCTEXT("AreYouSure", "ARE YOU SURE ?"),
LOCTEXT("ConfirmDeleteTR", "Do you really want to remove this trade route ?"),
FSimpleDelegate::CreateSP(this, &SFlareTradeRouteInfo::OnDeleteTradeRouteConfirmed, TradeRoute));
}
void SFlareTradeRouteInfo::OnDeleteTradeRouteConfirmed(UFlareTradeRoute* TradeRoute)
{
FCHECK(TradeRoute);
TradeRoute->Dissolve();
UpdateTradeRouteList();
}
#undef LOCTEXT_NAMESPACE
|
Fix trade route padding value
|
Fix trade route padding value
|
C++
|
bsd-3-clause
|
arbonagw/HeliumRain,arbonagw/HeliumRain,arbonagw/HeliumRain,arbonagw/HeliumRain,arbonagw/HeliumRain
|
d400da25e03fa67101580d6152f13de7433fc506
|
src/hdf5/Group.cpp
|
src/hdf5/Group.cpp
|
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/Group.hpp>
#include <nix/util/util.hpp>
#include <boost/multi_array.hpp>
#include <H5Gpublic.h>
namespace nix {
namespace hdf5 {
optGroup::optGroup(const Group &parent, const std::string &g_name)
: parent(parent), g_name(g_name)
{}
boost::optional<Group> optGroup::operator() (bool create) const {
if (parent.hasGroup(g_name)) {
g = boost::optional<Group>(parent.openGroup(g_name));
} else if (create) {
g = boost::optional<Group>(parent.openGroup(g_name, true));
}
return g;
}
Group::Group()
: groupId(H5I_INVALID_HID)
{}
Group::Group(const H5::Group &h5group)
: groupId(h5group.getLocId())
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(hid_t id)
: groupId(id)
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(const Group &other)
: groupId(other.groupId)
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(Group &&other) : groupId(other.groupId) {
other.groupId = H5I_INVALID_HID;
}
Group& Group::operator=(Group other)
{
using std::swap;
swap(this->groupId, other.groupId);
return *this;
}
bool Group::hasAttr(const std::string &name) const {
return H5Aexists(groupId, name.c_str());
}
void Group::removeAttr(const std::string &name) const {
H5Adelete(groupId, name.c_str());
}
bool Group::hasObject(const std::string &name) const {
// empty string should return false, not exception (which H5Lexists would)
if (name.empty()) {
return false;
}
htri_t res = H5Lexists(groupId, name.c_str(), H5P_DEFAULT);
return res;
}
size_t Group::objectCount() const {
return h5Group().getNumObjs();
}
boost::optional<Group> Group::findGroupByAttribute(const std::string &attribute, const std::string &value) const {
boost::optional<Group> ret;
// look up first direct sub-group that has given attribute with given value
for (size_t index = 0; index < objectCount(); index++) {
std::string obj_name = objectName(index);
if(hasGroup(obj_name)) {
Group group = openGroup(obj_name, false);
if(group.hasAttr(attribute)) {
std::string attr_value;
group.getAttr(attribute, attr_value);
if (attr_value == value) {
ret = group;
break;
}
}
}
}
return ret;
}
boost::optional<DataSet> Group::findDataByAttribute(const std::string &attribute, const std::string &value) const {
std::vector<DataSet> dsets;
boost::optional<DataSet> ret;
// look up all direct sub-datasets that have the given attribute
for (size_t index = 0; index < objectCount(); index++) {
std::string obj_name = objectName(index);
if(hasData(obj_name)) {
DataSet dset(h5Group().openDataSet(obj_name));
if(dset.hasAttr(attribute)) dsets.push_back(dset);
}
}
// look for first dataset with given attribute set to given value
auto found = std::find_if(dsets.begin(), dsets.end(),
[value, attribute](DataSet &dset) {
std::string attr_value;
dset.getAttr(attribute, attr_value);
return attr_value == value; });
if(found != dsets.end()) ret = *found;
return ret;
}
std::string Group::objectName(size_t index) const {
// check if index valid
if(index > objectCount()) {
throw OutOfBounds("No object at given index", index);
}
std::string str_name;
// check whether name is found by index
ssize_t name_len = H5Lget_name_by_idx(groupId,
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
NULL,
0,
H5P_DEFAULT);
if (name_len > 0) {
char* name = new char[name_len+1];
name_len = H5Lget_name_by_idx(groupId,
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
name,
name_len+1,
H5P_DEFAULT);
str_name = name;
delete [] name;
} else {
throw std::runtime_error("objectName: No object found, H5Lget_name_by_idx returned no name");
}
return str_name;
}
bool Group::hasData(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5Group().getObjinfo(name, info);
if (info.type == H5G_DATASET) {
return true;
}
}
return false;
}
void Group::removeData(const std::string &name) {
if (hasData(name))
h5Group().unlink(name);
}
DataSet Group::openData(const std::string &name) const {
H5::DataSet ds5 = h5Group().openDataSet(name);
return DataSet(ds5);
}
bool Group::hasGroup(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5Group().getObjinfo(name, info);
if (info.type == H5G_GROUP) {
return true;
}
}
return false;
}
Group Group::openGroup(const std::string &name, bool create) const {
if(!util::nameCheck(name)) throw InvalidName("openGroup");
Group g;
if (hasGroup(name)) {
g = Group(h5Group().openGroup(name));
} else if (create) {
hid_t gcpl = H5Pcreate(H5P_GROUP_CREATE);
if (gcpl < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Pcreate)");
}
//we want hdf5 to keep track of the order in which links were created so that
//the order for indexed based accessors is stable cf. issue #387
herr_t res = H5Pset_link_creation_order(gcpl, H5P_CRT_ORDER_TRACKED|H5P_CRT_ORDER_INDEXED);
if (res < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Pset_link_cr...)");
}
hid_t h5_gid = H5Gcreate2(groupId, name.c_str(), H5P_DEFAULT, gcpl, H5P_DEFAULT);
H5Pclose(gcpl);
if (h5_gid < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Gcreate2)");
}
g = Group(H5::Group(h5_gid));
} else {
throw std::runtime_error("Unable to open group with name '" + name + "'!");
}
return g;
}
optGroup Group::openOptGroup(const std::string &name) {
if(!util::nameCheck(name)) throw InvalidName("openOptGroup");
return optGroup(*this, name);
}
void Group::removeGroup(const std::string &name) {
if (hasGroup(name))
h5Group().unlink(name);
}
void Group::renameGroup(const std::string &old_name, const std::string &new_name) {
if(!util::nameCheck(new_name)) throw InvalidName("renameGroup");
if (hasGroup(old_name)) {
h5Group().move(old_name, new_name);
}
}
bool Group::operator==(const Group &group) const {
return groupId == group.groupId;
}
bool Group::operator!=(const Group &group) const {
return groupId != group.groupId;
}
H5::Group Group::h5Group() const {
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
return H5::Group(groupId);
} else {
return H5::Group();
}
}
Group Group::createLink(const Group &target, const std::string &link_name) {
if(!util::nameCheck(link_name)) throw InvalidName("createLink");
herr_t error = H5Lcreate_hard(target.groupId, ".", groupId, link_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
if (error)
throw std::runtime_error("Unable to create link " + link_name);
return openGroup(link_name, false);
}
// TODO implement some kind of roll-back in order to avoid half renamed links.
bool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {
if(!util::nameCheck(new_name)) throw InvalidName("renameAllLinks");
bool renamed = false;
if (hasGroup(old_name)) {
std::vector<std::string> links;
Group group = openGroup(old_name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.groupId, name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(groupId, name_read, H5L_SAME_LOC);
links.push_back(name_read);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.groupId, name_read, size);
}
renamed = links.size() > 0;
for (std::string curr_name: links) {
size_t pos = curr_name.find_last_of('/') + 1;
if (curr_name.substr(pos) == old_name) {
curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());
}
herr_t error = H5Lcreate_hard(group.groupId, ".", groupId, curr_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
renamed = renamed && (error >= 0);
}
}
return renamed;
}
// TODO implement some kind of roll-back in order to avoid half removed links.
bool Group::removeAllLinks(const std::string &name) {
bool removed = false;
if (hasGroup(name)) {
Group group = openGroup(name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.groupId, name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(groupId, name_read, H5L_SAME_LOC);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.groupId, name_read, size);
}
delete[] name_read;
removed = true;
}
return removed;
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, void *data) {
attr.read(mem_type, data);
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, std::string *data) {
StringWriter writer(size, data);
attr.read(mem_type, *writer);
writer.finish();
H5::DataSet::vlenReclaim(*writer, mem_type, attr.getSpace()); //recycle space?
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const void *data) {
attr.write(mem_type, data);
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const std::string *data) {
StringReader reader(size, data);
attr.write(mem_type, *reader);
}
H5::Attribute Group::openAttr(const std::string &name) const {
hid_t ha = H5Aopen(groupId, name.c_str(), H5P_DEFAULT);
return H5::Attribute(ha);
}
H5::Attribute Group::createAttr(const std::string &name, H5::DataType fileType, H5::DataSpace fileSpace) const {
hid_t ha = H5Acreate(groupId, name.c_str(), fileType.getId(), fileSpace.getId(), H5P_DEFAULT, H5P_DEFAULT);
return H5::Attribute(ha);
}
Group::~Group() {
close();
}
void Group::close() {
//NB: the group might have been closed outside this object
// like e.g. FileHDF5::close currently does so
if (H5Iis_valid(groupId)) {
H5Idec_ref(groupId);
groupId = H5I_INVALID_HID;
}
}
boost::optional<Group> Group::findGroupByNameOrAttribute(std::string const &attr, std::string const &value) const {
if (hasObject(value)) {
return boost::make_optional(openGroup(value, false));
} else if (util::looksLikeUUID(value)) {
return findGroupByAttribute(attr, value);
} else {
return boost::optional<Group>();
}
}
boost::optional<DataSet> Group::findDataByNameOrAttribute(std::string const &attr, std::string const &value) const {
if (hasObject(value)) {
return boost::make_optional(openData(value));
} else if (util::looksLikeUUID(value)) {
return findDataByAttribute(attr, value);
} else {
return boost::optional<DataSet>();
}
}
} // namespace hdf5
} // namespace nix
|
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/Group.hpp>
#include <nix/util/util.hpp>
#include <boost/multi_array.hpp>
#include <H5Gpublic.h>
namespace nix {
namespace hdf5 {
optGroup::optGroup(const Group &parent, const std::string &g_name)
: parent(parent), g_name(g_name)
{}
boost::optional<Group> optGroup::operator() (bool create) const {
if (parent.hasGroup(g_name)) {
g = boost::optional<Group>(parent.openGroup(g_name));
} else if (create) {
g = boost::optional<Group>(parent.openGroup(g_name, true));
}
return g;
}
Group::Group()
: groupId(H5I_INVALID_HID)
{}
Group::Group(const H5::Group &h5group)
: groupId(h5group.getLocId())
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(hid_t id)
: groupId(id)
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(const Group &other)
: groupId(other.groupId)
{
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
}
}
Group::Group(Group &&other) : groupId(other.groupId) {
other.groupId = H5I_INVALID_HID;
}
Group& Group::operator=(Group other)
{
using std::swap;
swap(this->groupId, other.groupId);
return *this;
}
bool Group::hasAttr(const std::string &name) const {
return H5Aexists(groupId, name.c_str());
}
void Group::removeAttr(const std::string &name) const {
H5Adelete(groupId, name.c_str());
}
bool Group::hasObject(const std::string &name) const {
// empty string should return false, not exception (which H5Lexists would)
if (name.empty()) {
return false;
}
htri_t res = H5Lexists(groupId, name.c_str(), H5P_DEFAULT);
return res;
}
size_t Group::objectCount() const {
hsize_t n_objs;
herr_t res = H5Gget_num_objs(groupId, &n_objs);
if(res < 0) {
throw std::runtime_error("Could not get object count"); //FIXME
}
return n_objs;
}
boost::optional<Group> Group::findGroupByAttribute(const std::string &attribute, const std::string &value) const {
boost::optional<Group> ret;
// look up first direct sub-group that has given attribute with given value
for (size_t index = 0; index < objectCount(); index++) {
std::string obj_name = objectName(index);
if(hasGroup(obj_name)) {
Group group = openGroup(obj_name, false);
if(group.hasAttr(attribute)) {
std::string attr_value;
group.getAttr(attribute, attr_value);
if (attr_value == value) {
ret = group;
break;
}
}
}
}
return ret;
}
boost::optional<DataSet> Group::findDataByAttribute(const std::string &attribute, const std::string &value) const {
std::vector<DataSet> dsets;
boost::optional<DataSet> ret;
// look up all direct sub-datasets that have the given attribute
for (size_t index = 0; index < objectCount(); index++) {
std::string obj_name = objectName(index);
if(hasData(obj_name)) {
DataSet dset(h5Group().openDataSet(obj_name));
if(dset.hasAttr(attribute)) dsets.push_back(dset);
}
}
// look for first dataset with given attribute set to given value
auto found = std::find_if(dsets.begin(), dsets.end(),
[value, attribute](DataSet &dset) {
std::string attr_value;
dset.getAttr(attribute, attr_value);
return attr_value == value; });
if(found != dsets.end()) ret = *found;
return ret;
}
std::string Group::objectName(size_t index) const {
// check if index valid
if(index > objectCount()) {
throw OutOfBounds("No object at given index", index);
}
std::string str_name;
// check whether name is found by index
ssize_t name_len = H5Lget_name_by_idx(groupId,
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
NULL,
0,
H5P_DEFAULT);
if (name_len > 0) {
char* name = new char[name_len+1];
name_len = H5Lget_name_by_idx(groupId,
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
name,
name_len+1,
H5P_DEFAULT);
str_name = name;
delete [] name;
} else {
throw std::runtime_error("objectName: No object found, H5Lget_name_by_idx returned no name");
}
return str_name;
}
bool Group::hasData(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5Group().getObjinfo(name, info);
if (info.type == H5G_DATASET) {
return true;
}
}
return false;
}
void Group::removeData(const std::string &name) {
if (hasData(name))
h5Group().unlink(name);
}
DataSet Group::openData(const std::string &name) const {
H5::DataSet ds5 = h5Group().openDataSet(name);
return DataSet(ds5);
}
bool Group::hasGroup(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5Group().getObjinfo(name, info);
if (info.type == H5G_GROUP) {
return true;
}
}
return false;
}
Group Group::openGroup(const std::string &name, bool create) const {
if(!util::nameCheck(name)) throw InvalidName("openGroup");
Group g;
if (hasGroup(name)) {
g = Group(h5Group().openGroup(name));
} else if (create) {
hid_t gcpl = H5Pcreate(H5P_GROUP_CREATE);
if (gcpl < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Pcreate)");
}
//we want hdf5 to keep track of the order in which links were created so that
//the order for indexed based accessors is stable cf. issue #387
herr_t res = H5Pset_link_creation_order(gcpl, H5P_CRT_ORDER_TRACKED|H5P_CRT_ORDER_INDEXED);
if (res < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Pset_link_cr...)");
}
hid_t h5_gid = H5Gcreate2(groupId, name.c_str(), H5P_DEFAULT, gcpl, H5P_DEFAULT);
H5Pclose(gcpl);
if (h5_gid < 0) {
throw std::runtime_error("Unable to create group with name '" + name + "'! (H5Gcreate2)");
}
g = Group(H5::Group(h5_gid));
} else {
throw std::runtime_error("Unable to open group with name '" + name + "'!");
}
return g;
}
optGroup Group::openOptGroup(const std::string &name) {
if(!util::nameCheck(name)) throw InvalidName("openOptGroup");
return optGroup(*this, name);
}
void Group::removeGroup(const std::string &name) {
if (hasGroup(name))
h5Group().unlink(name);
}
void Group::renameGroup(const std::string &old_name, const std::string &new_name) {
if(!util::nameCheck(new_name)) throw InvalidName("renameGroup");
if (hasGroup(old_name)) {
h5Group().move(old_name, new_name);
}
}
bool Group::operator==(const Group &group) const {
return groupId == group.groupId;
}
bool Group::operator!=(const Group &group) const {
return groupId != group.groupId;
}
H5::Group Group::h5Group() const {
if (H5Iis_valid(groupId)) {
H5Iinc_ref(groupId);
return H5::Group(groupId);
} else {
return H5::Group();
}
}
Group Group::createLink(const Group &target, const std::string &link_name) {
if(!util::nameCheck(link_name)) throw InvalidName("createLink");
herr_t error = H5Lcreate_hard(target.groupId, ".", groupId, link_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
if (error)
throw std::runtime_error("Unable to create link " + link_name);
return openGroup(link_name, false);
}
// TODO implement some kind of roll-back in order to avoid half renamed links.
bool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {
if(!util::nameCheck(new_name)) throw InvalidName("renameAllLinks");
bool renamed = false;
if (hasGroup(old_name)) {
std::vector<std::string> links;
Group group = openGroup(old_name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.groupId, name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(groupId, name_read, H5L_SAME_LOC);
links.push_back(name_read);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.groupId, name_read, size);
}
renamed = links.size() > 0;
for (std::string curr_name: links) {
size_t pos = curr_name.find_last_of('/') + 1;
if (curr_name.substr(pos) == old_name) {
curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());
}
herr_t error = H5Lcreate_hard(group.groupId, ".", groupId, curr_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
renamed = renamed && (error >= 0);
}
}
return renamed;
}
// TODO implement some kind of roll-back in order to avoid half removed links.
bool Group::removeAllLinks(const std::string &name) {
bool removed = false;
if (hasGroup(name)) {
Group group = openGroup(name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.groupId, name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(groupId, name_read, H5L_SAME_LOC);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.groupId, name_read, size);
}
delete[] name_read;
removed = true;
}
return removed;
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, void *data) {
attr.read(mem_type, data);
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, std::string *data) {
StringWriter writer(size, data);
attr.read(mem_type, *writer);
writer.finish();
H5::DataSet::vlenReclaim(*writer, mem_type, attr.getSpace()); //recycle space?
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const void *data) {
attr.write(mem_type, data);
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const std::string *data) {
StringReader reader(size, data);
attr.write(mem_type, *reader);
}
H5::Attribute Group::openAttr(const std::string &name) const {
hid_t ha = H5Aopen(groupId, name.c_str(), H5P_DEFAULT);
return H5::Attribute(ha);
}
H5::Attribute Group::createAttr(const std::string &name, H5::DataType fileType, H5::DataSpace fileSpace) const {
hid_t ha = H5Acreate(groupId, name.c_str(), fileType.getId(), fileSpace.getId(), H5P_DEFAULT, H5P_DEFAULT);
return H5::Attribute(ha);
}
Group::~Group() {
close();
}
void Group::close() {
//NB: the group might have been closed outside this object
// like e.g. FileHDF5::close currently does so
if (H5Iis_valid(groupId)) {
H5Idec_ref(groupId);
groupId = H5I_INVALID_HID;
}
}
boost::optional<Group> Group::findGroupByNameOrAttribute(std::string const &attr, std::string const &value) const {
if (hasObject(value)) {
return boost::make_optional(openGroup(value, false));
} else if (util::looksLikeUUID(value)) {
return findGroupByAttribute(attr, value);
} else {
return boost::optional<Group>();
}
}
boost::optional<DataSet> Group::findDataByNameOrAttribute(std::string const &attr, std::string const &value) const {
if (hasObject(value)) {
return boost::make_optional(openData(value));
} else if (util::looksLikeUUID(value)) {
return findDataByAttribute(attr, value);
} else {
return boost::optional<DataSet>();
}
}
} // namespace hdf5
} // namespace nix
|
use H5Gget_num_objs
|
Group::objectCount: use H5Gget_num_objs
|
C++
|
bsd-3-clause
|
stoewer/nix
|
70ba319c871b32e2f44059a2fec048d75194bba4
|
src/embedded.cc
|
src/embedded.cc
|
/**
* Copyright (c) Jason White
*
* MIT License
*
* Description:
* Path manipulation module.
*/
#include "embedded.h"
#include <string.h> // for strcmp
#include <stdlib.h> // for bsearch
#include <lua.hpp>
// Helper macro for adding new modules
#define SCRIPT(module, path, name) \
{(module), (path), scripts_ ## name ## _lua, sizeof(scripts_ ## name ## _lua)}
namespace {
struct Script
{
const char* name;
const char* path;
const void* data;
size_t length;
// Loads this Lua script
int load(lua_State* L) const;
};
/**
* Main scripts
*/
#include "embedded/init.c"
#include "embedded/shutdown.c"
/**
* Initialization/shutdown scripts.
*/
const Script script_init = SCRIPT("init", "init.lua", init);
const Script script_shutdown = SCRIPT("shutdown", "shutdown.lua", shutdown);
/**
* Modules to embed
*/
#include "embedded/rules.c"
#include "embedded/rules/cc.c"
#include "embedded/rules/cc/gcc.c"
#include "embedded/rules/d.c"
#include "embedded/rules/d/dmd.c"
/**
* List of embedded Lua scripts.
*
* NOTE: This must be in alphabetical order according to the Lua script path.
*/
const Script embedded[] = {
SCRIPT("rules", "{embedded}/rules.lua", rules),
SCRIPT("rules.cc", "{embedded}/rules/cc.lua", rules_cc),
SCRIPT("rules.cc.gcc", "{embedded}/rules/cc/gcc.lua", rules_cc_gcc),
SCRIPT("rules.d", "{embedded}/rules/d.lua", rules_d),
SCRIPT("rules.d.dmd", "{embedded}/rules/d/dmd.lua", rules_d_dmd),
};
const size_t embedded_len = sizeof(embedded)/sizeof(Script);
int compare_embedded(const void* key, const void* elem) {
return strcmp((const char*)key, ((const Script*)elem)->name);
}
// Note that this assumes the list of modules is sorted.
const Script* find_embedded(const char* name) {
return (const Script*)bsearch(name, embedded, embedded_len, sizeof(Script), compare_embedded);
}
int Script::load(lua_State* L) const {
return luaL_loadbuffer(L, (const char*)data, length, name);
}
} // namespace
int load_embedded(lua_State* L, const char* name)
{
const Script* m = find_embedded(name);
if (!m) {
lua_pushfstring(L, "embedded script '%s' not found", name);
return LUA_ERRFILE;
}
return m->load(L);
}
int embedded_searcher(lua_State* L) {
const char* name = luaL_checkstring(L, 1);
const Script* m = find_embedded(name);
if (!m) {
lua_pushfstring(L, "embedded script '%s' not found", name);
return 1;
}
// Return block function + file name to pass to it
if (m->load(L))
return 1;
lua_pushstring(L, m->path);
return 2;
}
int load_init(lua_State* L) {
return script_init.load(L);
}
int load_shutdown(lua_State* L) {
return script_shutdown.load(L);
}
|
/**
* Copyright (c) Jason White
*
* MIT License
*
* Description:
* Path manipulation module.
*/
#include "embedded.h"
#include <string.h> // for strcmp
#include <stdlib.h> // for bsearch
#include <lua.hpp>
// Helper macro for adding new modules
#define SCRIPT(module, path, name) \
{(module), (path), scripts_ ## name ## _lua, sizeof(scripts_ ## name ## _lua)}
namespace {
struct Script
{
const char* name;
const char* path;
const void* data;
size_t length;
// Loads this Lua script
int load(lua_State* L) const;
};
/**
* Main scripts
*/
#include "embedded/init.c"
#include "embedded/shutdown.c"
/**
* Initialization/shutdown scripts.
*/
const Script script_init = SCRIPT("init", "init.lua", init);
const Script script_shutdown = SCRIPT("shutdown", "shutdown.lua", shutdown);
/**
* Modules to embed
*/
#include "embedded/rules.c"
#include "embedded/rules/cc.c"
#include "embedded/rules/cc/gcc.c"
#include "embedded/rules/d.c"
#include "embedded/rules/d/dmd.c"
/**
* List of embedded Lua scripts.
*
* NOTE: This *must* be in sorted order according to the module name.
*/
const Script embedded[] = {
SCRIPT("rules", "{embedded}/rules.lua", rules),
SCRIPT("rules.cc", "{embedded}/rules/cc.lua", rules_cc),
SCRIPT("rules.cc.gcc", "{embedded}/rules/cc/gcc.lua", rules_cc_gcc),
SCRIPT("rules.d", "{embedded}/rules/d.lua", rules_d),
SCRIPT("rules.d.dmd", "{embedded}/rules/d/dmd.lua", rules_d_dmd),
};
const size_t embedded_len = sizeof(embedded)/sizeof(Script);
int compare_embedded(const void* key, const void* elem) {
return strcmp((const char*)key, ((const Script*)elem)->name);
}
// Note that this assumes the list of modules is sorted.
const Script* find_embedded(const char* name) {
return (const Script*)bsearch(name, embedded, embedded_len, sizeof(Script), compare_embedded);
}
int Script::load(lua_State* L) const {
return luaL_loadbuffer(L, (const char*)data, length, name);
}
} // namespace
int load_embedded(lua_State* L, const char* name)
{
const Script* m = find_embedded(name);
if (!m) {
lua_pushfstring(L, "embedded script '%s' not found", name);
return LUA_ERRFILE;
}
return m->load(L);
}
int embedded_searcher(lua_State* L) {
const char* name = luaL_checkstring(L, 1);
const Script* m = find_embedded(name);
if (!m) {
lua_pushfstring(L, "embedded script '%s' not found", name);
return 1;
}
// Return block function + file name to pass to it
if (m->load(L))
return 1;
lua_pushstring(L, m->path);
return 2;
}
int load_init(lua_State* L) {
return script_init.load(L);
}
int load_shutdown(lua_State* L) {
return script_shutdown.load(L);
}
|
Clean up formatting of embedded module list
|
Clean up formatting of embedded module list
|
C++
|
mit
|
jasonwhite/bblua,jasonwhite/bblua,jasonwhite/button-lua,jasonwhite/button-lua,jasonwhite/bblua,jasonwhite/button-lua
|
a349687d499a76496dc9433d5437398f774f0bd4
|
src/glu/sgi/libnurbs/internals/knotvector.cc
|
src/glu/sgi/libnurbs/internals/knotvector.cc
|
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
*/
/*
* knotvector.c++
*
*/
#include "glimports.h"
#include "mystdio.h"
#include "myassert.h"
#include "knotvector.h"
#include "defines.h"
#ifdef __WATCOMC__
#pragma warning 726 10
#endif
void Knotvector::init( long _knotcount, long _stride, long _order, INREAL *_knotlist )
{
knotcount = _knotcount;
stride = _stride;
order = _order;
knotlist = new Knot[_knotcount];
assert( knotlist != 0 );
for( int i = 0; i != _knotcount; i++ )
knotlist[i] = (Knot) _knotlist[i];
}
Knotvector::Knotvector( void )
{
knotlist = 0;
}
Knotvector::~Knotvector( void )
{
if( knotlist ) delete[] knotlist;
}
int Knotvector::validate( void )
{
/* kindex is used as an array index so subtract one first,
* this propagates throughout the code so study carefully */
long kindex = knotcount-1;
if( order < 1 || order > MAXORDER ) {
// spline order un-supported
return( 1 );
}
if( knotcount < (2 * order) ) {
// too few knots
return( 2 );
}
if( identical( knotlist[kindex-(order-1)], knotlist[order-1]) ) {
// valid knot range is empty
return( 3 );
}
for( long i = 0; i < kindex; i++)
if( knotlist[i] > knotlist[i+1] ) {
// decreasing knot sequence
return( 4 );
}
/* check for valid multiplicity */
/* kindex is currently the index of the last knot.
* In the next loop it is decremented to ignore the last knot
* and the loop stops when kindex is 2 so as to ignore the first
* knot as well. These knots are not used in computing
* knot multiplicities.
*/
long multi = 1;
for( ; kindex >= 1; kindex-- ) {
if( knotlist[kindex] - knotlist[kindex-1] < TOLERANCE ) {
multi++;
continue;
}
if ( multi > order ) {
// knot multiplicity greater than order of spline
return( 5 );
}
multi = 1;
}
if ( multi > order ) {
// knot multiplicity greater than order of spline
return( 5 );
}
return 0;
}
void Knotvector::show( const char *msg )
{
#ifndef NDEBUG
_glu_dprintf( "%s\n", msg );
_glu_dprintf( "order = %ld, count = %ld\n", order, knotcount );
for( int i=0; i<knotcount; i++ )
_glu_dprintf( "knot[%d] = %g\n", i, knotlist[i] );
#endif
}
|
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
*/
/*
* knotvector.c++
*
*/
#include "glimports.h"
#include "mystdio.h"
#include "myassert.h"
#include "knotvector.h"
#include "defines.h"
#ifdef __WATCOMC__
#pragma warning 726 10
#endif
void Knotvector::init( long _knotcount, long _stride, long _order, INREAL *_knotlist )
{
knotcount = _knotcount;
stride = _stride;
order = _order;
knotlist = new Knot[_knotcount];
assert( knotlist != 0 );
for( int i = 0; i != _knotcount; i++ )
knotlist[i] = (Knot) _knotlist[i];
}
Knotvector::Knotvector( void )
{
knotcount = 0;
stride = 0;
order = 0;
knotlist = 0;
}
Knotvector::~Knotvector( void )
{
if( knotlist ) delete[] knotlist;
}
int Knotvector::validate( void )
{
/* kindex is used as an array index so subtract one first,
* this propagates throughout the code so study carefully */
long kindex = knotcount-1;
if( order < 1 || order > MAXORDER ) {
// spline order un-supported
return( 1 );
}
if( knotcount < (2 * order) ) {
// too few knots
return( 2 );
}
if( identical( knotlist[kindex-(order-1)], knotlist[order-1]) ) {
// valid knot range is empty
return( 3 );
}
for( long i = 0; i < kindex; i++)
if( knotlist[i] > knotlist[i+1] ) {
// decreasing knot sequence
return( 4 );
}
/* check for valid multiplicity */
/* kindex is currently the index of the last knot.
* In the next loop it is decremented to ignore the last knot
* and the loop stops when kindex is 2 so as to ignore the first
* knot as well. These knots are not used in computing
* knot multiplicities.
*/
long multi = 1;
for( ; kindex >= 1; kindex-- ) {
if( knotlist[kindex] - knotlist[kindex-1] < TOLERANCE ) {
multi++;
continue;
}
if ( multi > order ) {
// knot multiplicity greater than order of spline
return( 5 );
}
multi = 1;
}
if ( multi > order ) {
// knot multiplicity greater than order of spline
return( 5 );
}
return 0;
}
void Knotvector::show( const char *msg )
{
#ifndef NDEBUG
_glu_dprintf( "%s\n", msg );
_glu_dprintf( "order = %ld, count = %ld\n", order, knotcount );
for( int i=0; i<knotcount; i++ )
_glu_dprintf( "knot[%d] = %g\n", i, knotlist[i] );
#endif
}
|
Initialize members of class Knotvector.
|
glu/sgi: Initialize members of class Knotvector.
|
C++
|
mit
|
metora/MesaGLSLCompiler,jbarczak/glsl-optimizer,adobe/glsl2agal,KTXSoftware/glsl2agal,tokyovigilante/glsl-optimizer,wolf96/glsl-optimizer,jbarczak/glsl-optimizer,wolf96/glsl-optimizer,zz85/glsl-optimizer,zeux/glsl-optimizer,zeux/glsl-optimizer,djreep81/glsl-optimizer,dellis1972/glsl-optimizer,benaadams/glsl-optimizer,mcanthony/glsl-optimizer,mcanthony/glsl-optimizer,adobe/glsl2agal,tokyovigilante/glsl-optimizer,mapbox/glsl-optimizer,mapbox/glsl-optimizer,zeux/glsl-optimizer,KTXSoftware/glsl2agal,benaadams/glsl-optimizer,zeux/glsl-optimizer,dellis1972/glsl-optimizer,bkaradzic/glsl-optimizer,tokyovigilante/glsl-optimizer,metora/MesaGLSLCompiler,djreep81/glsl-optimizer,wolf96/glsl-optimizer,bkaradzic/glsl-optimizer,wolf96/glsl-optimizer,KTXSoftware/glsl2agal,mapbox/glsl-optimizer,mcanthony/glsl-optimizer,jbarczak/glsl-optimizer,dellis1972/glsl-optimizer,KTXSoftware/glsl2agal,KTXSoftware/glsl2agal,djreep81/glsl-optimizer,zeux/glsl-optimizer,tokyovigilante/glsl-optimizer,benaadams/glsl-optimizer,benaadams/glsl-optimizer,jbarczak/glsl-optimizer,zz85/glsl-optimizer,mapbox/glsl-optimizer,jbarczak/glsl-optimizer,djreep81/glsl-optimizer,adobe/glsl2agal,bkaradzic/glsl-optimizer,zz85/glsl-optimizer,zz85/glsl-optimizer,mapbox/glsl-optimizer,djreep81/glsl-optimizer,wolf96/glsl-optimizer,zz85/glsl-optimizer,bkaradzic/glsl-optimizer,adobe/glsl2agal,benaadams/glsl-optimizer,adobe/glsl2agal,mcanthony/glsl-optimizer,bkaradzic/glsl-optimizer,benaadams/glsl-optimizer,tokyovigilante/glsl-optimizer,dellis1972/glsl-optimizer,dellis1972/glsl-optimizer,zz85/glsl-optimizer,metora/MesaGLSLCompiler,mcanthony/glsl-optimizer
|
33a2ac58a6ddd64ba02b4ffd0d00edd6e6e3becd
|
src/insert_mode.cc
|
src/insert_mode.cc
|
/* 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 <ncurses.h>
#include "concat_c.hh"
#include "configuration.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "insert_mode.hh"
#include "key_aliases.hh"
#include "show_message.hh"
#include "vick-move/src/move.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<insert_c>(track, contents.y,
contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const int y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y) {}
virtual bool is_overriding() { return true; }
virtual void undo(contents& contents) {
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents) {
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const {
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref) {
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y,
move_t x)
: o(o)
, n(n)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<replace_c>(contents.cont[contents.y]
.substr(contents.x,
n.size()),
n, contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref) {
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
} else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<append_c>(track, contents.y,
contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref) {
if (contents.cont[contents.y].empty())
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
// cancel out ++ from beginning
if (contents.x != 0)
contents.x--;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
|
/* 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 <ncurses.h>
#include "concat_c.hh"
#include "configuration.hh"
#include "contents.hh"
#include "file_contents.hh"
#include "insert_mode.hh"
#include "key_aliases.hh"
#include "show_message.hh"
#include "vick-move/src/move.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<insert_c>(track, contents.y,
contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const int y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y) {}
virtual bool is_overriding() override {
return true;
}
virtual void undo(contents& contents) override {
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents) override {
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref) {
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (contents.refresh) {
print_contents(contents);
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y,
move_t x)
: o(o)
, n(n)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<replace_c>(contents.cont[contents.y]
.substr(contents.x,
n.size()),
n, contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref) {
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
} else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x) {}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override {
contents.cont[y] = contents.cont[y].substr(0, x) + track +
contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override {
return std::make_shared<append_c>(track, contents.y,
contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref) {
if (contents.cont[contents.y].empty())
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed)
changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
} else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
// cancel out ++ from beginning
if (contents.x != 0)
contents.x--;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
|
Add `override` keyword to help compilation errors
|
Add `override` keyword to help compilation errors
|
C++
|
mpl-2.0
|
czipperz/vick-insert-mode
|
88b41063cdbdd254477b2cb749735378c3a20dd6
|
src/lib/mongoBackend/MongoCommonRegister.cpp
|
src/lib/mongoBackend/MongoCommonRegister.cpp
|
/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermín Galán
*/
#include <stdint.h>
#include <utility>
#include <map>
#include <string>
#include <vector>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/string.h"
#include "common/globals.h"
#include "common/statistics.h"
#include "common/sem.h"
#include "common/RenderFormat.h"
#include "common/defaultValues.h"
#include "alarmMgr/alarmMgr.h"
#include "mongoBackend/MongoGlobal.h"
#include "mongoBackend/TriggeredSubscription.h"
#include "mongoBackend/connectionOperations.h"
#include "mongoBackend/mongoConnectionPool.h"
#include "mongoBackend/safeMongo.h"
#include "mongoBackend/dbConstants.h"
#include "mongoBackend/MongoCommonRegister.h"
/* ****************************************************************************
*
* USING
*/
using mongo::BSONArrayBuilder;
using mongo::BSONObjBuilder;
using mongo::BSONObj;
using mongo::BSONElement;
using mongo::DBClientBase;
using mongo::DBClientCursor;
using mongo::OID;
/* ****************************************************************************
*
* processRegisterContext -
*
* This function has a slightly different behaviour depending on whether the id
* parameter is null (new registration case) or not null (update case), in
* particular:
*
* - In the new registration case, the _id is generated and insert() is used to
* put the document in the DB.
* - In the update case, the _id is set according to the argument 'id' and update() is
* used to put the document in the DB.
*/
HttpStatusCode processRegisterContext
(
RegisterContextRequest* requestP,
RegisterContextResponse* responseP,
OID* id,
const std::string& tenant,
const std::string& servicePath,
const std::string& format,
const std::string& fiwareCorrelator
)
{
std::string err;
/* If expiration is not present, then use a default one */
if (requestP->duration.isEmpty())
{
requestP->duration.set(DEFAULT_DURATION);
}
/* Calculate expiration (using the current time and the duration field in the request) */
long long expiration = getCurrentTime() + requestP->duration.parse();
LM_T(LmtMongo, ("Registration expiration: %lu", expiration));
/* Create the mongoDB registration document */
BSONObjBuilder reg;
OID oid;
if (id == NULL)
{
oid.init();
}
else
{
oid = *id;
}
reg.append("_id", oid);
reg.append(REG_EXPIRATION, expiration);
// FIXME P4: See issue #3078
reg.append(REG_SERVICE_PATH, servicePath.empty() ? SERVICE_PATH_ROOT : servicePath);
reg.append(REG_FORMAT, format);
//
// We accumulate the subscriptions in a map. The key of the map is the string representing subscription id
// 'triggerEntitiesV' is used to define which entities to include in notifications
//
BSONArrayBuilder contextRegistration;
for (unsigned int ix = 0; ix < requestP->contextRegistrationVector.size(); ++ix)
{
ContextRegistration* cr = requestP->contextRegistrationVector[ix];
BSONArrayBuilder entities;
for (unsigned int jx = 0; jx < cr->entityIdVector.size(); ++jx)
{
EntityId* en = cr->entityIdVector[jx];
if (en->type.empty())
{
entities.append(BSON(REG_ENTITY_ID << en->id));
LM_T(LmtMongo, ("Entity registration: {id: %s}", en->id.c_str()));
}
else
{
entities.append(BSON(REG_ENTITY_ID << en->id << REG_ENTITY_TYPE << en->type));
LM_T(LmtMongo, ("Entity registration: {id: %s, type: %s}", en->id.c_str(), en->type.c_str()));
}
}
BSONArrayBuilder attrs;
for (unsigned int jx = 0; jx < cr->contextRegistrationAttributeVector.size(); ++jx)
{
ContextRegistrationAttribute* cra = cr->contextRegistrationAttributeVector[jx];
attrs.append(BSON(REG_ATTRS_NAME << cra->name << REG_ATTRS_TYPE << cra->type));
LM_T(LmtMongo, ("Attribute registration: {name: %s, type: %s}",
cra->name.c_str(),
cra->type.c_str()));
}
contextRegistration.append(
BSON(
REG_ENTITIES << entities.arr() <<
REG_ATTRS << attrs.arr() <<
REG_PROVIDING_APPLICATION << requestP->contextRegistrationVector[ix]->providingApplication.get()));
LM_T(LmtMongo, ("providingApplication registration: %s",
requestP->contextRegistrationVector[ix]->providingApplication.c_str()));
}
reg.append(REG_CONTEXT_REGISTRATION, contextRegistration.arr());
/* Note that we are using upsert = "true". This means that if the document doesn't previously
* exist in the collection, it is created. Thus, this way both uses of registerContext are OK
* (either new registration or updating an existing one)
*/
if (!collectionUpdate(getRegistrationsCollectionName(tenant), BSON("_id" << oid), reg.obj(), true, &err))
{
responseP->errorCode.fill(SccReceiverInternalError, err);
return SccOk;
}
// Fill the response element
responseP->duration = requestP->duration;
responseP->registrationId.set(oid.toString());
responseP->errorCode.fill(SccOk);
return SccOk;
}
|
/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermín Galán
*/
#include <stdint.h>
#include <utility>
#include <map>
#include <string>
#include <vector>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/string.h"
#include "common/globals.h"
#include "common/statistics.h"
#include "common/sem.h"
#include "common/RenderFormat.h"
#include "common/defaultValues.h"
#include "alarmMgr/alarmMgr.h"
#include "mongoBackend/MongoGlobal.h"
#include "mongoBackend/TriggeredSubscription.h"
#include "mongoBackend/connectionOperations.h"
#include "mongoBackend/mongoConnectionPool.h"
#include "mongoBackend/safeMongo.h"
#include "mongoBackend/dbConstants.h"
#include "mongoBackend/MongoCommonRegister.h"
/* ****************************************************************************
*
* USING
*/
using mongo::BSONArrayBuilder;
using mongo::BSONObjBuilder;
using mongo::BSONObj;
using mongo::BSONElement;
using mongo::DBClientBase;
using mongo::DBClientCursor;
using mongo::OID;
/* ****************************************************************************
*
* processRegisterContext -
*
* This function has a slightly different behaviour depending on whether the id
* parameter is null (new registration case) or not null (update case), in
* particular:
*
* - In the new registration case, the _id is generated and insert() is used to
* put the document in the DB.
* - In the update case, the _id is set according to the argument 'id' and update() is
* used to put the document in the DB.
*/
HttpStatusCode processRegisterContext
(
RegisterContextRequest* requestP,
RegisterContextResponse* responseP,
OID* id,
const std::string& tenant,
const std::string& servicePath,
const std::string& format,
const std::string& fiwareCorrelator
)
{
std::string err;
/* If expiration is not present, then use a default one */
if (requestP->duration.isEmpty())
{
requestP->duration.set(DEFAULT_DURATION);
}
/* Calculate expiration (using the current time and the duration field in the request) */
long long expiration = getCurrentTime() + requestP->duration.parse();
LM_T(LmtMongo, ("Registration expiration: %lu", expiration));
/* Create the mongoDB registration document */
BSONObjBuilder reg;
OID oid;
if (id == NULL)
{
oid.init();
}
else
{
oid = *id;
}
reg.append("_id", oid);
reg.append(REG_EXPIRATION, expiration);
// FIXME P4: See issue #3078
reg.append(REG_SERVICE_PATH, servicePath.empty() ? SERVICE_PATH_ROOT : servicePath);
reg.append(REG_FORMAT, format);
BSONArrayBuilder contextRegistration;
for (unsigned int ix = 0; ix < requestP->contextRegistrationVector.size(); ++ix)
{
ContextRegistration* cr = requestP->contextRegistrationVector[ix];
BSONArrayBuilder entities;
for (unsigned int jx = 0; jx < cr->entityIdVector.size(); ++jx)
{
EntityId* en = cr->entityIdVector[jx];
if (en->type.empty())
{
entities.append(BSON(REG_ENTITY_ID << en->id));
LM_T(LmtMongo, ("Entity registration: {id: %s}", en->id.c_str()));
}
else
{
entities.append(BSON(REG_ENTITY_ID << en->id << REG_ENTITY_TYPE << en->type));
LM_T(LmtMongo, ("Entity registration: {id: %s, type: %s}", en->id.c_str(), en->type.c_str()));
}
}
BSONArrayBuilder attrs;
for (unsigned int jx = 0; jx < cr->contextRegistrationAttributeVector.size(); ++jx)
{
ContextRegistrationAttribute* cra = cr->contextRegistrationAttributeVector[jx];
attrs.append(BSON(REG_ATTRS_NAME << cra->name << REG_ATTRS_TYPE << cra->type));
LM_T(LmtMongo, ("Attribute registration: {name: %s, type: %s}",
cra->name.c_str(),
cra->type.c_str()));
}
contextRegistration.append(
BSON(
REG_ENTITIES << entities.arr() <<
REG_ATTRS << attrs.arr() <<
REG_PROVIDING_APPLICATION << requestP->contextRegistrationVector[ix]->providingApplication.get()));
LM_T(LmtMongo, ("providingApplication registration: %s",
requestP->contextRegistrationVector[ix]->providingApplication.c_str()));
}
reg.append(REG_CONTEXT_REGISTRATION, contextRegistration.arr());
/* Note that we are using upsert = "true". This means that if the document doesn't previously
* exist in the collection, it is created. Thus, this way both uses of registerContext are OK
* (either new registration or updating an existing one)
*/
if (!collectionUpdate(getRegistrationsCollectionName(tenant), BSON("_id" << oid), reg.obj(), true, &err))
{
responseP->errorCode.fill(SccReceiverInternalError, err);
return SccOk;
}
// Fill the response element
responseP->duration = requestP->duration;
responseP->registrationId.set(oid.toString());
responseP->errorCode.fill(SccOk);
return SccOk;
}
|
REMOVE obsolete comment
|
REMOVE obsolete comment
|
C++
|
agpl-3.0
|
telefonicaid/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion,telefonicaid/fiware-orion
|
ff94d3d7d94f1d7703ed3f916936f8e1a0d95bdf
|
creator/plugins/docks/propertiesdock/propertywidgetitems/qsizefpropertywidgetitem.cpp
|
creator/plugins/docks/propertiesdock/propertywidgetitems/qsizefpropertywidgetitem.cpp
|
/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "qsizefpropertywidgetitem.h"
#include <QtGui/QDoubleSpinBox>
#include <QtGui/QHBoxLayout>
REGISTER_PROPERTYWIDGETITEM(GluonCreator,QSizeFPropertyWidgetItem)
using namespace GluonCreator;
class QSizeFPropertyWidgetItem::QSizeFPropertyWidgetItemPrivate
{
public:
QSizeFPropertyWidgetItemPrivate() {};
QDoubleSpinBox *height;
QDoubleSpinBox *width;
QSizeF value;
};
QSizeFPropertyWidgetItem::QSizeFPropertyWidgetItem(QWidget* parent, Qt::WindowFlags f)
: PropertyWidgetItem(parent, f)
{
d = new QSizeFPropertyWidgetItemPrivate;
QWidget *widget = new QWidget(this);
QHBoxLayout *layout = new QHBoxLayout();
layout->setSpacing(0);
widget->setLayout(layout);
d->height = new QDoubleSpinBox(this);
d->height->setPrefix(tr("Height: "));
layout->addWidget(d->height);
connect(d->height, SIGNAL(valueChanged(double)), SLOT(heightValueChanged(double)));
d->width = new QDoubleSpinBox(this);
d->width->setPrefix(tr("Width: "));
layout->addWidget(d->width);
connect(d->width, SIGNAL(valueChanged(double)), SLOT(widthValueChanged(double)));
setEditWidget(widget);
}
QSizeFPropertyWidgetItem::~QSizeFPropertyWidgetItem()
{
delete d;
}
QList< QString >
QSizeFPropertyWidgetItem::supportedDataTypes() const
{
QList<QString> supportedTypes;
supportedTypes.append("QSizeF");
return supportedTypes;
}
PropertyWidgetItem*
QSizeFPropertyWidgetItem::instantiate()
{
return new QSizeFPropertyWidgetItem();
}
void
QSizeFPropertyWidgetItem::setEditValue(const QVariant& value)
{
d->value = value.toSizeF();
d->height->setValue(d->value.height());
d->width->setValue(d->value.width());
}
void
QSizeFPropertyWidgetItem::heightValueChanged(double value)
{
d->value = QSizeF(value, d->value.width());
PropertyWidgetItem::valueChanged(QVariant(d->value));
}
void
QSizeFPropertyWidgetItem::widthValueChanged(double value)
{
d->value = QSizeF(d->value.height(), value);
PropertyWidgetItem::valueChanged(QVariant(d->value));
}
#include "qsizefpropertywidgetitem.moc"
|
/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "qsizefpropertywidgetitem.h"
#include <QtGui/QDoubleSpinBox>
#include <QtGui/QHBoxLayout>
#include <cfloat>
REGISTER_PROPERTYWIDGETITEM(GluonCreator,QSizeFPropertyWidgetItem)
using namespace GluonCreator;
class QSizeFPropertyWidgetItem::QSizeFPropertyWidgetItemPrivate
{
public:
QSizeFPropertyWidgetItemPrivate() {};
QDoubleSpinBox *height;
QDoubleSpinBox *width;
QSizeF value;
};
QSizeFPropertyWidgetItem::QSizeFPropertyWidgetItem(QWidget* parent, Qt::WindowFlags f)
: PropertyWidgetItem(parent, f)
{
d = new QSizeFPropertyWidgetItemPrivate;
QWidget *widget = new QWidget(this);
QHBoxLayout *layout = new QHBoxLayout();
layout->setSpacing(0);
widget->setLayout(layout);
d->height = new QDoubleSpinBox(this);
d->height->setPrefix(tr("Height: "));
d->height->setRange(-FLT_MAX, FLT_MAX);
layout->addWidget(d->height);
connect(d->height, SIGNAL(valueChanged(double)), SLOT(heightValueChanged(double)));
d->width = new QDoubleSpinBox(this);
d->width->setPrefix(tr("Width: "));
d->width->setRange(-FLT_MAX, FLT_MAX);
layout->addWidget(d->width);
connect(d->width, SIGNAL(valueChanged(double)), SLOT(widthValueChanged(double)));
setEditWidget(widget);
}
QSizeFPropertyWidgetItem::~QSizeFPropertyWidgetItem()
{
delete d;
}
QList< QString >
QSizeFPropertyWidgetItem::supportedDataTypes() const
{
QList<QString> supportedTypes;
supportedTypes.append("QSizeF");
return supportedTypes;
}
PropertyWidgetItem*
QSizeFPropertyWidgetItem::instantiate()
{
return new QSizeFPropertyWidgetItem();
}
void
QSizeFPropertyWidgetItem::setEditValue(const QVariant& value)
{
d->value = value.toSizeF();
d->height->setValue(d->value.height());
d->width->setValue(d->value.width());
}
void
QSizeFPropertyWidgetItem::heightValueChanged(double value)
{
d->value.setHeight(value);
PropertyWidgetItem::valueChanged(QVariant(d->value));
}
void
QSizeFPropertyWidgetItem::widthValueChanged(double value)
{
d->value.setWidth(value);
PropertyWidgetItem::valueChanged(QVariant(d->value));
}
#include "qsizefpropertywidgetitem.moc"
|
Fix the QSizeF PWI
|
Fix the QSizeF PWI
|
C++
|
lgpl-2.1
|
KDE/gluon,cgaebel/gluon,cgaebel/gluon,pranavrc/example-gluon,pranavrc/example-gluon,KDE/gluon,KDE/gluon,pranavrc/example-gluon,cgaebel/gluon,cgaebel/gluon,KDE/gluon,pranavrc/example-gluon
|
54b068c0329112fadb0b63ceacb2d1be9a2330bd
|
core/smartview/RuleCondition.cpp
|
core/smartview/RuleCondition.cpp
|
#include <core/stdafx.h>
#include <core/smartview/RuleCondition.h>
#include <core/smartview/RestrictionStruct.h>
#include <core/interpret/guid.h>
namespace smartview
{
PropertyName::PropertyName(const std::shared_ptr<binaryParser>& parser)
{
Kind = blockT<BYTE>::parse(parser);
Guid = blockT<GUID>::parse(parser);
if (*Kind == MNID_ID)
{
LID = blockT<DWORD>::parse(parser);
}
else if (*Kind == MNID_STRING)
{
NameSize = blockT<BYTE>::parse(parser);
Name = blockStringW::parse(parser, *NameSize / sizeof(WCHAR));
}
}
void RuleCondition::Init(bool bExtended) noexcept { m_bExtended = bExtended; }
void RuleCondition::parse()
{
m_NamedPropertyInformation.NoOfNamedProps = blockT<WORD>::parse(m_Parser);
if (*m_NamedPropertyInformation.NoOfNamedProps && *m_NamedPropertyInformation.NoOfNamedProps < _MaxEntriesLarge)
{
m_NamedPropertyInformation.PropId.reserve(*m_NamedPropertyInformation.NoOfNamedProps);
for (auto i = 0; i < *m_NamedPropertyInformation.NoOfNamedProps; i++)
{
m_NamedPropertyInformation.PropId.push_back(blockT<WORD>::parse(m_Parser));
}
m_NamedPropertyInformation.NamedPropertiesSize = blockT<DWORD>::parse(m_Parser);
m_NamedPropertyInformation.PropertyName.reserve(*m_NamedPropertyInformation.NoOfNamedProps);
for (auto i = 0; i < *m_NamedPropertyInformation.NoOfNamedProps; i++)
{
m_NamedPropertyInformation.PropertyName.emplace_back(std::make_shared<PropertyName>(m_Parser));
}
}
m_lpRes = std::make_shared<RestrictionStruct>(true, m_bExtended);
m_lpRes->smartViewParser::parse(m_Parser, false);
}
void RuleCondition::parseBlocks()
{
setRoot(m_bExtended ? L"Extended Rule Condition\r\n" : L"Rule Condition\r\n");
addChild(
m_NamedPropertyInformation.NoOfNamedProps,
L"Number of named props = 0x%1!04X!\r\n",
m_NamedPropertyInformation.NoOfNamedProps->getData());
if (!m_NamedPropertyInformation.PropId.empty())
{
terminateBlock();
addChild(
m_NamedPropertyInformation.NamedPropertiesSize,
L"Named prop size = 0x%1!08X!",
m_NamedPropertyInformation.NamedPropertiesSize->getData());
for (size_t i = 0; i < m_NamedPropertyInformation.PropId.size(); i++)
{
terminateBlock();
addHeader(L"Named Prop 0x%1!04X!\r\n", i);
addChild(
m_NamedPropertyInformation.PropId[i],
L"\tPropID = 0x%1!04X!\r\n",
m_NamedPropertyInformation.PropId[i]->getData());
addChild(
m_NamedPropertyInformation.PropertyName[i]->Kind,
L"\tKind = 0x%1!02X!\r\n",
m_NamedPropertyInformation.PropertyName[i]->Kind->getData());
addChild(
m_NamedPropertyInformation.PropertyName[i]->Guid,
L"\tGuid = %1!ws!\r\n",
guid::GUIDToString(*m_NamedPropertyInformation.PropertyName[i]->Guid).c_str());
if (m_NamedPropertyInformation.PropertyName[i]->Kind == MNID_ID)
{
addChild(
m_NamedPropertyInformation.PropertyName[i]->LID,
L"\tLID = 0x%1!08X!",
m_NamedPropertyInformation.PropertyName[i]->LID->getData());
}
else if (*m_NamedPropertyInformation.PropertyName[i]->Kind == MNID_STRING)
{
addChild(
m_NamedPropertyInformation.PropertyName[i]->NameSize,
L"\tNameSize = 0x%1!02X!\r\n",
m_NamedPropertyInformation.PropertyName[i]->NameSize->getData());
addHeader(L"\tName = ");
addChild(
m_NamedPropertyInformation.PropertyName[i]->Name,
m_NamedPropertyInformation.PropertyName[i]->Name->c_str());
}
}
}
if (m_lpRes && m_lpRes->hasData())
{
addChild(m_lpRes->getBlock());
}
}
} // namespace smartview
|
#include <core/stdafx.h>
#include <core/smartview/RuleCondition.h>
#include <core/smartview/RestrictionStruct.h>
#include <core/interpret/guid.h>
namespace smartview
{
PropertyName::PropertyName(const std::shared_ptr<binaryParser>& parser)
{
Kind = blockT<BYTE>::parse(parser);
Guid = blockT<GUID>::parse(parser);
if (*Kind == MNID_ID)
{
LID = blockT<DWORD>::parse(parser);
}
else if (*Kind == MNID_STRING)
{
NameSize = blockT<BYTE>::parse(parser);
Name = blockStringW::parse(parser, *NameSize / sizeof(WCHAR));
}
}
void RuleCondition::Init(bool bExtended) noexcept { m_bExtended = bExtended; }
void RuleCondition::parse()
{
m_NamedPropertyInformation.NoOfNamedProps = blockT<WORD>::parse(m_Parser);
if (*m_NamedPropertyInformation.NoOfNamedProps && *m_NamedPropertyInformation.NoOfNamedProps < _MaxEntriesLarge)
{
m_NamedPropertyInformation.PropId.reserve(*m_NamedPropertyInformation.NoOfNamedProps);
for (auto i = 0; i < *m_NamedPropertyInformation.NoOfNamedProps; i++)
{
m_NamedPropertyInformation.PropId.push_back(blockT<WORD>::parse(m_Parser));
}
m_NamedPropertyInformation.NamedPropertiesSize = blockT<DWORD>::parse(m_Parser);
m_NamedPropertyInformation.PropertyName.reserve(*m_NamedPropertyInformation.NoOfNamedProps);
for (auto i = 0; i < *m_NamedPropertyInformation.NoOfNamedProps; i++)
{
m_NamedPropertyInformation.PropertyName.emplace_back(std::make_shared<PropertyName>(m_Parser));
}
}
m_lpRes = std::make_shared<RestrictionStruct>(true, m_bExtended);
m_lpRes->smartViewParser::parse(m_Parser, false);
}
void RuleCondition::parseBlocks()
{
setRoot(m_bExtended ? L"Extended Rule Condition\r\n" : L"Rule Condition\r\n");
addChild(
m_NamedPropertyInformation.NoOfNamedProps,
L"Number of named props = 0x%1!04X!\r\n",
m_NamedPropertyInformation.NoOfNamedProps->getData());
if (!m_NamedPropertyInformation.PropId.empty())
{
terminateBlock();
addChild(
m_NamedPropertyInformation.NamedPropertiesSize,
L"Named prop size = 0x%1!08X!",
m_NamedPropertyInformation.NamedPropertiesSize->getData());
for (size_t i = 0; i < m_NamedPropertyInformation.PropId.size(); i++)
{
auto namedProp = std::make_shared<block>();
addChild(namedProp);
namedProp->setText(L"Named Prop 0x%1!04X!\r\n", i);
namedProp->addChild(
m_NamedPropertyInformation.PropId[i],
L"\tPropID = 0x%1!04X!\r\n",
m_NamedPropertyInformation.PropId[i]->getData());
namedProp->addChild(
m_NamedPropertyInformation.PropertyName[i]->Kind,
L"\tKind = 0x%1!02X!\r\n",
m_NamedPropertyInformation.PropertyName[i]->Kind->getData());
namedProp->addChild(
m_NamedPropertyInformation.PropertyName[i]->Guid,
L"\tGuid = %1!ws!\r\n",
guid::GUIDToString(*m_NamedPropertyInformation.PropertyName[i]->Guid).c_str());
if (m_NamedPropertyInformation.PropertyName[i]->Kind == MNID_ID)
{
namedProp->addChild(
m_NamedPropertyInformation.PropertyName[i]->LID,
L"\tLID = 0x%1!08X!",
m_NamedPropertyInformation.PropertyName[i]->LID->getData());
}
else if (*m_NamedPropertyInformation.PropertyName[i]->Kind == MNID_STRING)
{
namedProp->addChild(
m_NamedPropertyInformation.PropertyName[i]->NameSize,
L"\tNameSize = 0x%1!02X!\r\n",
m_NamedPropertyInformation.PropertyName[i]->NameSize->getData());
namedProp->addChild(
m_NamedPropertyInformation.PropertyName[i]->Name,
L"\tName = %1!ws!",
m_NamedPropertyInformation.PropertyName[i]->Name->c_str());
}
}
}
if (m_lpRes && m_lpRes->hasData())
{
addChild(m_lpRes->getBlock());
}
}
} // namespace smartview
|
Fix block tree for rule condition
|
Fix block tree for rule condition
|
C++
|
mit
|
stephenegriffin/mfcmapi,stephenegriffin/mfcmapi,stephenegriffin/mfcmapi
|
8b23a3f6014dce0ae22227674821452ce399fcc9
|
src/geom/edge.C
|
src/geom/edge.C
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/edge.h"
#include "libmesh/node_elem.h"
namespace libMesh
{
unsigned int Edge::local_side_node(unsigned int side,
unsigned int /*side_node*/) const
{
libmesh_assert_less (side, this->n_sides());
return side;
}
unsigned int Edge::local_edge_node(unsigned int /*edge*/,
unsigned int /*edge_node*/) const
{
libmesh_error_msg("Calling Edge::local_edge_node() does not make sense.");
return 0;
}
std::unique_ptr<Elem> Edge::side_ptr (const unsigned int i)
{
libmesh_assert_less (i, 2);
std::unique_ptr<Elem> nodeelem = libmesh_make_unique<NodeElem>(this);
nodeelem->set_node(0) = this->node_ptr(i);
return nodeelem;
}
void Edge::side_ptr (std::unique_ptr<Elem> & side,
const unsigned int i)
{
libmesh_assert_less (i, this->n_sides());
if (!side.get() || side->type() != NODEELEM)
side = this->build_side_ptr(i, false);
else
{
side->subdomain_id() = this->subdomain_id();
#ifdef LIBMESH_ENABLE_AMR
side->set_p_level(this->p_level());
#endif
side->set_node(0) = this->node_ptr(i);
}
}
std::unique_ptr<Elem> Edge::build_side_ptr (const unsigned int i, bool)
{
libmesh_assert_less (i, 2);
std::unique_ptr<Elem> nodeelem = libmesh_make_unique<NodeElem>(this);
nodeelem->set_node(0) = this->node_ptr(i);
#ifndef LIBMESH_ENABLE_DEPRECATED
nodeelem->set_parent(nullptr);
#endif
nodeelem->set_interior_parent(this);
return nodeelem;
}
void Edge::build_side_ptr (std::unique_ptr<Elem> & side,
const unsigned int i)
{
this->side_ptr(side, i);
}
bool Edge::is_child_on_side(const unsigned int c,
const unsigned int s) const
{
libmesh_assert_less (c, this->n_children());
libmesh_assert_less (s, this->n_sides());
return (c == s);
}
unsigned int Edge::opposite_side(const unsigned int side_in) const
{
libmesh_assert_less (side_in, 2);
return 1 - side_in;
}
unsigned int Edge::opposite_node(const unsigned int node_in,
const unsigned int libmesh_dbg_var(side_in)) const
{
libmesh_assert_less (node_in, 2);
libmesh_assert_less (side_in, this->n_sides());
libmesh_assert(this->is_node_on_side(node_in, side_in));
return 1 - node_in;
}
std::vector<unsigned>
Edge::nodes_on_side(const unsigned int s) const
{
libmesh_assert_less(s, 2);
return {s};
}
std::vector<unsigned>
Edge::nodes_on_edge(const unsigned int e) const
{
return nodes_on_side(e);
}
} // namespace libMesh
|
// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/edge.h"
#include "libmesh/node_elem.h"
namespace libMesh
{
unsigned int Edge::local_side_node(unsigned int side,
unsigned int /*side_node*/) const
{
libmesh_assert_less (side, this->n_sides());
return side;
}
unsigned int Edge::local_edge_node(unsigned int /*edge*/,
unsigned int /*edge_node*/) const
{
libmesh_error_msg("Calling Edge::local_edge_node() does not make sense.");
return 0;
}
std::unique_ptr<Elem> Edge::side_ptr (const unsigned int i)
{
libmesh_assert_less (i, 2);
std::unique_ptr<Elem> nodeelem = libmesh_make_unique<NodeElem>(this);
nodeelem->set_node(0) = this->node_ptr(i);
return nodeelem;
}
void Edge::side_ptr (std::unique_ptr<Elem> & side,
const unsigned int i)
{
libmesh_assert_less (i, this->n_sides());
if (!side.get() || side->type() != NODEELEM)
side = this->build_side_ptr(i, false);
else
{
side->subdomain_id() = this->subdomain_id();
side->set_node(0) = this->node_ptr(i);
}
}
std::unique_ptr<Elem> Edge::build_side_ptr (const unsigned int i, bool)
{
libmesh_assert_less (i, 2);
std::unique_ptr<Elem> nodeelem = libmesh_make_unique<NodeElem>(this);
nodeelem->set_node(0) = this->node_ptr(i);
#ifndef LIBMESH_ENABLE_DEPRECATED
nodeelem->set_parent(nullptr);
#endif
nodeelem->set_interior_parent(this);
return nodeelem;
}
void Edge::build_side_ptr (std::unique_ptr<Elem> & side,
const unsigned int i)
{
this->side_ptr(side, i);
}
bool Edge::is_child_on_side(const unsigned int c,
const unsigned int s) const
{
libmesh_assert_less (c, this->n_children());
libmesh_assert_less (s, this->n_sides());
return (c == s);
}
unsigned int Edge::opposite_side(const unsigned int side_in) const
{
libmesh_assert_less (side_in, 2);
return 1 - side_in;
}
unsigned int Edge::opposite_node(const unsigned int node_in,
const unsigned int libmesh_dbg_var(side_in)) const
{
libmesh_assert_less (node_in, 2);
libmesh_assert_less (side_in, this->n_sides());
libmesh_assert(this->is_node_on_side(node_in, side_in));
return 1 - node_in;
}
std::vector<unsigned>
Edge::nodes_on_side(const unsigned int s) const
{
libmesh_assert_less(s, 2);
return {s};
}
std::vector<unsigned>
Edge::nodes_on_edge(const unsigned int e) const
{
return nodes_on_side(e);
}
} // namespace libMesh
|
remove inadvertant set_p_level() call
|
Edge::side_ptr(): remove inadvertant set_p_level() call
This change was made by accident in f1782255be while I was trying to
update the various Elem::build_side_ptr() routines in #2592, so this
simply reverts that change.
There appears to be larger issues with the consistency of the
Elem::side_ptr() method and setting of the side's p_level, but this
change can at least be reverted before those are addressed.
|
C++
|
lgpl-2.1
|
libMesh/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,libMesh/libmesh,dschwen/libmesh,jwpeterson/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,jwpeterson/libmesh,libMesh/libmesh,dschwen/libmesh,libMesh/libmesh,dschwen/libmesh,roystgnr/libmesh,jwpeterson/libmesh,libMesh/libmesh,dschwen/libmesh,libMesh/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,dschwen/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,dschwen/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,roystgnr/libmesh,dschwen/libmesh,roystgnr/libmesh,libMesh/libmesh,jwpeterson/libmesh,dschwen/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,jwpeterson/libmesh,libMesh/libmesh
|
6e73b6097e1ad21d7cccc648404a82afe3e2ab4f
|
server/pipe.cpp
|
server/pipe.cpp
|
//
//
//
#include <thread>
#include "device-codec.hpp"
#include "device-id.h"
#include "log-wrapper.hpp"
#include "pipe.hpp"
namespace led_d
{
namespace
{
using char_t = core::device::codec_t::char_t;
char_t get_char (const core::matrix_t::column_t &column)
{
char_t res = 0, mask = 1;
for (std::size_t bit = 0; bit < core::matrix_t::column_size; ++bit) {
if (column.test (bit) == true)
res |= mask;
mask <<= 1;
}
return res;
}
void decode_1_char_msg (char_t msg_id, char_t serial_id, char_t info)
{
log_t::buffer_t buf;
bool complain = true;
switch (msg_id) {
case ID_HEADER_DECODE_FAILED:
buf << "Device failed to decode header for message with serial id \""
<< serial_id << "\"";
break;
case ID_STATUS:
if (info != ID_STATUS_OK) {
buf << "Bad status \"" << (int) info << "\" arrived for serial id \""
<< (int) serial_id << "\"";
} else {
complain = false;
}
break;
case ID_INVALID_MSG:
buf << "Device failed to recognize \"" << info
<< "\" as message id, serial id \"" << serial_id << "\"";
break;
case ID_BUTTON:
buf << "Not implemented \"button\" message is arrived, value \""
<< info << "\"";
break;
default:
{
buf << "Unknown message id \"" << msg_id << "\", serial id \""
<< serial_id << "\"";
log_t::error (buf);
}
break;
}
if (complain == true)
log_t::error (buf);
}
} // namespace anonymous
pipe_t::pipe_t (serial_t &serial)
: m_device (serial),
m_serial_id (0)
{
m_device.bind (std::bind (&pipe_t::decode, this, std::placeholders::_1),
std::bind (&pipe_t::write, this));
}
pipe_t::~pipe_t ()
{
}
bool pipe_t::render (const core::matrix_t &matrix)
{
if (matrix.size () > ID_MAX_MATRIX_SIZE)
return false;
//header and submatrix-type
constexpr std::size_t data_size = ID_MAX_SUB_MATRIX_SIZE - ID_HEADER_SIZE - 1;
// 1. convert
msg_t matrix_data;
for (std::size_t i = 0; i < matrix.size (); ++i)
matrix_data.push_back (get_char (matrix.get_column (i)));
// 2. split into submatrices
msg_t submatrix_data;
bool first = true;
while (matrix_data.empty () == false) {
auto upto = matrix_data.begin ();
bool last = (matrix_data.size () <= data_size) ? true : false;
std::advance (upto, last ? matrix_data.size () : data_size);
char_t sub_type = (first ? ID_SUB_MATRIX_TYPE_FIRST : 0)
| (last ? ID_SUB_MATRIX_TYPE_LAST : 0);
sub_type = (sub_type == 0) ? ID_SUB_MATRIX_TYPE_MIDDLE : sub_type;
submatrix_data.splice (submatrix_data.begin (), matrix_data,
matrix_data.begin (), upto);
msg_t sub_msg = codec_t::encode
(get_serial_id (), ID_SUB_MATRIX, sub_type, std::cref (submatrix_data));
m_write_queue.push (sub_msg);
}
return true;
}
void pipe_t::write ()
{
if ((m_block.can_go () == false)
|| (m_device.ready () == false))
return;
auto opt_msg = m_write_queue.pop ();
if (opt_msg.has_value () == false)
return;
// write changes argument => remember serial_id
char_t serial_id = opt_msg->front ();
if (m_device.write (*opt_msg) == true)
m_block.tighten (serial_id);
else {
log_t::buffer_t buf;
buf << "pipe: Failed to write message to serial";
log_t::error (buf);
}
}
void pipe_t::decode (msg_t &msg)
{
char_t msg_id = 0;
char_t serial_id = 0;
if (codec_t::decode_modify
(msg, std::ref (serial_id), std::ref (msg_id)) == false) {
log_t::error ("pipe: Failed to decode message header");
return;
}
// header is OK => try to relax blocker
m_block.relax (serial_id);
// blocker is relaxed => try to write
write ();
switch (msg_id) {
case ID_HEADER_DECODE_FAILED:
case ID_STATUS:
case ID_BUTTON:
case ID_INVALID_MSG:
{
char_t info = 0;
if (codec_t::decode_modify (msg, std::ref (info)) == false) {
log_t::buffer_t buf;
buf << "pipe: Failed to decode message body, message id: \""
<< msg_id << "\", serial id: \"" << serial_id << "\"";
log_t::error (buf);
return;
}
decode_1_char_msg (msg_id, serial_id, info);
}
break;
default:
{
log_t::buffer_t buf;
buf << "Unknown message is arrived with id \"" << msg_id
<< "\", serial id \"" << serial_id << "\"";
log_t::error (buf);
return;
}
break;
}
}
char_t pipe_t::get_serial_id ()
{
if (++m_serial_id != ID_DEVICE_SERIAL)
return m_serial_id;
return ++m_serial_id;
}
} // namespace led_d
|
//
//
//
#include <thread>
#include "device-codec.hpp"
#include "device-id.h"
#include "log-wrapper.hpp"
#include "pipe.hpp"
namespace led_d
{
namespace
{
using char_t = core::device::codec_t::char_t;
char_t get_char (const core::matrix_t::column_t &column)
{
char_t res = 0, mask = 1;
for (std::size_t bit = 0; bit < core::matrix_t::column_size; ++bit) {
if (column.test (bit) == true)
res |= mask;
mask <<= 1;
}
return res;
}
void decode_1_char_msg (char_t msg_id, char_t serial_id, char_t info)
{
log_t::buffer_t buf;
bool complain = true;
switch (msg_id) {
case ID_HEADER_DECODE_FAILED:
buf << "Device failed to decode header for message with serial id \""
<< serial_id << "\"";
break;
case ID_STATUS:
if (info != ID_STATUS_OK) {
buf << "Bad status \"" << (int) info << "\" arrived for serial id \""
<< (int) serial_id << "\"";
} else {
complain = false;
}
break;
case ID_INVALID_MSG:
buf << "Device failed to recognize \"" << info
<< "\" as message id, serial id \"" << serial_id << "\"";
break;
case ID_BUTTON:
buf << "Not implemented \"button\" message is arrived, value \""
<< info << "\"";
break;
default:
{
buf << "Unknown message id \"" << msg_id << "\", serial id \""
<< serial_id << "\"";
log_t::error (buf);
}
break;
}
if (complain == true)
log_t::error (buf);
}
} // namespace anonymous
pipe_t::pipe_t (serial_t &serial)
: m_device (serial),
m_serial_id (0)
{
m_device.bind (std::bind (&pipe_t::decode, this, std::placeholders::_1),
std::bind (&pipe_t::write, this));
}
pipe_t::~pipe_t ()
{
}
bool pipe_t::render (const core::matrix_t &matrix)
{
if (matrix.size () > ID_MAX_MATRIX_SIZE)
return false;
//header and submatrix-type
constexpr std::size_t data_size = ID_MAX_SUB_MATRIX_SIZE - ID_HEADER_SIZE - 1;
// 1. convert
msg_t matrix_data;
for (std::size_t i = 0; i < matrix.size (); ++i)
matrix_data.push_back (get_char (matrix.get_column (i)));
// 2. split into submatrices
msg_t submatrix_data;
bool first = true;
while (matrix_data.empty () == false) {
auto upto = matrix_data.begin ();
bool last = (matrix_data.size () <= data_size) ? true : false;
std::advance (upto, last ? matrix_data.size () : data_size);
char_t sub_type = (first ? ID_SUB_MATRIX_TYPE_FIRST : 0);
sub_type |= (last ? ID_SUB_MATRIX_TYPE_LAST : 0);
sub_type = (sub_type == 0) ? ID_SUB_MATRIX_TYPE_MIDDLE : sub_type;
submatrix_data.splice (submatrix_data.begin (), matrix_data,
matrix_data.begin (), upto);
msg_t sub_msg = codec_t::encode
(get_serial_id (), ID_SUB_MATRIX, sub_type, std::cref (submatrix_data));
m_write_queue.push (sub_msg);
}
return true;
}
void pipe_t::write ()
{
if ((m_block.can_go () == false)
|| (m_device.ready () == false))
return;
auto opt_msg = m_write_queue.pop ();
if (opt_msg.has_value () == false)
return;
// write changes argument => remember serial_id
char_t serial_id = opt_msg->front ();
if (m_device.write (*opt_msg) == true)
m_block.tighten (serial_id);
else {
log_t::buffer_t buf;
buf << "pipe: Failed to write message to serial";
log_t::error (buf);
}
}
void pipe_t::decode (msg_t &msg)
{
char_t msg_id = 0;
char_t serial_id = 0;
if (codec_t::decode_modify
(msg, std::ref (serial_id), std::ref (msg_id)) == false) {
log_t::error ("pipe: Failed to decode message header");
return;
}
// header is OK => try to relax blocker
m_block.relax (serial_id);
// blocker is relaxed => try to write
write ();
switch (msg_id) {
case ID_HEADER_DECODE_FAILED:
case ID_STATUS:
case ID_BUTTON:
case ID_INVALID_MSG:
{
char_t info = 0;
if (codec_t::decode_modify (msg, std::ref (info)) == false) {
log_t::buffer_t buf;
buf << "pipe: Failed to decode message body, message id: \""
<< msg_id << "\", serial id: \"" << serial_id << "\"";
log_t::error (buf);
return;
}
decode_1_char_msg (msg_id, serial_id, info);
}
break;
default:
{
log_t::buffer_t buf;
buf << "Unknown message is arrived with id \"" << msg_id
<< "\", serial id \"" << serial_id << "\"";
log_t::error (buf);
return;
}
break;
}
}
char_t pipe_t::get_serial_id ()
{
if (++m_serial_id != ID_DEVICE_SERIAL)
return m_serial_id;
return ++m_serial_id;
}
} // namespace led_d
|
Fix submatrix flag
|
server: Fix submatrix flag
|
C++
|
mit
|
cppcoder123/led-server,cppcoder123/led-server,cppcoder123/led-server
|
ef07524100927b4437ce399e41f9ce1a4c6ba0d7
|
Code/Common/mvdImageViewManipulator.cxx
|
Code/Common/mvdImageViewManipulator.cxx
|
/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdImageViewManipulator.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ImageViewManipulator
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
QObject( parent ),
m_NavigationContext(),
m_MouseContext()
{
// TODO: Remove later because initialized in struct's default constructor and resizeEvent().
this->InitializeContext(1,1);
}
/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}
/*******************************************************************************/
void
ImageViewManipulator
::InitializeContext(int width, int height)
{
ImageRegionType::SizeType initialSize;
initialSize[0] = width;
initialSize[1] = height;
// initialize with the given size
m_NavigationContext.m_ViewportImageRegion.SetSize(initialSize);
}
/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
// Update the context with the pressed position
m_MouseContext.x = event->x();
m_MouseContext.y = event->y();
}
/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
// Update the mouse context
m_MouseContext.dx = -event->x() + m_MouseContext.x;
m_MouseContext.dy = -event->y() + m_MouseContext.y;
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// print the region
//std::cout << "Region Before offset : "<< currentRegion << std::endl;
// Apply the offset to the (start) index of the stored region
ImageRegionType::OffsetType offset;
offset[0] = m_MouseContext.dx;
offset[1] = m_MouseContext.dy;
// Apply the offset to the (start) index of the stored region
IndexType index = currentRegion.GetIndex() + offset;
currentRegion.SetIndex(index);
// Constraint the region to the largestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
// print the region
//std::cout << "Region After offset : "<< m_NavigationContext.m_BufferedRegion << std::endl;
}
/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent( QMouseEvent * event)
{
//TODO: Implement mouseReleaseEvent.
//std::cout <<" Not Implemented yet ..." << std::endl;
}
/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Get the new widget size
ImageRegionType::SizeType size;
size[0] = event->size().width();
size[1] = event->size().height();
// Update the stored region with the new size
currentRegion.SetSize(size);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
ImageRegionType::SizeType zeroSize;
zeroSize.Fill(0);
if (largest.GetSize() != zeroSize)
{
// Else we can constrain it
IndexType index = region.GetIndex();
ImageRegionType::SizeType size = region.GetSize();
// If region is larger than big, then crop
if (region.GetSize()[0] > largest.GetSize()[0])
{
size[0] = largest.GetSize()[0];
}
if (region.GetSize()[1] > largest.GetSize()[1])
{
size[1] = largest.GetSize()[1];
}
// Else we can constrain it
// For each dimension
for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
{
// push left if necessary
if (region.GetIndex()[dim] < largest.GetIndex()[dim])
{
index[dim] = largest.GetIndex()[dim];
}
// push right if necessary
if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
{
index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
}
}
region.SetSize(size);
region.SetIndex(index);
}
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
/*****************************************************************************/
} // end namespace 'mvd'
|
/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdImageViewManipulator.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
namespace mvd
{
/*
TRANSLATOR mvd::ImageViewManipulator
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
QObject( parent ),
m_NavigationContext(),
m_MouseContext()
{
// TODO: Remove later because initialized in struct's default constructor and resizeEvent().
this->InitializeContext(1,1);
}
/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}
/*******************************************************************************/
void
ImageViewManipulator
::InitializeContext(int width, int height)
{
ImageRegionType::SizeType initialSize;
initialSize[0] = width;
initialSize[1] = height;
// initialize with the given size
m_NavigationContext.m_ViewportImageRegion.SetSize(initialSize);
}
/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
// Update the context with the pressed position
m_MouseContext.x = event->x();
m_MouseContext.y = event->y();
}
/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
// Update the mouse context
m_MouseContext.dx = -event->x() + m_MouseContext.x;
m_MouseContext.dy = -event->y() + m_MouseContext.y;
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Apply the offset to the (start) index of the stored region
ImageRegionType::OffsetType offset;
offset[0] = m_MouseContext.dx;
offset[1] = m_MouseContext.dy;
// Apply the offset to the (start) index of the stored region
IndexType index = currentRegion.GetIndex() + offset;
currentRegion.SetIndex(index);
// Constraint the region to the largestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent( QMouseEvent * event)
{
//TODO: Implement mouseReleaseEvent.
//std::cout <<" Not Implemented yet ..." << std::endl;
}
/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
// Update the navigation context
ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;
// Get the new widget size
ImageRegionType::SizeType size;
size[0] = event->size().width();
size[1] = event->size().height();
// Update the stored region with the new size
currentRegion.SetSize(size);
// Constraint this region to the LargestPossibleRegion
this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}
/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
ImageRegionType::SizeType zeroSize;
zeroSize.Fill(0);
if (largest.GetSize() != zeroSize)
{
// Else we can constrain it
IndexType index = region.GetIndex();
ImageRegionType::SizeType size = region.GetSize();
// If region is larger than big, then crop
if (region.GetSize()[0] > largest.GetSize()[0])
{
size[0] = largest.GetSize()[0];
}
if (region.GetSize()[1] > largest.GetSize()[1])
{
size[1] = largest.GetSize()[1];
}
// Else we can constrain it
// For each dimension
for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
{
// push left if necessary
if (region.GetIndex()[dim] < largest.GetIndex()[dim])
{
index[dim] = largest.GetIndex()[dim];
}
// push right if necessary
if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
{
index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
}
}
region.SetSize(size);
region.SetIndex(index);
}
}
/*****************************************************************************/
/* SLOTS */
/*****************************************************************************/
/*****************************************************************************/
} // end namespace 'mvd'
|
remove commented verbosity
|
ENH: remove commented verbosity
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
bbf822a6777256017f968469411d3db630087e07
|
cpp/patch_up_ppns_for_k10plus.cc
|
cpp/patch_up_ppns_for_k10plus.cc
|
/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "ControlNumberGuesser.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
const std::string OLD_PPN_LIST_FILE(UBTools::GetTuelibPath() + "alread_replaced_old_ppns.blob");
constexpr size_t OLD_PPN_LENGTH(9);
void LoadAlreadyProcessedPPNs(std::unordered_set<std::string> * const alread_processed_ppns) {
if (not FileUtil::Exists(OLD_PPN_LIST_FILE))
return;
std::string blob;
FileUtil::ReadStringOrDie(OLD_PPN_LIST_FILE, &blob);
if (unlikely((blob.length() % OLD_PPN_LENGTH) != 0))
LOG_ERROR("fractional PPN's are not possible!");
const size_t count(blob.length() / OLD_PPN_LENGTH);
alread_processed_ppns->reserve(count);
for (size_t i(0); i < count; ++i)
alread_processed_ppns->emplace(blob.substr(i * OLD_PPN_LENGTH, OLD_PPN_LENGTH));
}
void LoadMapping(MARC::Reader * const marc_reader, const std::unordered_set<std::string> &alread_processed_ppns,
std::unordered_map<std::string, std::string> * const old_to_new_map)
{
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (StringUtil::StartsWith(subfield_a, "(DE-576)")) {
const auto old_ppn(subfield_a.substr(__builtin_strlen("(DE-576)")));
if (alread_processed_ppns.find(old_ppn) == alread_processed_ppns.cend())
old_to_new_map->emplace(old_ppn, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " new mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
+ "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
db_connection->queryOrDie("SELECT DISTINCT " + column + " FROM " + table);
auto result_set(db_connection->getLastResultSet());
unsigned replacement_count(0);
while (const DbRow row = result_set.getNextRow()) {
const auto old_and_new(old_to_new_map.find(row[column]));
if (old_and_new != old_to_new_map.cend()) {
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_and_new->second
+ "' WHERE " + column + "='" + old_and_new->first + "'");
++replacement_count;
}
}
LOG_INFO("Replaced " + std::to_string(replacement_count) + " PPN's in ixtheo.keyword_translations.");
}
void StoreNewAlreadyProcessedPPNs(const std::unordered_set<std::string> &alread_processed_ppns,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
std::string blob;
blob.reserve(alread_processed_ppns.size() * OLD_PPN_LENGTH + old_to_new_map.size() * OLD_PPN_LENGTH);
for (const auto &alread_processed_ppn : alread_processed_ppns)
blob += alread_processed_ppn;
for (const auto &old_and_new_ppns : old_to_new_map)
blob += old_and_new_ppns.first;
FileUtil::WriteStringOrDie(OLD_PPN_LIST_FILE, blob);
}
} // unnamed namespace
int Main(int argc, char **argv) {
::progname = argv[0];
if (argc < 2)
::Usage("marc_input1 [marc_input2 .. marc_inputN]");
std::unordered_set<std::string> alread_processed_ppns;
LoadAlreadyProcessedPPNs(&alread_processed_ppns);
std::unordered_map<std::string, std::string> old_to_new_map;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), alread_processed_ppns, &old_to_new_map);
}
if (old_to_new_map.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
ControlNumberGuesser control_number_guesser;
control_number_guesser.swapControlNumbers(old_to_new_map);
std::string mysql_url;
VuFind::GetMysqlURL(&mysql_url);
DbConnection db_connection(mysql_url);
PatchTable(&db_connection, "vufind.resource", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.record", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.change_tracker", "id", old_to_new_map);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(&db_connection, "ixtheo.keyword_translations", "ppn", old_to_new_map);
PatchTable(&db_connection, "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name", old_to_new_map);
PatchTable(&db_connection, "vufind.ixtheo_pda_subscriptions", "book_ppn", old_to_new_map);
PatchTable(&db_connection, "vufind.relbib_ids", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.bibstudies_ids", "record_id", old_to_new_map);
} else {
PatchTable(&db_connection, "vufind.full_text_cache", "id", old_to_new_map);
PatchTable(&db_connection, "vufind.full_text_cache_urls", "id", old_to_new_map);
}
StoreNewAlreadyProcessedPPNs(alread_processed_ppns, old_to_new_map);
return EXIT_SUCCESS;
}
|
/** \file patch_up_ppns_for_k10plus.cc
* \brief Swaps out all persistent old PPN's with new PPN's.
* \author Dr. Johannes Ruscheinski
*/
/*
Copyright (C) 2019, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <cstring>
#include <kchashdb.h>
#include "Compiler.h"
#include "ControlNumberGuesser.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
#include "VuFind.h"
namespace {
const std::string OLD_PPN_LIST_FILE(UBTools::GetTuelibPath() + "alread_replaced_old_ppns.blob");
constexpr size_t OLD_PPN_LENGTH(9);
void LoadAlreadyProcessedPPNs(std::unordered_set<std::string> * const alread_processed_ppns) {
if (not FileUtil::Exists(OLD_PPN_LIST_FILE))
return;
std::string blob;
FileUtil::ReadStringOrDie(OLD_PPN_LIST_FILE, &blob);
if (unlikely((blob.length() % OLD_PPN_LENGTH) != 0))
LOG_ERROR("fractional PPN's are not possible!");
const size_t count(blob.length() / OLD_PPN_LENGTH);
alread_processed_ppns->reserve(count);
for (size_t i(0); i < count; ++i)
alread_processed_ppns->emplace(blob.substr(i * OLD_PPN_LENGTH, OLD_PPN_LENGTH));
}
void LoadMapping(MARC::Reader * const marc_reader, const std::unordered_set<std::string> &alread_processed_ppns,
std::unordered_map<std::string, std::string> * const old_to_new_map)
{
while (const auto record = marc_reader->read()) {
for (const auto &field : record.getTagRange("035")) {
const auto subfield_a(field.getFirstSubfieldWithCode('a'));
if (StringUtil::StartsWith(subfield_a, "(DE-576)")) {
const auto old_ppn(subfield_a.substr(__builtin_strlen("(DE-576)")));
if (alread_processed_ppns.find(old_ppn) == alread_processed_ppns.cend())
old_to_new_map->emplace(old_ppn, record.getControlNumber());
}
}
}
LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " new mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
+ "\".\n");
}
void PatchTable(DbConnection * const db_connection, const std::string &table, const std::string &column,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
db_connection->queryOrDie("SELECT DISTINCT " + column + " FROM " + table);
auto result_set(db_connection->getLastResultSet());
unsigned replacement_count(0);
while (const DbRow row = result_set.getNextRow()) {
const auto old_and_new(old_to_new_map.find(row[column]));
if (old_and_new != old_to_new_map.cend()) {
db_connection->queryOrDie("UPDATE IGNORE " + table + " SET " + column + "='" + old_and_new->second
+ "' WHERE " + column + "='" + old_and_new->first + "'");
++replacement_count;
}
}
LOG_INFO("Replaced " + std::to_string(replacement_count) + " PPN's in ixtheo.keyword_translations.");
}
void StoreNewAlreadyProcessedPPNs(const std::unordered_set<std::string> &alread_processed_ppns,
const std::unordered_map<std::string, std::string> &old_to_new_map)
{
std::string blob;
blob.reserve(alread_processed_ppns.size() * OLD_PPN_LENGTH + old_to_new_map.size() * OLD_PPN_LENGTH);
for (const auto &alread_processed_ppn : alread_processed_ppns)
blob += alread_processed_ppn;
for (const auto &old_and_new_ppns : old_to_new_map)
blob += old_and_new_ppns.first;
FileUtil::WriteStringOrDie(OLD_PPN_LIST_FILE, blob);
}
void PatchNotifiedDB(const std::string &user_type, const std::unordered_map<std::string, std::string> &old_to_new_map) {
const std::string DB_FILENAME(UBTools::GetTuelibPath() + user_type + "_notified.db");
std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB());
if (not (db->open(DB_FILENAME,
kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::OCREATE)))
{
LOG_INFO("\"" + DB_FILENAME + "\" not found!");
return;
}
unsigned updated_count(0);
for (const auto &old_and_new : old_to_new_map) {
std::string value;
if (db->get(old_and_new.first, &value)) {
if (unlikely(not db->remove(old_and_new.first)))
LOG_ERROR("failed to remove key \"" + old_and_new.first + "\" from \"" + DB_FILENAME + "\"!");
if (unlikely(not db->add(old_and_new.second, value)))
LOG_ERROR("failed to add key \"" + old_and_new.second + "\" from \"" + DB_FILENAME + "\"!");
++updated_count;
}
}
LOG_INFO("Updated " + std::to_string(updated_count) + " entries in \"" + DB_FILENAME + "\".");
}
} // unnamed namespace
int Main(int argc, char **argv) {
::progname = argv[0];
if (argc < 2)
::Usage("marc_input1 [marc_input2 .. marc_inputN]");
std::unordered_set<std::string> alread_processed_ppns;
LoadAlreadyProcessedPPNs(&alread_processed_ppns);
std::unordered_map<std::string, std::string> old_to_new_map;
for (int arg_no(1); arg_no < argc; ++arg_no) {
const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
LoadMapping(marc_reader.get(), alread_processed_ppns, &old_to_new_map);
}
if (old_to_new_map.empty()) {
LOG_INFO("nothing to do!");
return EXIT_SUCCESS;
}
PatchNotifiedDB("ixtheo", old_to_new_map);
PatchNotifiedDB("relbib", old_to_new_map);
ControlNumberGuesser control_number_guesser;
control_number_guesser.swapControlNumbers(old_to_new_map);
std::string mysql_url;
VuFind::GetMysqlURL(&mysql_url);
DbConnection db_connection(mysql_url);
PatchTable(&db_connection, "vufind.resource", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.record", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.change_tracker", "id", old_to_new_map);
if (VuFind::GetTueFindFlavour() == "ixtheo") {
PatchTable(&db_connection, "ixtheo.keyword_translations", "ppn", old_to_new_map);
PatchTable(&db_connection, "vufind.ixtheo_journal_subscriptions", "journal_control_number_or_bundle_name", old_to_new_map);
PatchTable(&db_connection, "vufind.ixtheo_pda_subscriptions", "book_ppn", old_to_new_map);
PatchTable(&db_connection, "vufind.relbib_ids", "record_id", old_to_new_map);
PatchTable(&db_connection, "vufind.bibstudies_ids", "record_id", old_to_new_map);
} else {
PatchTable(&db_connection, "vufind.full_text_cache", "id", old_to_new_map);
PatchTable(&db_connection, "vufind.full_text_cache_urls", "id", old_to_new_map);
}
StoreNewAlreadyProcessedPPNs(alread_processed_ppns, old_to_new_map);
return EXIT_SUCCESS;
}
|
Patch new_journal_alert notification databases.
|
Patch new_journal_alert notification databases.
|
C++
|
agpl-3.0
|
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
|
4d92f445ce8c6bdeb6ac781b88d80cdf09b68715
|
src/clients/earthWatcher/kml.cc
|
src/clients/earthWatcher/kml.cc
|
/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Use Google's libkml to out a KML file based upon the current network topology.
* @author [email protected]
*/
#define CUSTOM_ICON // use non-default icon for nodes
// libkml
#include "kml/convenience/convenience.h"
#include "kml/engine.h"
#include "kml/dom.h"
#include "libwatcher/watcherGraph.h"
#include <boost/lexical_cast.hpp>
using kmldom::ChangePtr;
using kmldom::CreatePtr;
using kmldom::CoordinatesPtr;
using kmldom::DocumentPtr;
using kmldom::FeaturePtr;
using kmldom::FolderPtr;
using kmldom::IconStyleIconPtr;
using kmldom::IconStylePtr;
using kmldom::KmlFactory;
using kmldom::KmlPtr;
using kmldom::LabelStylePtr;
using kmldom::LineStringPtr;
using kmldom::LineStylePtr;
using kmldom::MultiGeometryPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
using kmldom::StylePtr;
using kmldom::UpdatePtr;
using kmlengine::KmlFile;
using kmlengine::KmlFilePtr;
using namespace watcher;
namespace {
#ifdef CUSTOM_ICON
/*
* Keep a mapping to the random Icon associated with a particular node so that the
* same icon is used between invocations of write_kml().
*/
typedef std::map<NodeIdentifier, std::string> NodeIconMap ;
typedef NodeIconMap::iterator NodeIconMapIterator ;
NodeIconMap nodeIconMap;
const std::string BASE_ICON_URL = "http://maps.google.com/mapfiles/kml/shapes/";
// interesting icons for placemarks
const char *ICONS[] = {
"cabs.png",
"bus.png",
"rail.png",
"truck.png",
"airports.png",
"ferry.png",
"heliport.png",
"tram.png",
"sailing.png"
};
// template to get the number of items in an array
template <typename T, int N> size_t sizeof_array( T (&)[N] ) { return N; }
void icon_setup(KmlFactory* kmlFac, DocumentPtr document)
{
// set up styles for each icon we use, using the icon name as the id
for (size_t i = 0; i < sizeof_array(ICONS); ++i) {
IconStyleIconPtr icon(kmlFac->CreateIconStyleIcon());
std::string url(BASE_ICON_URL + ICONS[i]);
icon->set_href(url.c_str());
IconStylePtr iconStyle(kmlFac->CreateIconStyle());
iconStyle->set_icon(icon);
StylePtr style(kmlFac->CreateStyle());
style->set_iconstyle(iconStyle);
style->set_id(ICONS[i]);
document->add_styleselector(style);
}
}
/*
* For testing purposes, randomly select an interesting icon to replace the default yellow pushpin.
* In order to use the same icon between invocations of write_kml(), a map is used to store the icon
* selected.
*/
void set_node_icon(const WatcherGraphNode& node, PlacemarkPtr ptr)
{
std::string styleUrl;
NodeIconMapIterator it = nodeIconMap.find(node.nodeId);
if (it == nodeIconMap.end()) {
styleUrl = std::string("#") + ICONS[ random() % sizeof_array(ICONS) ];
nodeIconMap[node.nodeId] = styleUrl;
} else
styleUrl = it->second;
ptr->set_styleurl(styleUrl);
}
#endif // CUSTOM_ICON
void output_nodes(KmlFactory* kmlFac, const WatcherGraph& graph, FolderPtr folder)
{
// iterate over all nodes in the graph
WatcherGraph::vertexIterator vi, vend;
for (tie(vi, vend) = vertices(graph.theGraph); vi != vend; ++vi) {
const WatcherGraphNode &node = graph.theGraph[*vi];
PlacemarkPtr ptr = kmlFac->CreatePlacemark();
std::string ip(node.nodeId.to_string());
ptr->set_name(ip); // textual label, can be html
//ptr->set_id(ip); // internal label for locating object in the DOM tree
// set the location
ptr->set_geometry(kmlconvenience::CreatePointLatLon(node.gpsData->y, node.gpsData->x));
/*
//target id is required when changing some attribute of a feature already in the dom
ptr->set_targetid("node0");
*/
#ifdef CUSTOM_ICON
set_node_icon(node, ptr);
#endif
folder->add_feature(ptr);//add to DOM
}
}
/*
* Convert a watcher color to the KML format.
*/
std::string watcher_color_to_kml(const watcher::Color& color)
{
char buf[sizeof("aabbggrr")];
sprintf(buf, "%02x%02x%02x%02x", color.a, color.b, color.g, color.r);
return std::string(buf);
}
void output_edges(KmlFactory* kmlFac, const WatcherGraph& graph, DocumentPtr document, FolderPtr folder)
{
WatcherGraph::edgeIterator ei, eend;
unsigned int count = 0;
bool has_style = false;
for (tie(ei, eend) = edges(graph.theGraph); ei != eend; ++ei, ++count) {
const WatcherGraphEdge &edge = graph.theGraph[*ei];
const WatcherGraphNode &node1 = graph.theGraph[source(*ei, graph.theGraph)];
const WatcherGraphNode &node2 = graph.theGraph[target(*ei, graph.theGraph)];
CoordinatesPtr coords = kmlFac->CreateCoordinates();
coords->add_latlng(node1.gpsData->y, node1.gpsData->x);
coords->add_latlng(node2.gpsData->y, node2.gpsData->x);
LineStringPtr lineString = kmlFac->CreateLineString();
lineString->set_coordinates(coords);
CoordinatesPtr pointCoords(kmlFac->CreateCoordinates());
//place label at the midpoint on the line between the two nodes
pointCoords->add_latlng((node1.gpsData->y + node2.gpsData->y)/2,(node1.gpsData->x + node2.gpsData->x)/2);
PointPtr point(kmlFac->CreatePoint());
point->set_coordinates(pointCoords);
/*
* Google Earth doesn't allow a label to be attached to something without a Point, so
* we need to create a container with the LineString and the Point at which to attach
* the label/icon.
*/
MultiGeometryPtr multiGeo(kmlFac->CreateMultiGeometry());
multiGeo->add_geometry(lineString);
multiGeo->add_geometry(point);
PlacemarkPtr ptr = kmlFac->CreatePlacemark();
ptr->set_geometry(multiGeo);
// WatcherGraphEdge supports multiple labels per edge, but GE only supports one, so just use the first label in the list
LabelDisplayInfoPtr labelDisplayInfo(edge.labels.front());
if (labelDisplayInfo) {
ptr->set_name(labelDisplayInfo->labelText);
}
// WatcherGraph only has a single style per layer, so we stash the value somewhere instead of creating multiple styles
if (!has_style) {
LineStylePtr lineStyle(kmlFac->CreateLineStyle());
lineStyle->set_color(watcher_color_to_kml(edge.displayInfo->color));
lineStyle->set_width(edge.displayInfo->width);
IconStylePtr iconStyle(kmlFac->CreateIconStyle());
iconStyle->set_scale(0); // scale to 0 should mean hide it?
StylePtr style(kmlFac->CreateStyle());
style->set_id("edge-style");
style->set_linestyle(lineStyle);
style->set_iconstyle(iconStyle);
if (labelDisplayInfo) {
LabelStylePtr labelStyle(kmlFac->CreateLabelStyle());
labelStyle->set_color(watcher_color_to_kml(labelDisplayInfo->foregroundColor));
style->set_labelstyle(labelStyle);
}
document->add_styleselector(style);
has_style = true;
}
ptr->set_styleurl("#edge-style");
folder->add_feature(ptr);//add to DOM
}
}
} // end namespace
void write_kml(const WatcherGraph& graph, const std::string& outputFile)
{
// libkml boilerplate
KmlFactory* kmlFac(kmldom::KmlFactory::GetFactory());
KmlPtr kml(kmlFac->CreateKml());
/*
* create initial DOM tree. As nodes appear, they get added to the tree.
* As nodes move, we update the position attribute
* in the DOM, and regenerate the KML file.
*/
DocumentPtr document(kmlFac->CreateDocument());
kml->set_feature(document);
FolderPtr folder(kmlFac->CreateFolder());
folder->set_name("Watcher");
document->add_feature(folder);
#ifdef CUSTOM_ICON
icon_setup(kmlFac, document);
#endif // CUSTOM_ICON
output_nodes(kmlFac, graph, folder);
output_edges(kmlFac, graph, document, folder);
kmlbase::File::WriteStringToFile(kmldom::SerializePretty(kml), outputFile);
}
|
/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER 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.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Use Google's libkml to out a KML file based upon the current network topology.
* @author [email protected]
*/
#define CUSTOM_ICON // use non-default icon for nodes
// libkml
#include "kml/convenience/convenience.h"
#include "kml/engine.h"
#include "kml/dom.h"
#include "libwatcher/watcherGraph.h"
#include <boost/lexical_cast.hpp>
using kmldom::ChangePtr;
using kmldom::CreatePtr;
using kmldom::CoordinatesPtr;
using kmldom::DocumentPtr;
using kmldom::FeaturePtr;
using kmldom::FolderPtr;
using kmldom::IconStyleIconPtr;
using kmldom::IconStylePtr;
using kmldom::KmlFactory;
using kmldom::KmlPtr;
using kmldom::LabelStylePtr;
using kmldom::LineStringPtr;
using kmldom::LineStylePtr;
using kmldom::MultiGeometryPtr;
using kmldom::PlacemarkPtr;
using kmldom::PointPtr;
using kmldom::StylePtr;
using kmldom::UpdatePtr;
using kmlengine::KmlFile;
using kmlengine::KmlFilePtr;
using namespace watcher;
namespace {
#ifdef CUSTOM_ICON
/*
* Keep a mapping to the random Icon associated with a particular node so that the
* same icon is used between invocations of write_kml().
*/
typedef std::map<NodeIdentifier, std::string> NodeIconMap ;
typedef NodeIconMap::iterator NodeIconMapIterator ;
NodeIconMap nodeIconMap;
const std::string BASE_ICON_URL = "http://maps.google.com/mapfiles/kml/shapes/";
// interesting icons for placemarks
const char *ICONS[] = {
"cabs.png",
"bus.png",
"rail.png",
"truck.png",
"airports.png",
"ferry.png",
"heliport.png",
"tram.png",
"sailing.png"
};
// template to get the number of items in an array
template <typename T, int N> size_t sizeof_array( T (&)[N] ) { return N; }
void icon_setup(KmlFactory* kmlFac, DocumentPtr document)
{
// set up styles for each icon we use, using the icon name as the id
for (size_t i = 0; i < sizeof_array(ICONS); ++i) {
IconStyleIconPtr icon(kmlFac->CreateIconStyleIcon());
std::string url(BASE_ICON_URL + ICONS[i]);
icon->set_href(url.c_str());
IconStylePtr iconStyle(kmlFac->CreateIconStyle());
iconStyle->set_icon(icon);
StylePtr style(kmlFac->CreateStyle());
style->set_iconstyle(iconStyle);
style->set_id(ICONS[i]);
document->add_styleselector(style);
}
}
/*
* For testing purposes, randomly select an interesting icon to replace the default yellow pushpin.
* In order to use the same icon between invocations of write_kml(), a map is used to store the icon
* selected.
*/
void set_node_icon(const WatcherGraphNode& node, PlacemarkPtr ptr)
{
std::string styleUrl;
NodeIconMapIterator it = nodeIconMap.find(node.nodeId);
if (it == nodeIconMap.end()) {
styleUrl = std::string("#") + ICONS[ random() % sizeof_array(ICONS) ];
nodeIconMap[node.nodeId] = styleUrl;
} else
styleUrl = it->second;
ptr->set_styleurl(styleUrl);
}
#endif // CUSTOM_ICON
void output_nodes(KmlFactory* kmlFac, const WatcherGraph& graph, FolderPtr folder)
{
// iterate over all nodes in the graph
WatcherGraph::vertexIterator vi, vend;
for (tie(vi, vend) = vertices(graph.theGraph); vi != vend; ++vi) {
const WatcherGraphNode &node = graph.theGraph[*vi];
PlacemarkPtr ptr = kmlFac->CreatePlacemark();
std::string ip(node.nodeId.to_string());
ptr->set_name(ip); // textual label, can be html
// set the location
ptr->set_geometry(kmlconvenience::CreatePointLatLon(node.gpsData->y, node.gpsData->x));
//target id is required when changing some attribute of a feature already in the dom
//ptr->set_targetid("node0");
#ifdef CUSTOM_ICON
set_node_icon(node, ptr);
#endif
folder->add_feature(ptr);//add to DOM
}
}
/*
* Convert a watcher color to the KML format.
*/
std::string watcher_color_to_kml(const watcher::Color& color)
{
char buf[sizeof("aabbggrr")];
sprintf(buf, "%02x%02x%02x%02x", color.a, color.b, color.g, color.r);
return std::string(buf);
}
void output_edges(KmlFactory* kmlFac, const WatcherGraph& graph, DocumentPtr document, FolderPtr folder)
{
WatcherGraph::edgeIterator ei, eend;
unsigned int count = 0;
bool has_style = false;
for (tie(ei, eend) = edges(graph.theGraph); ei != eend; ++ei, ++count) {
const WatcherGraphEdge &edge = graph.theGraph[*ei];
const WatcherGraphNode &node1 = graph.theGraph[source(*ei, graph.theGraph)];
const WatcherGraphNode &node2 = graph.theGraph[target(*ei, graph.theGraph)];
CoordinatesPtr coords = kmlFac->CreateCoordinates();
coords->add_latlng(node1.gpsData->y, node1.gpsData->x);
coords->add_latlng(node2.gpsData->y, node2.gpsData->x);
LineStringPtr lineString = kmlFac->CreateLineString();
lineString->set_coordinates(coords);
CoordinatesPtr pointCoords(kmlFac->CreateCoordinates());
//place label at the midpoint on the line between the two nodes
pointCoords->add_latlng((node1.gpsData->y + node2.gpsData->y)/2,(node1.gpsData->x + node2.gpsData->x)/2);
PointPtr point(kmlFac->CreatePoint());
point->set_coordinates(pointCoords);
/*
* Google Earth doesn't allow a label to be attached to something without a Point, so
* we need to create a container with the LineString and the Point at which to attach
* the label/icon.
*/
MultiGeometryPtr multiGeo(kmlFac->CreateMultiGeometry());
multiGeo->add_geometry(lineString);
multiGeo->add_geometry(point);
PlacemarkPtr ptr = kmlFac->CreatePlacemark();
ptr->set_geometry(multiGeo);
// WatcherGraphEdge supports multiple labels per edge, but GE only supports one, so just use the first label in the list
LabelDisplayInfoPtr labelDisplayInfo(edge.labels.front());
if (labelDisplayInfo) {
ptr->set_name(labelDisplayInfo->labelText);
}
// WatcherGraph only has a single style per layer, so we stash the value somewhere instead of creating multiple styles
if (!has_style) {
LineStylePtr lineStyle(kmlFac->CreateLineStyle());
lineStyle->set_color(watcher_color_to_kml(edge.displayInfo->color));
lineStyle->set_width(edge.displayInfo->width);
IconStylePtr iconStyle(kmlFac->CreateIconStyle());
iconStyle->set_scale(0); // scale to 0 should mean hide it?
StylePtr style(kmlFac->CreateStyle());
style->set_id("edge-style");
style->set_linestyle(lineStyle);
style->set_iconstyle(iconStyle);
if (labelDisplayInfo) {
LabelStylePtr labelStyle(kmlFac->CreateLabelStyle());
labelStyle->set_color(watcher_color_to_kml(labelDisplayInfo->foregroundColor));
style->set_labelstyle(labelStyle);
}
document->add_styleselector(style);
has_style = true;
}
ptr->set_styleurl("#edge-style");
folder->add_feature(ptr);//add to DOM
}
}
} // end namespace
void write_kml(const WatcherGraph& graph, const std::string& outputFile)
{
// libkml boilerplate
KmlFactory* kmlFac(kmldom::KmlFactory::GetFactory());
KmlPtr kml(kmlFac->CreateKml());
/*
* create initial DOM tree. As nodes appear, they get added to the tree.
* As nodes move, we update the position attribute
* in the DOM, and regenerate the KML file.
*/
DocumentPtr document(kmlFac->CreateDocument());
kml->set_feature(document);
FolderPtr folder(kmlFac->CreateFolder());
folder->set_name("Watcher");
document->add_feature(folder);
#ifdef CUSTOM_ICON
icon_setup(kmlFac, document);
#endif // CUSTOM_ICON
output_nodes(kmlFac, graph, folder);
output_edges(kmlFac, graph, document, folder);
kmlbase::File::WriteStringToFile(kmldom::SerializePretty(kml), outputFile);
}
|
remove commented out code
|
remove commented out code
|
C++
|
agpl-3.0
|
glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization
|
ec54a19ee787844e0342d57446589b2d4f11aefa
|
tests/server/mediaElement.cpp
|
tests/server/mediaElement.cpp
|
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE MediaElement
#include <boost/test/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <MediaElementImpl.hpp>
#include <ElementConnectionData.hpp>
#include <MediaType.hpp>
using namespace kurento;
BOOST_AUTO_TEST_CASE (connection_test)
{
gst_init (NULL, NULL);
std::shared_ptr <MediaPipelineImpl> pipe (new MediaPipelineImpl (
boost::property_tree::ptree() ) );
std::shared_ptr <MediaElementImpl> sink (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysink") );
std::shared_ptr <MediaElementImpl> src (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysrc") );
std::shared_ptr <MediaType> VIDEO (new MediaType (MediaType::VIDEO) );
std::shared_ptr <MediaType> AUDIO (new MediaType (MediaType::AUDIO) );
src->setName ("SOURCE");
sink->setName ("SINK");
src->connect (sink);
auto connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 2);
for (auto it : connections) {
BOOST_CHECK (it->getSource()->getId() == src->getId() );
}
g_object_set (src->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);
connections = src->getSinkConnections ();
BOOST_CHECK (connections.size() == 2);
for (auto it : connections) {
BOOST_CHECK (it->getSource()->getId() == src->getId() );
}
connections = sink->getSourceConnections (AUDIO);
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (AUDIO, "");
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (AUDIO, "test");
BOOST_CHECK (connections.size() == 0);
connections = sink->getSourceConnections (VIDEO);
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "");
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "test");
BOOST_CHECK (connections.size() == 0);
src->disconnect (sink);
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 0);
src->connect (sink, AUDIO);
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 1);
connections = src->getSinkConnections ();
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "");
BOOST_CHECK (connections.size() == 0);
src.reset();
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 0);
}
|
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE MediaElement
#include <boost/test/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <MediaElementImpl.hpp>
#include <ElementConnectionData.hpp>
#include <MediaType.hpp>
using namespace kurento;
BOOST_AUTO_TEST_CASE (connection_test)
{
gst_init (NULL, NULL);
std::shared_ptr <MediaPipelineImpl> pipe (new MediaPipelineImpl (
boost::property_tree::ptree() ) );
std::shared_ptr <MediaElementImpl> sink (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysink") );
std::shared_ptr <MediaElementImpl> src (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysrc") );
std::shared_ptr <MediaType> VIDEO (new MediaType (MediaType::VIDEO) );
std::shared_ptr <MediaType> AUDIO (new MediaType (MediaType::AUDIO) );
src->setName ("SOURCE");
sink->setName ("SINK");
src->connect (sink);
auto connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 2);
for (auto it : connections) {
BOOST_CHECK (it->getSource()->getId() == src->getId() );
}
g_object_set (src->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);
g_object_set (sink->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);
connections = src->getSinkConnections ();
BOOST_CHECK (connections.size() == 2);
for (auto it : connections) {
BOOST_CHECK (it->getSource()->getId() == src->getId() );
}
connections = sink->getSourceConnections (AUDIO);
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (AUDIO, "");
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (AUDIO, "test");
BOOST_CHECK (connections.size() == 0);
connections = sink->getSourceConnections (VIDEO);
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "");
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "test");
BOOST_CHECK (connections.size() == 0);
src->disconnect (sink);
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 0);
src->connect (sink, AUDIO);
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 1);
connections = src->getSinkConnections ();
BOOST_CHECK (connections.size() == 1);
connections = sink->getSourceConnections (VIDEO, "");
BOOST_CHECK (connections.size() == 0);
src.reset();
connections = sink->getSourceConnections ();
BOOST_CHECK (connections.size() == 0);
}
BOOST_AUTO_TEST_CASE (release_before_real_connection)
{
GstElement *srcElement;
gst_init (NULL, NULL);
std::shared_ptr <MediaPipelineImpl> pipe (new MediaPipelineImpl (
boost::property_tree::ptree() ) );
std::shared_ptr <MediaElementImpl> sink (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysink") );
std::shared_ptr <MediaElementImpl> src (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummysrc") );
src->setName ("SOURCE");
sink->setName ("SINK");
g_object_set (sink->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);
srcElement = (GstElement *) g_object_ref (src->getGstreamerElement() );
g_object_set (srcElement, "audio", TRUE, NULL);
src->connect (sink);
src->disconnect (sink);
src->release ();
src.reset();
sink->release();
sink.reset();
g_object_set (srcElement, "audio", TRUE, "video", TRUE, NULL);
g_object_unref (srcElement);
}
BOOST_AUTO_TEST_CASE (loopback)
{
gst_init (NULL, NULL);
std::shared_ptr <MediaPipelineImpl> pipe (new MediaPipelineImpl (
boost::property_tree::ptree() ) );
std::shared_ptr <MediaElementImpl> duplex (new MediaElementImpl (
boost::property_tree::ptree(), pipe, "dummyduplex") );
duplex->setName ("DUPLEX");
g_object_set (duplex->getGstreamerElement(), "src-audio", TRUE, "src-video",
TRUE, "sink-audio", TRUE, "sink-video", TRUE, NULL);
duplex->connect (duplex);
duplex->release();
}
|
Add more connection tests
|
MediaElement: Add more connection tests
Change-Id: I0ba4c30bba40d1eb4f1f70922c4a208676b4cd29
|
C++
|
apache-2.0
|
Kurento/kms-core,ESTOS/kms-core,Kurento/kms-core,shelsonjava/kms-core,Kurento/kms-core,TribeMedia/kms-core,ESTOS/kms-core,ESTOS/kms-core,shelsonjava/kms-core,TribeMedia/kms-core,TribeMedia/kms-core,shelsonjava/kms-core,Kurento/kms-core,shelsonjava/kms-core,ESTOS/kms-core,TribeMedia/kms-core
|
53aa5b63a9ee971727d2ff62a25dacc3abf0286b
|
src/icu_util.cc
|
src/icu_util.cc
|
// Copyright 2013 the V8 project authors. 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 "icu_util.h"
#if defined(_WIN32)
#include <windows.h>
#endif
#if defined(V8_I18N_SUPPORT)
#include <stdio.h>
#include "unicode/putil.h"
#include "unicode/udata.h"
#define ICU_UTIL_DATA_FILE 0
#define ICU_UTIL_DATA_SHARED 1
#define ICU_UTIL_DATA_STATIC 2
#define ICU_UTIL_DATA_SYMBOL "icudt" U_ICU_VERSION_SHORT "_dat"
#define ICU_UTIL_DATA_SHARED_MODULE_NAME "icudt.dll"
#endif
namespace v8 {
namespace internal {
bool InitializeICU(const char* icu_data_file) {
#if !defined(V8_I18N_SUPPORT)
return true;
#else
#if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED
// We expect to find the ICU data module alongside the current module.
HMODULE module = LoadLibraryA(ICU_UTIL_DATA_SHARED_MODULE_NAME);
if (!module) return false;
FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL);
if (!addr) return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC
// Mac/Linux bundle the ICU data in.
return true;
#elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE
if (!icu_data_file) return false;
FILE* inf = fopen(icu_data_file, "rb");
if (!inf) return false;
fseek(inf, 0, SEEK_END);
size_t size = ftell(inf);
rewind(inf);
char* addr = new char[size];
if (fread(addr, 1, size, inf) != size) {
delete[] addr;
fclose(inf);
return false;
}
fclose(inf);
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#endif
#endif
}
} } // namespace v8::internal
|
// Copyright 2013 the V8 project authors. 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 "icu_util.h"
#if defined(_WIN32)
#include <windows.h>
#endif
#if defined(V8_I18N_SUPPORT)
#include <stdio.h>
#include <stdlib.h>
#include "unicode/putil.h"
#include "unicode/udata.h"
#define ICU_UTIL_DATA_FILE 0
#define ICU_UTIL_DATA_SHARED 1
#define ICU_UTIL_DATA_STATIC 2
#define ICU_UTIL_DATA_SYMBOL "icudt" U_ICU_VERSION_SHORT "_dat"
#define ICU_UTIL_DATA_SHARED_MODULE_NAME "icudt.dll"
#endif
namespace v8 {
namespace internal {
#if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE
namespace {
char* g_icu_data_ptr = NULL;
void free_icu_data_ptr() {
delete[] g_icu_data_ptr;
}
} // namespace
#endif
bool InitializeICU(const char* icu_data_file) {
#if !defined(V8_I18N_SUPPORT)
return true;
#else
#if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED
// We expect to find the ICU data module alongside the current module.
HMODULE module = LoadLibraryA(ICU_UTIL_DATA_SHARED_MODULE_NAME);
if (!module) return false;
FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL);
if (!addr) return false;
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(addr), &err);
return err == U_ZERO_ERROR;
#elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC
// Mac/Linux bundle the ICU data in.
return true;
#elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE
if (!icu_data_file) return false;
if (g_icu_data_ptr) return true;
FILE* inf = fopen(icu_data_file, "rb");
if (!inf) return false;
fseek(inf, 0, SEEK_END);
size_t size = ftell(inf);
rewind(inf);
g_icu_data_ptr = new char[size];
if (fread(g_icu_data_ptr, 1, size, inf) != size) {
delete[] g_icu_data_ptr;
g_icu_data_ptr = NULL;
fclose(inf);
return false;
}
fclose(inf);
atexit(free_icu_data_ptr);
UErrorCode err = U_ZERO_ERROR;
udata_setCommonData(reinterpret_cast<void*>(g_icu_data_ptr), &err);
return err == U_ZERO_ERROR;
#endif
#endif
}
} } // namespace v8::internal
|
Clean up ICU data tables on shutdown.
|
Clean up ICU data tables on shutdown.
This is only used by d8 if compiled with external data tables, or an
embedder that uses external data tables and v8's version of ICU.
BUG=none
[email protected]
LOG=n
Review URL: https://codereview.chromium.org/210973007
git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@20283 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
|
C++
|
mit
|
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
|
ba8c205253b35b05a17024edd831e49340a0dfc9
|
tests/test_serialize_file.cpp
|
tests/test_serialize_file.cpp
|
#define BOOST_TEST_MODULE "test_serialize_file"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
#include <fstream>
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
{
std::ofstream ofs("tmp1.toml");
ofs << data;
}
const auto serialized = toml::parse("tmp1.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << data;
}
const auto serialized = toml::parse("tmp2.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << data;
}
const auto serialized = toml::parse("tmp3.toml");
BOOST_CHECK(data == serialized);
}
|
#define BOOST_TEST_MODULE "test_serialize_file"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
#include <fstream>
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
{
std::ofstream ofs("tmp1.toml");
ofs << data;
}
auto serialized = toml::parse("tmp1.toml");
{
auto& owner = toml::get<toml::table>(serialized.at("owner"));
auto& bio = toml::get<std::string>(owner.at("bio"));
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << data;
}
const auto serialized = toml::parse("tmp2.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << data;
}
const auto serialized = toml::parse("tmp3.toml");
BOOST_CHECK(data == serialized);
}
|
change CRLF into LF before comparison
|
fix: change CRLF into LF before comparison
|
C++
|
mit
|
ToruNiina/toml11
|
71fd904be5b287e036565be72f836b2e5fd3dca7
|
urbackupclient/ClientHash.cpp
|
urbackupclient/ClientHash.cpp
|
#include "ClientHash.h"
#include "../Interface/File.h"
#include "../urbackupcommon/os_functions.h"
#include <memory>
#include <cstring>
#include <assert.h>
#include "../urbackupcommon/ExtentIterator.h"
#include "../fileservplugin/chunk_settings.h"
#include "../stringtools.h"
#include "../common/adler32.h"
#include "../md5.h"
#include "../urbackupcommon/TreeHash.h"
namespace
{
bool buf_is_zero(const char* buf, size_t bsize)
{
for (size_t i = 0; i < bsize; ++i)
{
if (buf[i] != 0)
{
return false;
}
}
return true;
}
std::string build_sparse_extent_content()
{
char buf[c_small_hash_dist] = {};
_u32 small_hash = urb_adler32(urb_adler32(0, NULL, 0), buf, c_small_hash_dist);
small_hash = little_endian(small_hash);
MD5 big_hash;
for (int64 i = 0; i<c_checkpoint_dist; i += c_small_hash_dist)
{
big_hash.update(reinterpret_cast<unsigned char*>(buf), c_small_hash_dist);
}
big_hash.finalize();
std::string ret;
ret.resize(chunkhash_single_size);
char* ptr = &ret[0];
memcpy(ptr, big_hash.raw_digest_int(), big_hash_size);
ptr += big_hash_size;
for (int64 i = 0; i < c_checkpoint_dist; i += c_small_hash_dist)
{
memcpy(ptr, &small_hash, sizeof(small_hash));
ptr += sizeof(small_hash);
}
return ret;
}
}
ClientHash::ClientHash(IFile * index_hdat_file,
bool own_hdat_file,
int64 index_hdat_fs_block_size,
size_t* snapshot_sequence_id, size_t snapshot_sequence_id_reference)
: index_hdat_file(index_hdat_file),
own_hdat_file(own_hdat_file),
index_hdat_fs_block_size(index_hdat_fs_block_size),
index_chunkhash_pos(-1),
snapshot_sequence_id(snapshot_sequence_id),
snapshot_sequence_id_reference(snapshot_sequence_id_reference)
{
}
ClientHash::~ClientHash()
{
if (own_hdat_file)
{
Server->destroy(index_hdat_file);
}
}
bool ClientHash::getShaBinary(const std::string & fn, IHashFunc & hf, bool with_cbt)
{
std::auto_ptr<IFsFile> f(Server->openFile(os_file_prefix(fn), MODE_READ_SEQUENTIAL_BACKUP));
if (f.get() == NULL)
{
return false;
}
int64 skip_start = -1;
bool needs_seek = false;
const size_t bsize = 512 * 1024;
int64 fpos = 0;
_u32 rc = 1;
std::vector<char> buf;
buf.resize(bsize);
FsExtentIterator extent_iterator(f.get(), bsize);
IFsFile::SSparseExtent curr_sparse_extent = extent_iterator.nextExtent();
int64 fsize = f->Size();
bool has_more_extents = false;
std::vector<IFsFile::SFileExtent> extents;
size_t curr_extent_idx = 0;
if (with_cbt
&& fsize>c_checkpoint_dist)
{
extents = f->getFileExtents(0, index_hdat_fs_block_size, has_more_extents);
}
else
{
with_cbt = false;
}
while (fpos <= fsize && rc>0)
{
while (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset + curr_sparse_extent.size<fpos)
{
curr_sparse_extent = extent_iterator.nextExtent();
}
size_t curr_bsize = bsize;
if (fpos + static_cast<int64>(curr_bsize) > fsize)
{
curr_bsize = static_cast<size_t>(fsize - fpos);
}
if (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset <= fpos
&& curr_sparse_extent.offset + curr_sparse_extent.size >= fpos + static_cast<int64>(bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
Server->Log("Sparse extent at fpos " + convert(fpos), LL_DEBUG);
fpos += bsize;
rc = static_cast<_u32>(bsize);
continue;
}
index_chunkhash_pos = -1;
if (!extents.empty()
&& index_hdat_file != NULL
&& fpos%c_checkpoint_dist == 0
&& curr_bsize == bsize)
{
assert(bsize == c_checkpoint_dist);
while (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size < fpos)
{
++curr_extent_idx;
if (curr_extent_idx >= extents.size()
&& has_more_extents)
{
extents = f->getFileExtents(fpos, index_hdat_fs_block_size, has_more_extents);
curr_extent_idx = 0;
}
}
if (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset <= fpos
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size >= fpos + static_cast<int64>(bsize))
{
int64 volume_pos = extents[curr_extent_idx].volume_offset + (fpos - extents[curr_extent_idx].offset);
index_chunkhash_pos = (volume_pos / c_checkpoint_dist)*(sizeof(_u16) + chunkhash_single_size);
index_chunkhash_pos_offset = static_cast<_u16>((volume_pos%c_checkpoint_dist) / 512);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference
&& index_hdat_file->Read(index_chunkhash_pos, chunkhash, sizeof(chunkhash)) == sizeof(chunkhash))
{
_u16 chunkhash_offset;
memcpy(&chunkhash_offset, chunkhash, sizeof(chunkhash_offset));
if (index_chunkhash_pos_offset == chunkhash_offset
&& !buf_is_zero(chunkhash, sizeof(chunkhash)))
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
std::string cbt_info = "fpos=" + convert(fpos) + " extent_offset=" + convert(extents[curr_extent_idx].offset) +
" extent_length=" + convert(extents[curr_extent_idx].size) +
" volume_pos=" + convert(volume_pos);
if (memcmp(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size) == 0)
{
Server->Log("Sparse extent from CBT data at "+cbt_info, LL_DEBUG);
if (skip_start == -1)
{
skip_start = fpos;
}
}
else
{
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
Server->Log("Hash data from CBT data at "+ cbt_info + ": "+
base64_encode((unsigned char*)(chunkhash + sizeof(_u16)), chunkhash_single_size), LL_DEBUG);
hf.addHashAllAdler(chunkhash + sizeof(_u16), chunkhash_single_size, bsize);
}
fpos += bsize;
rc = bsize;
needs_seek = true;
continue;
}
}
else
{
index_chunkhash_pos = -1;
}
}
}
if (skip_start != -1
|| needs_seek)
{
f->Seek(fpos);
needs_seek = false;
}
if (curr_bsize > 0)
{
bool has_read_error = false;
rc = f->Read(buf.data(), static_cast<_u32>(curr_bsize), &has_read_error);
if (has_read_error)
{
std::string msg;
int64 code = os_last_error(msg);
Server->Log("Read error while hashing \"" + fn + "\". " + msg + " (code: " + convert(code) + ")", LL_ERROR);
return false;
}
}
else
{
rc = 0;
}
if (rc == bsize && buf_is_zero(buf.data(), bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
Server->Log("Sparse extent (zeroes) at fpos " + convert(fpos), LL_DEBUG);
fpos += bsize;
rc = bsize;
if (index_chunkhash_pos != -1)
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
continue;
}
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
if (rc > 0)
{
hf.hash(buf.data(), rc);
fpos += rc;
}
}
return true;
}
void ClientHash::hash_output_all_adlers(int64 pos, const char * hash, size_t hsize)
{
Server->Log("Hash output at pos " + convert(pos) + ": " + base64_encode((const unsigned char*)hash, hsize),
LL_DEBUG);
if (index_chunkhash_pos != -1
&& index_hdat_file != NULL)
{
assert(hsize == chunkhash_single_size);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), hash, chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
}
|
#include "ClientHash.h"
#include "../Interface/File.h"
#include "../urbackupcommon/os_functions.h"
#include <memory>
#include <cstring>
#include <assert.h>
#include "../urbackupcommon/ExtentIterator.h"
#include "../fileservplugin/chunk_settings.h"
#include "../stringtools.h"
#include "../common/adler32.h"
#include "../md5.h"
#include "../urbackupcommon/TreeHash.h"
#define EX_DEBUG(x)
namespace
{
bool buf_is_zero(const char* buf, size_t bsize)
{
for (size_t i = 0; i < bsize; ++i)
{
if (buf[i] != 0)
{
return false;
}
}
return true;
}
std::string build_sparse_extent_content()
{
char buf[c_small_hash_dist] = {};
_u32 small_hash = urb_adler32(urb_adler32(0, NULL, 0), buf, c_small_hash_dist);
small_hash = little_endian(small_hash);
MD5 big_hash;
for (int64 i = 0; i<c_checkpoint_dist; i += c_small_hash_dist)
{
big_hash.update(reinterpret_cast<unsigned char*>(buf), c_small_hash_dist);
}
big_hash.finalize();
std::string ret;
ret.resize(chunkhash_single_size);
char* ptr = &ret[0];
memcpy(ptr, big_hash.raw_digest_int(), big_hash_size);
ptr += big_hash_size;
for (int64 i = 0; i < c_checkpoint_dist; i += c_small_hash_dist)
{
memcpy(ptr, &small_hash, sizeof(small_hash));
ptr += sizeof(small_hash);
}
return ret;
}
}
ClientHash::ClientHash(IFile * index_hdat_file,
bool own_hdat_file,
int64 index_hdat_fs_block_size,
size_t* snapshot_sequence_id, size_t snapshot_sequence_id_reference)
: index_hdat_file(index_hdat_file),
own_hdat_file(own_hdat_file),
index_hdat_fs_block_size(index_hdat_fs_block_size),
index_chunkhash_pos(-1),
snapshot_sequence_id(snapshot_sequence_id),
snapshot_sequence_id_reference(snapshot_sequence_id_reference)
{
}
ClientHash::~ClientHash()
{
if (own_hdat_file)
{
Server->destroy(index_hdat_file);
}
}
bool ClientHash::getShaBinary(const std::string & fn, IHashFunc & hf, bool with_cbt)
{
std::auto_ptr<IFsFile> f(Server->openFile(os_file_prefix(fn), MODE_READ_SEQUENTIAL_BACKUP));
if (f.get() == NULL)
{
return false;
}
int64 skip_start = -1;
bool needs_seek = false;
const size_t bsize = 512 * 1024;
int64 fpos = 0;
_u32 rc = 1;
std::vector<char> buf;
buf.resize(bsize);
FsExtentIterator extent_iterator(f.get(), bsize);
IFsFile::SSparseExtent curr_sparse_extent = extent_iterator.nextExtent();
int64 fsize = f->Size();
bool has_more_extents = false;
std::vector<IFsFile::SFileExtent> extents;
size_t curr_extent_idx = 0;
if (with_cbt
&& fsize>c_checkpoint_dist)
{
extents = f->getFileExtents(0, index_hdat_fs_block_size, has_more_extents);
}
else
{
with_cbt = false;
}
while (fpos <= fsize && rc>0)
{
while (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset + curr_sparse_extent.size<fpos)
{
curr_sparse_extent = extent_iterator.nextExtent();
}
size_t curr_bsize = bsize;
if (fpos + static_cast<int64>(curr_bsize) > fsize)
{
curr_bsize = static_cast<size_t>(fsize - fpos);
}
if (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset <= fpos
&& curr_sparse_extent.offset + curr_sparse_extent.size >= fpos + static_cast<int64>(bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
EX_DEBUG(Server->Log("Sparse extent at fpos " + convert(fpos), LL_DEBUG);)
fpos += bsize;
rc = static_cast<_u32>(bsize);
continue;
}
index_chunkhash_pos = -1;
if (!extents.empty()
&& index_hdat_file != NULL
&& fpos%c_checkpoint_dist == 0
&& curr_bsize == bsize)
{
assert(bsize == c_checkpoint_dist);
while (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size < fpos)
{
++curr_extent_idx;
if (curr_extent_idx >= extents.size()
&& has_more_extents)
{
extents = f->getFileExtents(fpos, index_hdat_fs_block_size, has_more_extents);
curr_extent_idx = 0;
}
}
if (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset <= fpos
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size >= fpos + static_cast<int64>(bsize))
{
int64 volume_pos = extents[curr_extent_idx].volume_offset + (fpos - extents[curr_extent_idx].offset);
index_chunkhash_pos = (volume_pos / c_checkpoint_dist)*(sizeof(_u16) + chunkhash_single_size);
index_chunkhash_pos_offset = static_cast<_u16>((volume_pos%c_checkpoint_dist) / 512);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference
&& index_hdat_file->Read(index_chunkhash_pos, chunkhash, sizeof(chunkhash)) == sizeof(chunkhash))
{
_u16 chunkhash_offset;
memcpy(&chunkhash_offset, chunkhash, sizeof(chunkhash_offset));
if (index_chunkhash_pos_offset == chunkhash_offset
&& !buf_is_zero(chunkhash, sizeof(chunkhash)))
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
EX_DEBUG(std::string cbt_info = "fpos=" + convert(fpos) + " extent_offset=" + convert(extents[curr_extent_idx].offset) +
" extent_length=" + convert(extents[curr_extent_idx].size) +
" volume_pos=" + convert(volume_pos);)
if (memcmp(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size) == 0)
{
EX_DEBUG(Server->Log("Sparse extent from CBT data at "+cbt_info, LL_DEBUG);)
if (skip_start == -1)
{
skip_start = fpos;
}
}
else
{
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
EX_DEBUG(Server->Log("Hash data from CBT data at "+ cbt_info + ": "+
base64_encode((unsigned char*)(chunkhash + sizeof(_u16)), chunkhash_single_size), LL_DEBUG);)
hf.addHashAllAdler(chunkhash + sizeof(_u16), chunkhash_single_size, bsize);
}
fpos += bsize;
rc = bsize;
needs_seek = true;
continue;
}
}
else
{
index_chunkhash_pos = -1;
}
}
}
if (skip_start != -1
|| needs_seek)
{
f->Seek(fpos);
needs_seek = false;
}
if (curr_bsize > 0)
{
bool has_read_error = false;
rc = f->Read(buf.data(), static_cast<_u32>(curr_bsize), &has_read_error);
if (has_read_error)
{
std::string msg;
int64 code = os_last_error(msg);
Server->Log("Read error while hashing \"" + fn + "\". " + msg + " (code: " + convert(code) + ")", LL_ERROR);
return false;
}
}
else
{
rc = 0;
}
if (rc == bsize && buf_is_zero(buf.data(), bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
EX_DEBUG(Server->Log("Sparse extent (zeroes) at fpos " + convert(fpos), LL_DEBUG);)
fpos += bsize;
rc = bsize;
if (index_chunkhash_pos != -1)
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
continue;
}
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
if (rc > 0)
{
hf.hash(buf.data(), rc);
fpos += rc;
}
}
return true;
}
void ClientHash::hash_output_all_adlers(int64 pos, const char * hash, size_t hsize)
{
EX_DEBUG(Server->Log("Hash output at pos " + convert(pos) + ": " + base64_encode((const unsigned char*)hash, hsize),
LL_DEBUG);)
if (index_chunkhash_pos != -1
&& index_hdat_file != NULL)
{
assert(hsize == chunkhash_single_size);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), hash, chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
}
|
Remove debug logging
|
Remove debug logging
|
C++
|
agpl-3.0
|
uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend
|
6b96ae27bcf197ed33c8be948e45ab730ae8b996
|
c7a/common/concurrent_queue.hpp
|
c7a/common/concurrent_queue.hpp
|
/*******************************************************************************
* c7a/common/concurrent_queue.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_COMMON_CONCURRENT_QUEUE_HEADER
#define C7A_COMMON_CONCURRENT_QUEUE_HEADER
#if HAVE_INTELTBB
#include <tbb/concurrent_queue.h>
#else // !HAVE_INTELTBB
#include <queue>
#include <mutex>
#endif // !HAVE_INTELTBB
namespace c7a {
namespace common {
#if HAVE_INTELTBB
template <typename T>
using concurrent_queue = tbb::concurrent_queue<T>;
#else // !HAVE_INTELTBB
/*!
* This is a queue, similar to std::queue and tbb::concurrent_queue, except that
* it uses mutexes for synchronization. This implementation is only here to be
* used if the Intel TBB is not available.
*
* Not all methods of tbb:concurrent_queue<> are available here, please add them
* if you need them. However, NEVER add any other methods that you might need.
*/
template <typename T>
class concurrent_queue
{
public:
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
protected:
//! the actual data queue
std::queue<T> queue_;
//! the mutex to lock before accessing the queue
mutable std::mutex mutex_;
public:
//! Pushes a copy of source onto back of the queue.
void push(const T& source) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(source);
}
//! Pushes given element into the queue by utilizing element's move
//! constructor
void push(T&& elem) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(std::move(elem));
}
//! Pushes a new element into the queue. The element is constructed with
//! given arguments.
template <typename ... Arguments>
void emplace(Arguments&& ... args) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.emplace(args ...);
}
//! Returns: true if queue has no items; false otherwise.
bool empty() const {
std::unique_lock<std::mutex> lock(mutex_);
return queue_.empty();
}
//! If value is available, pops it from the queue, assigns it to
//! destination, and destroys the original value. Otherwise does nothing.
bool try_pop(T& destination) {
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.empty())
return false;
destination = std::move(queue_.front());
queue_.pop();
return true;
}
//! Clears the queue.
void clear() {
std::unique_lock<std::mutex> lock(mutex_);
queue_.clear();
}
};
#endif // !HAVE_INTELTBB
} // namespace common
} // namespace c7a
#endif // !C7A_COMMON_CONCURRENT_QUEUE_HEADER
/******************************************************************************/
|
/*******************************************************************************
* c7a/common/concurrent_queue.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_COMMON_CONCURRENT_QUEUE_HEADER
#define C7A_COMMON_CONCURRENT_QUEUE_HEADER
//#if HAVE_INTELTBB
//#include <tbb/concurrent_queue.h>
//#else // !HAVE_INTELTBB
#include <queue>
#include <mutex>
//#endif // !HAVE_INTELTBB
namespace c7a {
namespace common {
/*#if HAVE_INTELTBB
template <typename T>
using concurrent_queue = tbb::concurrent_queue<T>;
#else // !HAVE_INTELTBB*/
/*!
* This is a queue, similar to std::queue and tbb::concurrent_queue, except that
* it uses mutexes for synchronization. This implementation is only here to be
* used if the Intel TBB is not available.
*
* Not all methods of tbb:concurrent_queue<> are available here, please add them
* if you need them. However, NEVER add any other methods that you might need.
*/
template <typename T>
class concurrent_queue
{
public:
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
protected:
//! the actual data queue
std::queue<T> queue_;
//! the mutex to lock before accessing the queue
mutable std::mutex mutex_;
public:
//! Pushes a copy of source onto back of the queue.
void push(const T& source) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(source);
}
//! Pushes given element into the queue by utilizing element's move
//! constructor
void push(T&& elem) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(std::move(elem));
}
//! Pushes a new element into the queue. The element is constructed with
//! given arguments.
template <typename ... Arguments>
void emplace(Arguments&& ... args) {
std::unique_lock<std::mutex> lock(mutex_);
queue_.emplace(args ...);
}
//! Returns: true if queue has no items; false otherwise.
bool empty() const {
std::unique_lock<std::mutex> lock(mutex_);
return queue_.empty();
}
//! If value is available, pops it from the queue, assigns it to
//! destination, and destroys the original value. Otherwise does nothing.
bool try_pop(T& destination) {
std::unique_lock<std::mutex> lock(mutex_);
if (queue_.empty())
return false;
destination = std::move(queue_.front());
queue_.pop();
return true;
}
//! Clears the queue.
void clear() {
std::unique_lock<std::mutex> lock(mutex_);
queue_.clear();
}
};
//#endif // !HAVE_INTELTBB
} // namespace common
} // namespace c7a
#endif // !C7A_COMMON_CONCURRENT_QUEUE_HEADER
/******************************************************************************/
|
remove usage of tbb::concurrent_queue, as it seems to be less immune to race conditions than the other implementation (?)
|
remove usage of tbb::concurrent_queue, as it seems to be less immune to race conditions than the other implementation (?)
|
C++
|
bsd-2-clause
|
manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill
|
7debf628142d15717669707c9d1d6b678751070c
|
src/matching.cc
|
src/matching.cc
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
using Row = std::vector<double>;
using Rows = std::vector<Row>;
double distance(const Row& lhs, const Row& rhs) {
assert(lhs.size() == rhs.size());
auto sqdists = Row{};
sqdists.reserve(lhs.size());
std::transform(
std::begin(lhs), std::end(lhs), std::begin(rhs),
std::back_inserter(sqdists),
[](const double l, const double r) { return std::pow(l - r, 2); });
return std::accumulate(std::begin(sqdists), std::end(sqdists), 0.0);
}
Row parseRow(const std::string& str) {
auto row = Row{};
std::stringstream ss{str};
std::string tmp;
while (getline(ss, tmp, ',')) {
row.push_back(std::stod(tmp));
}
return row;
}
std::vector<std::size_t> matchingPositions(const Rows& original, const Rows& modified) {
assert(original.size() == modified.size());
auto positions = std::vector<std::size_t>{};
positions.reserve(original.size());
auto ps = std::vector<std::size_t>(original.size());
std::iota(std::begin(ps), std::end(ps), 0u);
for (const auto& orow : original) {
std::sort(std::begin(ps), std::end(ps),
[&orow, &modified](const std::size_t l, const std::size_t r) {
return distance(orow, modified[l]) >
distance(orow, modified[r]);
});
positions.push_back(ps.back());
ps.pop_back();
}
return positions;
}
int main() {
auto k = 0u;
std::cin >> k;
if (k == 0) { return EXIT_FAILURE; }
auto lines = std::vector<std::string>{};
auto iit = std::istream_iterator<std::string>{std::cin};
auto eit = std::istream_iterator<std::string>{};
std::copy(iit, eit, std::back_inserter(lines));
auto originalRows = std::vector<Row>(k);
auto modifiedRows = std::vector<Row>(k);
std::transform(std::begin(lines), std::begin(lines) + k,
std::begin(originalRows), parseRow);
std::transform(std::begin(lines) + k, std::end(lines),
std::begin(modifiedRows), parseRow);
const auto ps = matchingPositions(originalRows, modifiedRows);
for (auto i = 0u; i < k; ++i) {
std::cout << i << ',' << ps[i] << '\n';
}
}
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <iterator>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
using Row = std::vector<double>;
using Rows = std::vector<Row>;
double distance(const Row& lhs, const Row& rhs) {
assert(lhs.size() == rhs.size());
auto sqdists = Row{};
sqdists.reserve(lhs.size());
std::transform(
std::begin(lhs), std::end(lhs), std::begin(rhs),
std::back_inserter(sqdists),
[](const double l, const double r) { return std::pow(l - r, 2); });
return std::accumulate(std::begin(sqdists), std::end(sqdists), 0.0);
}
Row parseRow(const std::string& str) {
auto row = Row{};
std::stringstream ss{str};
std::string tmp;
while (getline(ss, tmp, ',')) {
row.push_back(std::stod(tmp));
}
return row;
}
std::vector<std::size_t> matchingPositions(const Rows& original, const Rows& modified) {
assert(original.size() == modified.size());
auto positions = std::vector<std::size_t>{};
positions.reserve(original.size());
auto ps = std::vector<std::size_t>(original.size());
std::iota(std::begin(ps), std::end(ps), 0u);
for (const auto& orow : original) {
std::sort(std::begin(ps), std::end(ps),
[&orow, &modified](const std::size_t l, const std::size_t r) {
return distance(orow, modified[l]) >
distance(orow, modified[r]);
});
positions.push_back(ps.back());
ps.pop_back();
}
return positions;
}
int main() {
auto k = 0u;
std::cin >> k;
if (k == 0) { return EXIT_FAILURE; }
auto lines = std::vector<std::string>{};
auto iit = std::istream_iterator<std::string>{std::cin};
auto eit = std::istream_iterator<std::string>{};
std::copy(iit, eit, std::back_inserter(lines));
auto originalRows = std::vector<Row>(k);
auto modifiedRows = std::vector<Row>(k);
std::transform(std::begin(lines), std::begin(lines) + k,
std::begin(originalRows), parseRow);
std::transform(std::begin(lines) + k, std::end(lines),
std::begin(modifiedRows), parseRow);
const auto ps = matchingPositions(originalRows, modifiedRows);
for (auto i = 0u; i < k; ++i) {
std::cout << i << ',' << ps[i] << '\n';
}
}
|
Solve "Matching Datasets" and "Matching Datasets++".
|
Solve "Matching Datasets" and "Matching Datasets++".
|
C++
|
mit
|
kdungs/codecon
|
b36dcccc49185e12452360264ca996c8f9461a95
|
src/primecount.cpp
|
src/primecount.cpp
|
///
/// @file primecount.cpp
/// @brief primecount C++ API
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef HAVE_MPI
#include <mpi.h>
namespace primecount {
int mpi_num_procs()
{
int procs;
MPI_Comm_size(MPI_COMM_WORLD, &procs);
return procs;
}
int mpi_proc_id()
{
int proc_id;
MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);
return proc_id;
}
int mpi_master_proc_id()
{
return 0;
}
bool is_mpi_master_proc()
{
return mpi_proc_id() == mpi_master_proc_id();
}
} // namespace
#endif
using namespace std;
namespace {
#ifdef _OPENMP
int threads_ = max(1, omp_get_max_threads());
#else
int threads_ = 1;
#endif
int status_precision_ = -1;
double alpha_ = -1;
// Below 10^7 the Deleglise-Rivat algorithm is slower than LMO
const int deleglise_rivat_threshold = 10000000;
}
namespace primecount {
int64_t pi(int64_t x)
{
return pi(x, threads_);
}
int64_t pi(int64_t x, int threads)
{
if (x < deleglise_rivat_threshold)
return pi_lmo(x, threads);
else
return pi_deleglise_rivat(x, threads);
}
#ifdef HAVE_INT128_T
int128_t pi(int128_t x)
{
return pi(x, threads_);
}
int128_t pi(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi((int64_t) x, threads);
else
return pi_deleglise_rivat(x, threads);
}
#endif
/// Alias for the fastest prime counting function in primecount.
/// @param x integer arithmetic expression e.g. "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x)
{
return pi(x, threads_);
}
/// Alias for the fastest prime counting function in primecount.
/// @param x integer arithmetic expression e.g. "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x, int threads)
{
maxint_t pi_x = pi(to_maxint(x), threads);
ostringstream oss;
oss << pi_x;
return oss.str();
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x, int threads)
{
return pi_deleglise_rivat_parallel2(x, threads);
}
#ifdef HAVE_INT128_T
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi_deleglise_rivat((int64_t) x, threads);
else
return pi_deleglise_rivat_parallel3(x, threads);
}
#endif
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
return pi_legendre(x, threads_);
}
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x)
{
return pi_lehmer(x, threads_);
}
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x)
{
return pi_lmo(x, threads_);
}
/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x, int threads)
{
return pi_lmo_parallel3(x, threads);
}
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x)
{
return pi_meissel(x, threads_);
}
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
return pi_primesieve(x, threads_);
}
/// Calculate the nth prime using a combination of the prime
/// counting function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
return nth_prime(n, threads_);
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
return phi(x, a, threads_);
}
/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max can be a 128-bit
/// integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
ostringstream oss;
#ifdef HAVE_INT128_T
// primecount is limited by:
// z < 2^62, with z = x^(2/3) / alpha
// x^(2/3) / alpha < 2^62
// x < (2^62 * alpha)^(3/2)
// safety buffer: use 61 instead of 62
double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
oss << (int128_t) max_x;
#else
unused_param(alpha);
oss << numeric_limits<int64_t>::max();
#endif
return oss.str();
}
/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
return omp_get_wtime();
#else
return (double) (std::clock() / CLOCKS_PER_SEC);
#endif
}
int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
thread_threshold = max((int64_t) 1, thread_threshold);
threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
threads = max(1, threads);
return threads;
}
void set_alpha(double alpha)
{
alpha_ = alpha;
}
double get_alpha()
{
return alpha_;
}
double get_alpha(maxint_t x, int64_t y)
{
// y = x13 * alpha, thus alpha = y / x13
double x13 = (double) iroot<3>(x);
return (double) y / x13;
}
/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
double alpha = get_alpha();
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
double a = 0.00156512;
double b = -0.0261411;
double c = 0.990948;
double logx = log((double) x);
alpha = a * pow(logx, 2) + b * logx + c;
}
return in_between(1, alpha, iroot<6>(x));
}
/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
double alpha = get_alpha();
double x2 = (double) x;
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
if (x2 <= 1e21)
{
double a = 0.000711339;
double b = -0.0160586;
double c = 0.123034;
double d = 0.802942;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
else
{
// Because of CPU cache misses sieving (S2_hard(x) and P2(x))
// becomes the main bottleneck above 10^21 . Hence we use a
// different alpha formula when x > 10^21 which returns a larger
// alpha which reduces sieving but increases S2_easy(x) work.
double a = 0.00149066;
double b = -0.0375705;
double c = 0.282139;
double d = 0.591972;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
}
return in_between(1, alpha, iroot<6>(x));
}
void set_num_threads(int threads)
{
#ifdef _OPENMP
threads_ = in_between(1, threads, omp_get_max_threads());
#else
unused_param(threads);
#endif
}
int get_num_threads()
{
return threads_;
}
void set_status_precision(int precision)
{
status_precision_ = in_between(0, precision, 5);
}
int get_status_precision(maxint_t x)
{
// use default precision when no command-line precision provided
if (status_precision_ < 0)
{
if ((double) x >= 1e23)
return 2;
if ((double) x >= 1e21)
return 1;
}
return (status_precision_ > 0) ? status_precision_ : 0;
}
maxint_t to_maxint(const string& expr)
{
maxint_t n = calculator::eval<maxint_t>(expr);
return n;
}
/// Get the primecount version number, in the form “i.j”.
string primecount_version()
{
return PRIMECOUNT_VERSION;
}
} // namespace
|
///
/// @file primecount.cpp
/// @brief primecount C++ API
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef HAVE_MPI
#include <mpi.h>
namespace primecount {
int mpi_num_procs()
{
int procs;
MPI_Comm_size(MPI_COMM_WORLD, &procs);
return procs;
}
int mpi_proc_id()
{
int proc_id;
MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);
return proc_id;
}
int mpi_master_proc_id()
{
return 0;
}
bool is_mpi_master_proc()
{
return mpi_proc_id() == mpi_master_proc_id();
}
} // namespace
#endif
using namespace std;
namespace {
int threads_ = -1;
int status_precision_ = -1;
double alpha_ = -1;
// Below 10^7 the Deleglise-Rivat algorithm is slower than LMO
const int deleglise_rivat_threshold = 10000000;
}
namespace primecount {
int64_t pi(int64_t x)
{
return pi(x, get_num_threads());
}
int64_t pi(int64_t x, int threads)
{
if (x < deleglise_rivat_threshold)
return pi_lmo(x, threads);
else
return pi_deleglise_rivat(x, threads);
}
#ifdef HAVE_INT128_T
int128_t pi(int128_t x)
{
return pi(x, get_num_threads());
}
int128_t pi(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi((int64_t) x, threads);
else
return pi_deleglise_rivat(x, threads);
}
#endif
/// Alias for the fastest prime counting function in primecount.
/// @param x integer arithmetic expression e.g. "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x)
{
return pi(x, get_num_threads());
}
/// Alias for the fastest prime counting function in primecount.
/// @param x integer arithmetic expression e.g. "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x, int threads)
{
maxint_t pi_x = pi(to_maxint(x), threads);
ostringstream oss;
oss << pi_x;
return oss.str();
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x)
{
return pi_deleglise_rivat(x, get_num_threads());
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x, int threads)
{
return pi_deleglise_rivat_parallel2(x, threads);
}
#ifdef HAVE_INT128_T
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x)
{
return pi_deleglise_rivat(x, get_num_threads());
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi_deleglise_rivat((int64_t) x, threads);
else
return pi_deleglise_rivat_parallel3(x, threads);
}
#endif
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
return pi_legendre(x, get_num_threads());
}
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x)
{
return pi_lehmer(x, get_num_threads());
}
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x)
{
return pi_lmo(x, get_num_threads());
}
/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x, int threads)
{
return pi_lmo_parallel3(x, threads);
}
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x)
{
return pi_meissel(x, get_num_threads());
}
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
return pi_primesieve(x, get_num_threads());
}
/// Calculate the nth prime using a combination of the prime
/// counting function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
return nth_prime(n, get_num_threads());
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
return phi(x, a, get_num_threads());
}
/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max can be a 128-bit
/// integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
ostringstream oss;
#ifdef HAVE_INT128_T
// primecount is limited by:
// z < 2^62, with z = x^(2/3) / alpha
// x^(2/3) / alpha < 2^62
// x < (2^62 * alpha)^(3/2)
// safety buffer: use 61 instead of 62
double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
oss << (int128_t) max_x;
#else
unused_param(alpha);
oss << numeric_limits<int64_t>::max();
#endif
return oss.str();
}
/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
return omp_get_wtime();
#else
return (double) (std::clock() / CLOCKS_PER_SEC);
#endif
}
int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
thread_threshold = max((int64_t) 1, thread_threshold);
threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
threads = max(1, threads);
return threads;
}
void set_alpha(double alpha)
{
alpha_ = alpha;
}
double get_alpha()
{
return alpha_;
}
double get_alpha(maxint_t x, int64_t y)
{
// y = x13 * alpha, thus alpha = y / x13
double x13 = (double) iroot<3>(x);
return (double) y / x13;
}
/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
double alpha = get_alpha();
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
double a = 0.00156512;
double b = -0.0261411;
double c = 0.990948;
double logx = log((double) x);
alpha = a * pow(logx, 2) + b * logx + c;
}
return in_between(1, alpha, iroot<6>(x));
}
/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
double alpha = get_alpha();
double x2 = (double) x;
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
if (x2 <= 1e21)
{
double a = 0.000711339;
double b = -0.0160586;
double c = 0.123034;
double d = 0.802942;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
else
{
// Because of CPU cache misses sieving (S2_hard(x) and P2(x))
// becomes the main bottleneck above 10^21 . Hence we use a
// different alpha formula when x > 10^21 which returns a larger
// alpha which reduces sieving but increases S2_easy(x) work.
double a = 0.00149066;
double b = -0.0375705;
double c = 0.282139;
double d = 0.591972;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
}
return in_between(1, alpha, iroot<6>(x));
}
void set_num_threads(int threads)
{
#ifdef _OPENMP
threads_ = in_between(1, threads, omp_get_max_threads());
#else
unused_param(threads);
#endif
}
int get_num_threads()
{
#ifdef _OPENMP
if (threads_ != -1)
return threads_;
else
return max(1, omp_get_max_threads());
#else
return 1;
#endif
}
void set_status_precision(int precision)
{
status_precision_ = in_between(0, precision, 5);
}
int get_status_precision(maxint_t x)
{
// use default precision when no command-line precision provided
if (status_precision_ < 0)
{
if ((double) x >= 1e23)
return 2;
if ((double) x >= 1e21)
return 1;
}
return (status_precision_ > 0) ? status_precision_ : 0;
}
maxint_t to_maxint(const string& expr)
{
maxint_t n = calculator::eval<maxint_t>(expr);
return n;
}
/// Get the primecount version number, in the form “i.j”.
string primecount_version()
{
return PRIMECOUNT_VERSION;
}
} // namespace
|
Fix get_num_threads() static compilation issue
|
Fix get_num_threads() static compilation issue
The previous code used threads_ = 1 on Linux when compiled statically even if OpenMP was enabled and the CPU had multiple CPU cores.
|
C++
|
bsd-2-clause
|
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
|
2e6a3752ab9415e15eb408b683e782aba27fc49b
|
src/qt/bitcoin.cpp
|
src/qt/bitcoin.cpp
|
/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. CapriCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "CapriCoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("CapriCoin");
//XXX app.setOrganizationDomain("");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("CapriCoin-Qt-testnet");
else
app.setApplicationName("CapriCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
|
/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QApplication>
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;
static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
// in case of modal message, use blocking connection to wait for user to click OK
QMetaObject::invokeMethod(guiref, "error",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
}
static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(QString, QString::fromStdString(strURI)));
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63));
QApplication::instance()->processEvents();
}
}
static void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Capricoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Do this early as we don't want to bother initializing if we are just calling IPC
ipcScanRelay(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Capricoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Capricoin");
//XXX app.setOrganizationDomain("");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Capricoin-Qt-testnet");
else
app.setApplicationName("Capricoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.QueueShutdown.connect(QueueShutdown);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
BitcoinGUI window;
guiref = &window;
if(AppInit2())
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit(argc, argv);
app.exec();
window.hide();
window.setClientModel(0);
window.setWalletModel(0);
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
|
Update bitcoin.cpp
|
Update bitcoin.cpp
|
C++
|
mit
|
Capricoinofficial/Capricoin,Capricoinofficial/Capricoin,Capricoinofficial/Capricoin,Capricoinofficial/Capricoin,Capricoinofficial/Capricoin
|
1d397be28d62889ca996af2cf5d79c1962841a44
|
src/options.cpp
|
src/options.cpp
|
#include "StdAfx.h"
/*
Command line and options file option handling for ultracomm.
*/
UltracommOptions::UltracommOptions(const int& argc, char* argv[])
{
//string appName = boost::filesystem::basename(argv[0]);
// Command-line-only options.
po::options_description cmdonly("Ultracomm command-line-only options");
cmdonly.add_options()
("help,h", "print help message and stop")
("version", "print ultracomm version and stop")
("optfile,o", po::value<string>(), "parameter options file (see below)")
;
// Options allowed in options file or on command line.
po::options_description cmd_or_file("Ultracomm options for command line or options file");
cmd_or_file.add_options()
("address,a", po::value<string>()->required(), "ultrasonix ip address")
("output,O", po::value<string>()->required(), "base output name (including path)")
("b-depth", po::value<int>(), "b-depth")
("datatype", po::value<int>(), "datatype")
("trigger_out", po::value<int>(), "trigger out")
("trigger_out_2", po::value<int>(), "trigger out 2")
("verbose,v", "display informational messages")
;
// Now combine into full set of command line options.
po::options_description cmdline_options;
cmdline_options.add(cmdonly).add(cmd_or_file);
// Read command line options into opt.
po::store(po::parse_command_line(argc, argv, cmdline_options), opt);
// This precedes po::notify() in case of error in parameters.
if (opt.count("help")) {
cout << cmdline_options << "\n";
throw WantsToStop();
}
if (opt.count("version")) {
cout << "Version info not implemented.\n";
throw WantsToStop();
}
// Add cmd_or_file file options.
if (opt.count("optfile")) {
if (opt.count("verbose")) {
cout << "verbosity is " << opt.count("verbose") << ".\n";
cout << "Using options file " << opt["optfile"].as<string>() << ".\n";
}
ifstream ifs(opt["optfile"].as<string>().c_str());
if (!ifs)
{
throw MissingOptionsFileError();
}
else
{
po::store(parse_config_file(ifs, cmd_or_file), opt);
}
}
// Will throw exception if error in parameters.
po::notify(opt);
}
|
#include "StdAfx.h"
/*
Command line and options file option handling for ultracomm.
*/
UltracommOptions::UltracommOptions(const int& argc, char* argv[])
{
//string appName = boost::filesystem::basename(argv[0]);
// Command-line-only options.
po::options_description cmdonly("Ultracomm command-line-only options");
cmdonly.add_options()
("help,h", "print help message and stop")
("version", "print ultracomm version and stop")
("optfile,o", po::value<string>(), "parameter options file (see below)")
;
// Options allowed in options file or on command line.
po::options_description cmd_or_file("Ultracomm options for command line or options file");
cmd_or_file.add_options()
("address,a", po::value<string>()->required(), "ultrasonix ip address")
("output,O", po::value<string>()->required(), "base output name (including path)")
("b-depth", po::value<int>(), "b-depth")
("datatype", po::value<int>()->required(), "datatype")
("trigger_out", po::value<int>(), "trigger out")
("trigger_out_2", po::value<int>(), "trigger out 2")
("verbose,v", "display informational messages")
;
// Now combine into full set of command line options.
po::options_description cmdline_options;
cmdline_options.add(cmdonly).add(cmd_or_file);
// Read command line options into opt.
po::store(po::parse_command_line(argc, argv, cmdline_options), opt);
// This precedes po::notify() in case of error in parameters.
if (opt.count("help")) {
cout << cmdline_options << "\n";
throw WantsToStop();
}
if (opt.count("version")) {
cout << "Version info not implemented.\n";
throw WantsToStop();
}
// Add cmd_or_file file options.
if (opt.count("optfile")) {
if (opt.count("verbose")) {
cout << "verbosity is " << opt.count("verbose") << ".\n";
cout << "Using options file " << opt["optfile"].as<string>() << ".\n";
}
ifstream ifs(opt["optfile"].as<string>().c_str());
if (!ifs)
{
throw MissingOptionsFileError();
}
else
{
po::store(parse_config_file(ifs, cmd_or_file), opt);
}
}
// Will throw exception if error in parameters.
po::notify(opt);
}
|
Make datatype a required program parameter.
|
Make datatype a required program parameter.
|
C++
|
bsd-3-clause
|
rsprouse/ultracomm,rsprouse/ultracomm,rsprouse/ultracomm
|
70db3cf9b8ff9efd27325d82599ad4c60d0289d2
|
src/patches.cpp
|
src/patches.cpp
|
#include "patches.h"
#include <QFile>
#include <QDialog>
#include <QVBoxLayout>
#include <QComboBox>
#include <QLabel>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QtEndian>
#define PATCH_PATH ":patches/"
#define PATCH_EXTRA PATCH_PATH "maphacks-"
const QStringList extraDataPatches = {
PATCH_EXTRA "us0.ips",
PATCH_EXTRA "us1.ips",
PATCH_EXTRA "jp.ips",
PATCH_EXTRA "eu.ips",
PATCH_EXTRA "fc.ips",
PATCH_EXTRA "de.ips",
};
int getGameVersion(QWidget *parent) {
QDialog dlg(parent);
dlg.setWindowTitle(QWidget::tr("Select ROM Version"));
QVBoxLayout layout;
dlg.setLayout(&layout);
QComboBox combo;
combo.addItems({
QWidget::tr("United States PRG0"),
QWidget::tr("United States PRG1"),
QWidget::tr("Japan"),
QWidget::tr("Europe"),
QWidget::tr("Canada"),
QWidget::tr("Germany")
});
layout.addWidget(&combo);
layout.addWidget(new QLabel(QWidget::tr("Be sure to select the correct region for your ROM.\n"
"Applying a patch cannot be undone!")));
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout.addWidget(&buttons);
QObject::connect(&buttons, SIGNAL(accepted()), &dlg, SLOT(accept()));
QObject::connect(&buttons, SIGNAL(rejected()), &dlg, SLOT(reject()));
if (dlg.exec()) {
return combo.currentIndex();
}
return -1;
}
bool applyPatch(ROMFile &file, QString path) {
QFile patch(path);
if (!patch.open(QIODevice::ReadOnly)) {
QMessageBox::critical(0, QWidget::tr("Error Applying Patch"),
QWidget::tr("Unable to open %1.").arg(path),
QMessageBox::Ok);
return false;
}
// ideally the target file should already be open (since the main window
// will probably be made to handle any errors and allows the user to select
// a new file, leaving it open afterwards), but we'll handle it quickly here
// as well
if (!file.open(QIODevice::ReadWrite)) {
QMessageBox::critical(0, QWidget::tr("Error Applying Patch"),
QWidget::tr("Unable to open %1.").arg(file.fileName()),
QMessageBox::Ok);
return false;
}
patch.seek(5);
uchar buf[4] = {0};
uint32_t addr;
uint16_t size;
char rle;
while (true) {
buf[0] = 0;
patch.read((char*)buf+1, 3);
addr = qFromBigEndian<uint32_t>(buf);
if (addr == 0x454F46) break; // "EOF"
file.seek(addr);
patch.read((char*)buf, 2);
size = qFromBigEndian<uint16_t>(buf);
if (!size) { // RLE patch entry
patch.read((char*)buf, 2);
size = qFromBigEndian<uint16_t>(buf);
patch.read(&rle, 1);
for (uint i = 0; i < size; i++) {
file.write(&rle, 1);
}
} else {
file.write(patch.read(size));
}
}
QMessageBox::information(0, QWidget::tr("Apply Patch"),
QWidget::tr("Patch applied successfully!"),
QMessageBox::Ok);
patch.close();
file.close();
return true;
}
|
#include "patches.h"
#include <QFile>
#include <QDialog>
#include <QVBoxLayout>
#include <QComboBox>
#include <QLabel>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QtEndian>
#define PATCH_PATH ":patches/"
#define PATCH_EXTRA PATCH_PATH "maphacks-"
const QStringList extraDataPatches = {
PATCH_EXTRA "us0.ips",
PATCH_EXTRA "us1.ips",
PATCH_EXTRA "jp.ips",
PATCH_EXTRA "eu.ips",
PATCH_EXTRA "fc.ips",
PATCH_EXTRA "de.ips",
};
int getGameVersion(QWidget *parent) {
QDialog dlg(parent);
dlg.setWindowTitle(QWidget::tr("Select ROM Version"));
QVBoxLayout layout;
dlg.setLayout(&layout);
QComboBox combo;
combo.addItems({
QWidget::tr("United States PRG0"),
QWidget::tr("United States PRG1"),
QWidget::tr("Japan"),
QWidget::tr("Europe"),
QWidget::tr("Canada"),
QWidget::tr("Germany")
});
layout.addWidget(&combo);
layout.addWidget(new QLabel(QWidget::tr("Be sure to select the correct region for your ROM.\n"
"Applying a patch cannot be undone!")));
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout.addWidget(&buttons);
QObject::connect(&buttons, SIGNAL(accepted()), &dlg, SLOT(accept()));
QObject::connect(&buttons, SIGNAL(rejected()), &dlg, SLOT(reject()));
if (dlg.exec()) {
return combo.currentIndex();
}
return -1;
}
bool applyPatch(ROMFile &file, QString path) {
QFile patch(path);
if (!patch.open(QIODevice::ReadOnly)) {
QMessageBox::critical(0, QWidget::tr("Error Applying Patch"),
QWidget::tr("Unable to open %1.").arg(path),
QMessageBox::Ok);
return false;
}
// ideally the target file should already be open (since the main window
// will probably be made to handle any errors and allows the user to select
// a new file, leaving it open afterwards), but we'll handle it quickly here
// as well
if (!file.open(QIODevice::ReadWrite)) {
QMessageBox::critical(0, QWidget::tr("Error Applying Patch"),
QWidget::tr("Unable to open %1.").arg(file.fileName()),
QMessageBox::Ok);
return false;
}
patch.seek(5);
uchar buf[4] = {0};
uint32_t addr;
uint16_t size;
char rle;
while (true) {
buf[0] = 0;
if (patch.read((char*)buf+1, 3) < 0) goto error;
addr = qFromBigEndian<uint32_t>(buf);
if (addr == 0x454F46) break; // "EOF"
file.seek(addr);
if (patch.read((char*)buf, 2) < 0) goto error;
size = qFromBigEndian<uint16_t>(buf);
if (!size) { // RLE patch entry
if (patch.read((char*)buf, 2) < 0) goto error;
size = qFromBigEndian<uint16_t>(buf);
if (patch.read(&rle, 1) < 0) goto error;
for (uint i = 0; i < size; i++) {
file.write(&rle, 1);
}
} else {
file.write(patch.read(size));
}
}
QMessageBox::information(0, QWidget::tr("Apply Patch"),
QWidget::tr("Patch applied successfully!"),
QMessageBox::Ok);
patch.close();
file.close();
return true;
error:
QMessageBox::critical(0, QWidget::tr("Error Applying Patch"),
QWidget::tr("Applying patch failed. The patch appears to be corrupt."),
QMessageBox::Ok);
patch.close();
file.close();
return false;
}
|
handle unexpected EOF in ips patches
|
handle unexpected EOF in ips patches
(even though all used patches are internal and unlikely to be corrupt)
|
C++
|
mit
|
devinacker/kale,devinacker/kale
|
a4bc900d67e449ba054a15b42679689b127dcdbf
|
src/pathbar.cpp
|
src/pathbar.cpp
|
/*
* Copyright (C) 2016 Hong Jen Yee (PCMan) <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "pathbar.h"
#include "pathbar_p.h"
#include <QToolButton>
#include <QScrollArea>
#include <QScrollBar>
#include <QHBoxLayout>
#include <QResizeEvent>
#include <QContextMenuEvent>
#include <QMenu>
#include <QClipboard>
#include <QApplication>
#include <QTimer>
#include <QDebug>
#include "pathedit.h"
namespace Fm {
PathBar::PathBar(QWidget* parent):
QWidget(parent),
tempPathEdit_(nullptr) {
QHBoxLayout* topLayout = new QHBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
topLayout->setSpacing(0);
bool rtl(layoutDirection() == Qt::RightToLeft);
// the arrow button used to scroll to start of the path
scrollToStart_ = new QToolButton(this);
scrollToStart_->setArrowType(rtl ? Qt::RightArrow : Qt::LeftArrow);
scrollToStart_->setAutoRepeat(true);
scrollToStart_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
connect(scrollToStart_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked);
topLayout->addWidget(scrollToStart_);
// there might be too many buttons when the path is long, so make it scrollable.
scrollArea_ = new QScrollArea(this);
scrollArea_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
scrollArea_->setFrameShape(QFrame::NoFrame);
scrollArea_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
scrollArea_->verticalScrollBar()->setDisabled(true);
connect(scrollArea_->horizontalScrollBar(), &QAbstractSlider::valueChanged, this, &PathBar::setArrowEnabledState);
topLayout->addWidget(scrollArea_, 1); // stretch factor=1, make it expandable
// the arrow button used to scroll to end of the path
scrollToEnd_ = new QToolButton(this);
scrollToEnd_->setArrowType(rtl ? Qt::LeftArrow : Qt::RightArrow);
scrollToEnd_->setAutoRepeat(true);
scrollToEnd_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
connect(scrollToEnd_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked);
topLayout->addWidget(scrollToEnd_);
// container widget of the path buttons
buttonsWidget_ = new QWidget(this);
buttonsWidget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
buttonsLayout_ = new QHBoxLayout(buttonsWidget_);
buttonsLayout_->setContentsMargins(0, 0, 0, 0);
buttonsLayout_->setSpacing(0);
buttonsLayout_->setSizeConstraint(QLayout::SetFixedSize); // required when added to scroll area according to QScrollArea doc.
scrollArea_->setWidget(buttonsWidget_); // make the buttons widget scrollable if the path is too long
}
void PathBar::resizeEvent(QResizeEvent* event) {
QWidget::resizeEvent(event);
updateScrollButtonVisibility();
}
void PathBar::wheelEvent(QWheelEvent* event) {
QWidget::wheelEvent(event);
QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction;
int vDelta = event->angleDelta().y();
if(vDelta > 0) {
if(scrollToStart_->isEnabled()) {
action = QAbstractSlider::SliderSingleStepSub;
}
}
else if(vDelta < 0) {
if(scrollToEnd_->isEnabled()) {
action = QAbstractSlider::SliderSingleStepAdd;
}
}
scrollArea_->horizontalScrollBar()->triggerAction(action);
}
void PathBar::mousePressEvent(QMouseEvent* event) {
QWidget::mousePressEvent(event);
if(event->button() == Qt::LeftButton) {
openEditor();
}
else if(event->button() == Qt::MiddleButton) {
PathButton* btn = qobject_cast<PathButton*>(childAt(event->x(), event->y()));
if(btn != nullptr) {
scrollArea_->ensureWidgetVisible(btn,
1); // a harmless compensation for a miscalculation in Qt
Q_EMIT middleClickChdir(pathForButton(btn));
}
}
}
void PathBar::contextMenuEvent(QContextMenuEvent* event) {
QMenu* menu = new QMenu(this);
connect(menu, &QMenu::aboutToHide, menu, &QMenu::deleteLater);
QAction* action = menu->addAction(tr("&Edit Path"));
connect(action, &QAction::triggered, this, &PathBar::openEditor);
action = menu->addAction(tr("&Copy Path"));
connect(action, &QAction::triggered, this, &PathBar::copyPath);
menu->popup(mapToGlobal(event->pos()));
}
void PathBar::updateScrollButtonVisibility() {
// Wait for the horizontal scrollbar to be completely shaped.
// Without this, the enabled state of arrow buttons might be
// wrong when the pathbar is created for the first time.
QTimer::singleShot(0, this, SLOT(setScrollButtonVisibility()));
}
void PathBar::setScrollButtonVisibility() {
bool showScrollers;
if(tempPathEdit_ != nullptr) {
showScrollers = false;
}
else {
showScrollers = (buttonsLayout_->sizeHint().width() > width());
}
scrollToStart_->setVisible(showScrollers);
scrollToEnd_->setVisible(showScrollers);
if(showScrollers) {
QScrollBar* sb = scrollArea_->horizontalScrollBar();
int value = sb->value();
scrollToStart_->setEnabled(value != sb->minimum());
scrollToEnd_->setEnabled(value != sb->maximum());
}
}
Fm::FilePath PathBar::pathForButton(PathButton* btn) {
std::string fullPath;
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
for(int i = 0; i < buttonCount; ++i) {
if(!fullPath.empty() && fullPath.back() != '/') {
fullPath += '/';
}
PathButton* elem = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget());
fullPath += elem->name();
if(elem == btn)
break;
}
return Fm::FilePath::fromPathStr(fullPath.c_str());
}
void PathBar::onButtonToggled(bool checked) {
if(checked) {
PathButton* btn = static_cast<PathButton*>(sender());
currentPath_ = pathForButton(btn);
Q_EMIT chdir(currentPath_);
// since scrolling to the toggled buton will happen correctly only when the
// layout is updated and because the update is disabled on creating buttons
// in setPath(), the update status can be used as a sign to know when to wait
if(updatesEnabled()) {
scrollArea_->ensureWidgetVisible(btn, 1);
}
else {
QTimer::singleShot(0, this, SLOT(ensureToggledVisible()));
}
}
}
void PathBar::ensureToggledVisible() {
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
for(int i = buttonCount - 1; i >= 0; --i) {
if(auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget())) {
if(btn->isChecked()) {
scrollArea_->ensureWidgetVisible(btn, 1);
return;
}
}
}
}
void PathBar::onScrollButtonClicked() {
QToolButton* btn = static_cast<QToolButton*>(sender());
QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction;
if(btn == scrollToEnd_) {
action = QAbstractSlider::SliderSingleStepAdd;
}
else if(btn == scrollToStart_) {
action = QAbstractSlider::SliderSingleStepSub;
}
scrollArea_->horizontalScrollBar()->triggerAction(action);
}
void PathBar::setPath(Fm::FilePath path) {
if(currentPath_ == path) { // same path, do nothing
return;
}
auto oldPath = std::move(currentPath_);
currentPath_ = std::move(path);
// check if we already have a button for this path
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
if(oldPath && currentPath_.isPrefixOf(oldPath)) {
for(int i = buttonCount - 1; i >= 0; --i) {
auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget());
if(pathForButton(btn) == currentPath_) {
btn->setChecked(true); // toggle the button
/* we don't need to emit chdir signal here since later
* toggled signal will be triggered on the button, which
* in turns emit chdir. */
return;
}
}
}
/* FIXME: if the new path is the subdir of our full path, actually
* we can append several new buttons rather than re-create
* all of the buttons. This can reduce flickers. */
setUpdatesEnabled(false);
// we do not have the path in the buttons list
// destroy existing path element buttons and the spacer
QLayoutItem* item;
while((item = buttonsLayout_->takeAt(0)) != nullptr) {
delete item->widget();
delete item;
}
// create new buttons for the new path
auto btnPath = currentPath_;
while(btnPath) {
Fm::CStrPtr name;
Fm::CStrPtr displayName;
auto parent = btnPath.parent();
// FIXME: some buggy uri types, such as menu://, fail to return NULL when there is no parent path.
// Instead, the path itself is returned. So we check if the parent path is the same as current path.
auto isRoot = !parent.isValid() || parent == btnPath;
if(isRoot) {
displayName = btnPath.displayName();
name = btnPath.toString();
}
else {
name = btnPath.baseName();
}
auto btn = new PathButton(name.get(), displayName ? displayName.get() : name.get(), isRoot, buttonsWidget_);
btn->show();
connect(btn, &QAbstractButton::toggled, this, &PathBar::onButtonToggled);
buttonsLayout_->insertWidget(0, btn);
if(isRoot) { // this is the root element of the path
break;
}
btnPath = parent;
}
buttonsLayout_->addStretch(1); // add a spacer at the tail of the buttons
// we don't want to scroll vertically. make the scroll area fit the height of the buttons
// FIXME: this is a little bit hackish :-(
scrollArea_->setFixedHeight(buttonsLayout_->sizeHint().height());
updateScrollButtonVisibility();
// to guarantee that the button will be scrolled to correctly,
// it should be toggled only after the layout update starts above
buttonCount = buttonsLayout_->count() - 1;
if(buttonCount > 0) {
PathButton* lastBtn = static_cast<PathButton*>(buttonsLayout_->itemAt(buttonCount - 1)->widget());
// we don't have to emit the chdir signal since the "onButtonToggled()" slot will be triggered by this.
lastBtn->setChecked(true);
}
setUpdatesEnabled(true);
}
void PathBar::openEditor() {
if(tempPathEdit_ == nullptr) {
tempPathEdit_ = new PathEdit(this);
delete layout()->replaceWidget(scrollArea_, tempPathEdit_, Qt::FindDirectChildrenOnly);
scrollArea_->hide();
scrollToStart_->setVisible(false);
scrollToEnd_->setVisible(false);
tempPathEdit_->setText(currentPath_.toString().get());
connect(tempPathEdit_, &PathEdit::returnPressed, this, &PathBar::onReturnPressed);
connect(tempPathEdit_, &PathEdit::editingFinished, this, &PathBar::closeEditor);
}
tempPathEdit_->setFocus();
tempPathEdit_->selectAll();
}
void PathBar::closeEditor() {
if(tempPathEdit_ == nullptr) {
return;
}
// If a menu has popped up synchronously (with QMenu::exec), the path buttons may be drawn
// but the path-edit may not disappear until the menu is closed. So, we hide it here.
tempPathEdit_->setVisible(false);
delete layout()->replaceWidget(tempPathEdit_, scrollArea_, Qt::FindDirectChildrenOnly);
scrollArea_->show();
if(buttonsLayout_->sizeHint().width() > width()) {
scrollToStart_->setVisible(true);
scrollToEnd_->setVisible(true);
}
tempPathEdit_->deleteLater();
tempPathEdit_ = nullptr;
updateScrollButtonVisibility();
Q_EMIT editingFinished();
}
void PathBar::copyPath() {
QApplication::clipboard()->setText(currentPath_.toString().get());
}
void PathBar::onReturnPressed() {
QByteArray pathStr = tempPathEdit_->text().toLocal8Bit();
setPath(Fm::FilePath::fromPathStr(pathStr.constData()));
}
void PathBar::setArrowEnabledState(int value) {
if(buttonsLayout_->sizeHint().width() > width()) {
QScrollBar* sb = scrollArea_->horizontalScrollBar();
scrollToStart_->setEnabled(value != sb->minimum());
scrollToEnd_->setEnabled(value != sb->maximum());
}
}
} // namespace Fm
|
/*
* Copyright (C) 2016 Hong Jen Yee (PCMan) <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "pathbar.h"
#include "pathbar_p.h"
#include <QToolButton>
#include <QScrollArea>
#include <QScrollBar>
#include <QHBoxLayout>
#include <QResizeEvent>
#include <QContextMenuEvent>
#include <QMenu>
#include <QClipboard>
#include <QApplication>
#include <QTimer>
#include <QDebug>
#include "pathedit.h"
namespace Fm {
PathBar::PathBar(QWidget* parent):
QWidget(parent),
tempPathEdit_(nullptr) {
QHBoxLayout* topLayout = new QHBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
topLayout->setSpacing(0);
bool rtl(layoutDirection() == Qt::RightToLeft);
// the arrow button used to scroll to start of the path
scrollToStart_ = new QToolButton(this);
scrollToStart_->setArrowType(rtl ? Qt::RightArrow : Qt::LeftArrow);
scrollToStart_->setAutoRepeat(true);
scrollToStart_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
connect(scrollToStart_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked);
topLayout->addWidget(scrollToStart_);
// there might be too many buttons when the path is long, so make it scrollable.
scrollArea_ = new QScrollArea(this);
scrollArea_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
scrollArea_->setFrameShape(QFrame::NoFrame);
scrollArea_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea_->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
scrollArea_->verticalScrollBar()->setDisabled(true);
connect(scrollArea_->horizontalScrollBar(), &QAbstractSlider::valueChanged, this, &PathBar::setArrowEnabledState);
topLayout->addWidget(scrollArea_, 1); // stretch factor=1, make it expandable
// the arrow button used to scroll to end of the path
scrollToEnd_ = new QToolButton(this);
scrollToEnd_->setArrowType(rtl ? Qt::LeftArrow : Qt::RightArrow);
scrollToEnd_->setAutoRepeat(true);
scrollToEnd_->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
connect(scrollToEnd_, &QToolButton::clicked, this, &PathBar::onScrollButtonClicked);
topLayout->addWidget(scrollToEnd_);
// container widget of the path buttons
buttonsWidget_ = new QWidget(this);
buttonsWidget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
buttonsLayout_ = new QHBoxLayout(buttonsWidget_);
buttonsLayout_->setContentsMargins(0, 0, 0, 0);
buttonsLayout_->setSpacing(0);
buttonsLayout_->setSizeConstraint(QLayout::SetFixedSize); // required when added to scroll area according to QScrollArea doc.
scrollArea_->setWidget(buttonsWidget_); // make the buttons widget scrollable if the path is too long
}
void PathBar::resizeEvent(QResizeEvent* event) {
QWidget::resizeEvent(event);
updateScrollButtonVisibility();
}
void PathBar::wheelEvent(QWheelEvent* event) {
QWidget::wheelEvent(event);
QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction;
int vDelta = event->angleDelta().y();
if(vDelta > 0) {
if(scrollToStart_->isEnabled()) {
action = QAbstractSlider::SliderSingleStepSub;
}
}
else if(vDelta < 0) {
if(scrollToEnd_->isEnabled()) {
action = QAbstractSlider::SliderSingleStepAdd;
}
}
scrollArea_->horizontalScrollBar()->triggerAction(action);
}
void PathBar::mousePressEvent(QMouseEvent* event) {
QWidget::mousePressEvent(event);
if(event->button() == Qt::LeftButton) {
openEditor();
}
else if(event->button() == Qt::MiddleButton) {
PathButton* btn = qobject_cast<PathButton*>(childAt(event->x(), event->y()));
if(btn != nullptr) {
scrollArea_->ensureWidgetVisible(btn,
1); // a harmless compensation for a miscalculation in Qt
Q_EMIT middleClickChdir(pathForButton(btn));
}
}
}
void PathBar::contextMenuEvent(QContextMenuEvent* event) {
QMenu* menu = new QMenu(this);
connect(menu, &QMenu::aboutToHide, menu, &QMenu::deleteLater);
QAction* action = menu->addAction(tr("&Edit Path"));
connect(action, &QAction::triggered, this, &PathBar::openEditor);
action = menu->addAction(tr("&Copy Path"));
connect(action, &QAction::triggered, this, &PathBar::copyPath);
menu->popup(mapToGlobal(event->pos()));
}
void PathBar::updateScrollButtonVisibility() {
// Wait for the horizontal scrollbar to be completely shaped.
// Without this, the enabled state of arrow buttons might be
// wrong when the pathbar is created for the first time.
QTimer::singleShot(0, this, SLOT(setScrollButtonVisibility()));
}
void PathBar::setScrollButtonVisibility() {
bool showScrollers;
if(tempPathEdit_ != nullptr) {
showScrollers = false;
}
else {
showScrollers = (buttonsLayout_->sizeHint().width() > width());
}
scrollToStart_->setVisible(showScrollers);
scrollToEnd_->setVisible(showScrollers);
if(showScrollers) {
QScrollBar* sb = scrollArea_->horizontalScrollBar();
int value = sb->value();
scrollToStart_->setEnabled(value != sb->minimum());
scrollToEnd_->setEnabled(value != sb->maximum());
}
}
Fm::FilePath PathBar::pathForButton(PathButton* btn) {
std::string fullPath;
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
for(int i = 0; i < buttonCount; ++i) {
if(!fullPath.empty() && fullPath.back() != '/') {
fullPath += '/';
}
PathButton* elem = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget());
fullPath += elem->name();
if(elem == btn)
break;
}
return Fm::FilePath::fromPathStr(fullPath.c_str());
}
void PathBar::onButtonToggled(bool checked) {
if(checked) {
PathButton* btn = static_cast<PathButton*>(sender());
currentPath_ = pathForButton(btn);
Q_EMIT chdir(currentPath_);
// since scrolling to the toggled buton will happen correctly only when the
// layout is updated and because the update is disabled on creating buttons
// in setPath(), the update status can be used as a sign to know when to wait
if(updatesEnabled()) {
scrollArea_->ensureWidgetVisible(btn, 1);
}
else {
QTimer::singleShot(0, this, SLOT(ensureToggledVisible()));
}
}
}
void PathBar::ensureToggledVisible() {
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
for(int i = buttonCount - 1; i >= 0; --i) {
if(auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget())) {
if(btn->isChecked()) {
scrollArea_->ensureWidgetVisible(btn, 1);
return;
}
}
}
}
void PathBar::onScrollButtonClicked() {
QToolButton* btn = static_cast<QToolButton*>(sender());
QAbstractSlider::SliderAction action = QAbstractSlider::SliderNoAction;
if(btn == scrollToEnd_) {
action = QAbstractSlider::SliderSingleStepAdd;
}
else if(btn == scrollToStart_) {
action = QAbstractSlider::SliderSingleStepSub;
}
scrollArea_->horizontalScrollBar()->triggerAction(action);
}
void PathBar::setPath(Fm::FilePath path) {
if(currentPath_ == path) { // same path, do nothing
return;
}
auto oldPath = std::move(currentPath_);
currentPath_ = std::move(path);
// check if we already have a button for this path
int buttonCount = buttonsLayout_->count() - 1; // the last item is a spacer
if(oldPath && currentPath_.isPrefixOf(oldPath)) {
for(int i = buttonCount - 1; i >= 0; --i) {
auto btn = static_cast<PathButton*>(buttonsLayout_->itemAt(i)->widget());
if(pathForButton(btn) == currentPath_) {
btn->setChecked(true); // toggle the button
/* we don't need to emit chdir signal here since later
* toggled signal will be triggered on the button, which
* in turns emit chdir. */
return;
}
}
}
/* FIXME: if the new path is the subdir of our full path, actually
* we can append several new buttons rather than re-create
* all of the buttons. This can reduce flickers. */
setUpdatesEnabled(false);
// we do not have the path in the buttons list
// destroy existing path element buttons and the spacer
QLayoutItem* item;
while((item = buttonsLayout_->takeAt(0)) != nullptr) {
delete item->widget();
delete item;
}
// create new buttons for the new path
auto btnPath = currentPath_;
while(btnPath) {
Fm::CStrPtr name;
Fm::CStrPtr displayName;
auto parent = btnPath.parent();
// FIXME: some buggy uri types, such as menu://, fail to return NULL when there is no parent path.
// Instead, the path itself is returned. So we check if the parent path is the same as current path.
auto isRoot = !parent.isValid() || parent == btnPath;
if(isRoot) {
displayName = btnPath.displayName();
name = btnPath.toString();
}
else {
name = btnPath.baseName();
}
auto btn = new PathButton(name.get(), displayName ? displayName.get() : name.get(), isRoot, buttonsWidget_);
btn->show();
connect(btn, &QAbstractButton::toggled, this, &PathBar::onButtonToggled);
buttonsLayout_->insertWidget(0, btn);
if(isRoot) { // this is the root element of the path
break;
}
btnPath = parent;
}
buttonsLayout_->addStretch(1); // add a spacer at the tail of the buttons
// we don't want to scroll vertically. make the scroll area fit the height of the buttons
// FIXME: this is a little bit hackish :-(
scrollArea_->setFixedHeight(buttonsLayout_->sizeHint().height());
updateScrollButtonVisibility();
// to guarantee that the button will be scrolled to correctly,
// it should be toggled only after the layout update starts above
buttonCount = buttonsLayout_->count() - 1;
if(buttonCount > 0) {
PathButton* lastBtn = static_cast<PathButton*>(buttonsLayout_->itemAt(buttonCount - 1)->widget());
// we don't have to emit the chdir signal since the "onButtonToggled()" slot will be triggered by this.
lastBtn->setChecked(true);
}
setUpdatesEnabled(true);
}
void PathBar::openEditor() {
if(tempPathEdit_ == nullptr) {
tempPathEdit_ = new PathEdit(this);
delete layout()->replaceWidget(scrollArea_, tempPathEdit_, Qt::FindDirectChildrenOnly);
scrollArea_->hide();
scrollToStart_->setVisible(false);
scrollToEnd_->setVisible(false);
tempPathEdit_->setText(currentPath_.toString().get());
connect(tempPathEdit_, &PathEdit::returnPressed, this, &PathBar::onReturnPressed);
connect(tempPathEdit_, &PathEdit::editingFinished, this, &PathBar::closeEditor);
}
tempPathEdit_->selectAll();
QApplication::clipboard()->setText(tempPathEdit_->text(), QClipboard::Selection);
QTimer::singleShot(0, tempPathEdit_, SLOT(setFocus()));
}
void PathBar::closeEditor() {
if(tempPathEdit_ == nullptr) {
return;
}
// If a menu has popped up synchronously (with QMenu::exec), the path buttons may be drawn
// but the path-edit may not disappear until the menu is closed. So, we hide it here.
tempPathEdit_->setVisible(false);
delete layout()->replaceWidget(tempPathEdit_, scrollArea_, Qt::FindDirectChildrenOnly);
scrollArea_->show();
if(buttonsLayout_->sizeHint().width() > width()) {
scrollToStart_->setVisible(true);
scrollToEnd_->setVisible(true);
}
tempPathEdit_->deleteLater();
tempPathEdit_ = nullptr;
updateScrollButtonVisibility();
Q_EMIT editingFinished();
}
void PathBar::copyPath() {
QApplication::clipboard()->setText(currentPath_.toString().get());
}
void PathBar::onReturnPressed() {
QByteArray pathStr = tempPathEdit_->text().toLocal8Bit();
setPath(Fm::FilePath::fromPathStr(pathStr.constData()));
}
void PathBar::setArrowEnabledState(int value) {
if(buttonsLayout_->sizeHint().width() > width()) {
QScrollBar* sb = scrollArea_->horizontalScrollBar();
scrollToStart_->setEnabled(value != sb->minimum());
scrollToEnd_->setEnabled(value != sb->maximum());
}
}
} // namespace Fm
|
Copy selected pathbar text to selection clipboard
|
Copy selected pathbar text to selection clipboard
Closes https://github.com/lxde/pcmanfm-qt/issues/604
Also use `QTimer::singleSho()` to focus the line-edit because otherwise, it might not have time to get focused if the main window didn't have focus (this can happen with some window managers like Enlightenment's).
|
C++
|
lgpl-2.1
|
lxde/libfm-qt,lxde/libfm-qt
|
5630e80b1d0e83708ca5d6fa84d5647051dedcbb
|
src/reql/btree.hpp
|
src/reql/btree.hpp
|
/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#ifndef REQL_REQL_BTREE_HPP_
#define REQL_REQL_BTREE_HPP_
#include "./reql/decode.hpp"
#include "./reql/parser.hpp"
#include "./reql/protocol.hpp"
#include "./reql/query.hpp"
#include "./reql/response.hpp"
#include "./reql/types.hpp"
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
namespace _ReQL {
template <class result_t, class str_t>
class BTree_t {
public:
BTree_t() {}
BTree_t(const str_t &addr, const str_t &port, const str_t &auth) :
p_protocol(addr, port, auth, [this](Response_t<str_t, Protocol_t<str_t> > &&response) {
p_root->push(std::move(response));
}) {}
bool isOpen() const {
return p_protocol.isOpen();
}
template <class query_t>
void run(const query_t &query, std::function<void(result_t &&result)> func) {
Query_t<str_t> q(p_next_token++, query);
p_protocol << q;
create(q.token(), func);
}
template <class kwargs_t, class query_t>
void run(const query_t &query, const kwargs_t &kwargs, std::function<void(result_t &&result)> func) {
Query_t<str_t> q(p_next_token++, query, kwargs);
p_protocol << q;
create(q.token(), func);
}
template <class kwargs_t, class query_t>
void noReply(const query_t &query, const kwargs_t &kwargs) {
Query_t<str_t> q(p_next_token++, query, kwargs);
p_protocol << q;
}
void noReplyWait() {
Query_t<str_t> query(p_next_token++, REQL_NOREPLY_WAIT);
p_protocol << query;
create(query.token());
}
void stop(ReQL_Token token) {
p_protocol.stop(token);
p_root.close(token);
}
private:
class BNode_t {
public:
enum Response_e {
REQL_CLIENT_ERROR = 16,
REQL_COMPILE_ERROR = 17,
REQL_RUNTIME_ERROR = 18,
REQL_SUCCESS_ATOM = 1,
REQL_SUCCESS_PARTIAL = 3,
REQL_SUCCESS_SEQUENCE = 2,
REQL_WAIT_COMPLETE = 4
};
BNode_t(const ReQL_Token &key, std::function<void(result_t &&result)> &func) : p_cur([func](Response_t<str_t, Protocol_t<str_t> > &&response) {
Parser_t<result_t> parser;
decode(response.json(), parser);
switch (parser.r_type()) {
case REQL_SUCCESS_ATOM:
case REQL_SUCCESS_SEQUENCE:
case REQL_WAIT_COMPLETE: {
break;
}
case REQL_SUCCESS_PARTIAL: {
response.next();
break;
}
case REQL_CLIENT_ERROR:
case REQL_COMPILE_ERROR:
case REQL_RUNTIME_ERROR:
default: {
}
}
func(std::move(parser.get()));
}), p_key(key) {}
void create(const ReQL_Token &key, std::function<void(result_t &&result)> &func) {
if (key == p_key) {
return;
}
if (key < p_key) {
if (p_left.get()) {
return p_left->create(key, func);
}
p_left.reset(new BNode_t(key, func));
return;
}
if (p_right.get()) {
return p_right->create(key, func);
}
p_right.reset(new BNode_t(key, func));
}
void push(Response_t<str_t, Protocol_t<str_t> > &&response) {
if (response == p_key) {
p_cur(std::move(response));
return;
}
if (response < p_key) {
return p_left->push(std::move(response));
}
return p_right->push(std::move(response));
}
void close(const ReQL_Token &key) {
if (key == p_key) {
return p_cur.close();
}
if (key < p_key) {
return p_left->close(key);
}
return p_right->close(key);
}
private:
std::function<void(Response_t<str_t, Protocol_t<str_t> > &&)> p_cur;
ReQL_Token p_key;
std::unique_ptr<BNode_t> p_left;
std::unique_ptr<BNode_t> p_right;
};
void create(const ReQL_Token &key, std::function<void(result_t &&result)> func) {
std::lock_guard<std::mutex> lock(p_mutex);
if (!p_root.get()) {
p_root.reset(new BNode_t(key, func));
} else {
p_root->create(key, func);
}
}
std::mutex p_mutex;
std::atomic<ReQL_Token> p_next_token;
Protocol_t<str_t> p_protocol;
std::unique_ptr<BNode_t> p_root;
std::thread p_thread;
};
} // namespace _ReQL
#endif // REQL_REQL_BTREE_HPP_
|
/*
Copyright 2014-2015 Adam Grandquist
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.
*/
/**
* @author Adam Grandquist
* @copyright Apache
*/
#ifndef REQL_REQL_BTREE_HPP_
#define REQL_REQL_BTREE_HPP_
#include "./reql/decode.hpp"
#include "./reql/parser.hpp"
#include "./reql/protocol.hpp"
#include "./reql/query.hpp"
#include "./reql/response.hpp"
#include "./reql/types.hpp"
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
namespace _ReQL {
template <class result_t, class str_t>
class BTree_t {
public:
BTree_t() {}
BTree_t(const str_t &addr, const str_t &port, const str_t &auth) :
p_protocol(addr, port, auth, [this](Response_t<str_t, Protocol_t<str_t> > &&response) {
p_root->push(std::move(response));
}) {}
bool isOpen() const {
return p_protocol.isOpen();
}
template <class query_t>
void run(const query_t &query, std::function<void(result_t &&result)> func) {
Query_t<str_t> q(p_next_token++, query);
p_protocol << q;
create(q.token(), func);
}
template <class kwargs_t, class query_t>
void run(const query_t &query, const kwargs_t &kwargs, std::function<void(result_t &&result)> func) {
Query_t<str_t> q(p_next_token++, query, kwargs);
p_protocol << q;
create(q.token(), func);
}
template <class kwargs_t, class query_t>
void noReply(const query_t &query, const kwargs_t &kwargs) {
Query_t<str_t> q(p_next_token++, query, kwargs);
p_protocol << q;
}
void noReplyWait() {
Query_t<str_t> query(p_next_token++, REQL_NOREPLY_WAIT);
p_protocol << query;
create(query.token());
}
void stop(ReQL_Token token) {
p_protocol.stop(token);
p_root.close(token);
}
private:
class BNode_t {
public:
enum Response_e {
CLIENT_ERROR = 16,
COMPILE_ERROR = 17,
RUNTIME_ERROR = 18,
SERVER_INFO = 5,
SUCCESS_ATOM = 1,
SUCCESS_PARTIAL = 3,
SUCCESS_SEQUENCE = 2,
WAIT_COMPLETE = 4
};
BNode_t(const ReQL_Token &key, std::function<void(result_t &&result)> &func) : p_cur([func](Response_t<str_t, Protocol_t<str_t> > &&response) {
Parser_t<result_t> parser;
decode(response.json(), parser);
switch (parser.r_type()) {
case SUCCESS_ATOM:
case SERVER_INFO: {
func(std::move(parser.get()[0]));
break;
}
case SUCCESS_PARTIAL: response.next(); [[clang::fallthrough]];
case SUCCESS_SEQUENCE: {
for (auto &&elem : parser.get()) {
func(std::move(elem));
}
break;
}
case WAIT_COMPLETE: {
func(result_t());
break;
}
case CLIENT_ERROR:
case COMPILE_ERROR:
case RUNTIME_ERROR: {
func(result_t(parser.get()));
break;
}
default: {
}
}
}), p_key(key) {}
void create(const ReQL_Token &key, std::function<void(result_t &&result)> &func) {
if (key == p_key) {
return;
}
if (key < p_key) {
if (p_left.get()) {
return p_left->create(key, func);
}
p_left.reset(new BNode_t(key, func));
return;
}
if (p_right.get()) {
return p_right->create(key, func);
}
p_right.reset(new BNode_t(key, func));
}
void push(Response_t<str_t, Protocol_t<str_t> > &&response) {
if (response == p_key) {
p_cur(std::move(response));
return;
}
if (response < p_key) {
return p_left->push(std::move(response));
}
return p_right->push(std::move(response));
}
void close(const ReQL_Token &key) {
if (key == p_key) {
return p_cur.close();
}
if (key < p_key) {
return p_left->close(key);
}
return p_right->close(key);
}
private:
std::function<void(Response_t<str_t, Protocol_t<str_t> > &&)> p_cur;
ReQL_Token p_key;
std::unique_ptr<BNode_t> p_left;
std::unique_ptr<BNode_t> p_right;
};
void create(const ReQL_Token &key, std::function<void(result_t &&result)> func) {
std::lock_guard<std::mutex> lock(p_mutex);
if (!p_root.get()) {
p_root.reset(new BNode_t(key, func));
} else {
p_root->create(key, func);
}
}
std::mutex p_mutex;
std::atomic<ReQL_Token> p_next_token;
Protocol_t<str_t> p_protocol;
std::unique_ptr<BNode_t> p_root;
std::thread p_thread;
};
} // namespace _ReQL
#endif // REQL_REQL_BTREE_HPP_
|
Add server info and flatten sequences.
|
Add server info and flatten sequences.
|
C++
|
apache-2.0
|
grandquista/ReQL-Core,grandquista/ReQL-Core,grandquista/ReQL-Core,grandquista/ReQL-Core
|
116c16e00f16115a1c2a1c8de2984ee4a47d9deb
|
src/sendwindow.hpp
|
src/sendwindow.hpp
|
// Copyright 2016 Peter Georg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! @file sendwindow.hpp
//! @brief Public interface for SendWindow.
//!
//! @author Peter Georg
#ifndef pMR_SENDWINDOW_H
#define pMR_SENDWINDOW_H
#include <cstdint>
#include "config.hpp"
#include "sendmemorywindow.hpp"
#include "window.hpp"
#include "misc/thread.hpp"
#include "misc/numeric.hpp"
#include "misc/type.hpp"
namespace pMR
{
//! @brief Send Window.
template<typename T>
class SendWindow : public Window<T>
{
public:
//! @brief Window for data to send to target.
//! @details Creates a SendWindow for specified connection. Sends
//! count elements T, stored in contigious memory region
//! buffer points to, to target.
//! @param connection Connection to associate Window with.
//! @param buffer Pointer to memory region used as send buffer.
//! @param count Number of elements of type T in send buffer.
SendWindow(Connection const &connection,
T *buffer, std::uint32_t const count);
//! @brief Window for data to send to target.
//! @details Creates a SendWindow for specified connection. Sends
//! count elements T, stored in internal buffer, to target.
//! @param connection Connection to associate Window with.
//! @param count Number of elements of type T in send buffer.
SendWindow(Connection const &connection, std::uint32_t const count);
SendWindow(const SendWindow&) = delete;
SendWindow(SendWindow&&) = default;
SendWindow& operator=(const SendWindow&) = delete;
SendWindow& operator=(SendWindow&&) = default;
~SendWindow();
//! @brief Initialize a send routine.
//! @note Send buffer associated with this send window may still
//! be accessed - read and write.
//! @warning Any outstanding synchronization or previously
//! initiated send routine, associated with the same connection,
//! has to be finished before initializing a send routine.
//! @note Receive and send routines associated with the same
//! connection may be initialized simultaneously.
void init();
//! @brief Post previously initialized send routine.
//! @warning Send buffer associated with this send window may be
//! accessed read only as soon as send routine has been posted.
//! @note Depending on the used provider, this routine might be
//! blocking.
void post();
//! @brief Wait for previously posted send routine to finish.
//! @note Write access to send buffer is allowed again after wait.
//! @note Blocking routine.
void wait();
//! @brief Copy data to internal buffer.
//! @details Copies data from storage - inputIt iterator points to -
//! to internal buffer starting at offset with bounds checking.
//! @param inputIt Iterator to source.
//! @param offset Offset for the internal buffer.
//! @param count Number of elements to copy.
template<class Iterator>
void insert(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count);
//! @brief Copy data to internal buffer.
//! @details Fills the internal buffer - starting at the beginning -
//! with data pointed to by inputIt.
//! @warning The container inputIt points to must be at least of the
//! same size as the internal buffer.
//! @param inputIt Iterator to source.
template<class Iterator>
void insert(Iterator inputIt);
//! @brief Multithreaded copy data to internal buffer.
//! @details Copies data from storage - inputIt iterator points to -
//! to internal buffer starting at offset with bounds checking.
//! The copy operation is shared among all threadCount threads
//! calling the function.
//! @warning threadID has to be in range [0, threadCount).
//! @warning The function has to be called with every threadID in
//! the range [0, threadCount).
//! @warning inputIt must be of type random access iterator.
//! @param inputIt Iterator to source.
//! @param offset Offset for the internal buffer.
//! @param count Number of elements to copy.
//! @param threadID ID of the current Thread.
//! @param threadCount Number of threads calling the function.
template<class Iterator>
void insertMT(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count,
int const threadID, int const threadCount);
//! @brief Multithreaded copy data to internal buffer.
//! @details Fills the internal buffer - starting at the beginning -
//! with data pointed to by inputIt. The copy operation is
//! shared among all threadCount threads calling the function.
//! @warning The container inputIt points to must be at least of the
//! same size as the internal buffer.
//! @warning threadID has to be in range [0, threadCount).
//! @warning The function has to be called with every threadID in
//! the range [0, threadCount).
//! @warning inputIt must be of type random access iterator.
//! @param inputIt Iterator to source.
//! @param threadID ID of the current Thread.
//! @param threadCount Number of threads calling the function.
template<class Iterator>
void insertMT(Iterator inputIt,
int const threadID, int const threadCount);
private:
SendMemoryWindow mMemoryWindow;
};
}
template<typename T>
pMR::SendWindow<T>::SendWindow(Connection const &connection,
T *const buffer, std::uint32_t const count)
: Window<T>(buffer, count),
mMemoryWindow(connection, buffer,
{static_cast<std::uint32_t>(count * sizeof(T))}) { }
template<typename T>
pMR::SendWindow<T>::SendWindow(Connection const &connection,
std::uint32_t const count)
: Window<T>(count),
mMemoryWindow(connection, this->mBuffer,
{static_cast<std::uint32_t>(count * sizeof(T))}) { }
template<typename T>
pMR::SendWindow<T>::~SendWindow()
{
#ifdef pMR_PROFILING
this->printStats("Send");
#endif // pMR_PROFILING
}
template<typename T>
void pMR::SendWindow<T>::init()
{
pMR_PROF_START(this->mTimeInit);
mMemoryWindow.init();
pMR_PROF_STOP(this->mTimeInit);
}
template<typename T>
void pMR::SendWindow<T>::post()
{
pMR_PROF_START(this->mTimePost);
mMemoryWindow.post();
pMR_PROF_STOP(this->mTimePost);
}
template<typename T>
void pMR::SendWindow<T>::wait()
{
pMR_PROF_START(this->mTimeWait);
mMemoryWindow.wait();
pMR_PROF_STOP(this->mTimeWait);
pMR_PROF_COUNT(this->mIterations);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insert(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count)
{
pMR_PROF_START(this->mTimeCopy);
this->checkBoundaries({offset}, {count});
std::copy_n(inputIt, count, this->mVector.begin() + offset);
pMR_PROF_STOP(this->mTimeCopy);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insert(Iterator inputIt)
{
return insert(inputIt, 0,
{static_cast<std::uint32_t>(this->mVector.size())});
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insertMT(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count,
int const threadID, int const threadCount)
{
pMR_PROF_START_THREAD(this->mTimeCopy);
this->checkBoundaries({offset}, {count});
static_assert(isRandomAccessIterator<Iterator>(),
"Iterator is not of random access type");
std::uint32_t threadStart;
std::uint32_t threadEnd;
splitWorkToThreads(offset, offset + count, threadID, threadCount,
threadStart, threadEnd,
getLeastCommonMultiple(static_cast<std::uint32_t>(alignment),
static_cast<std::uint32_t>(sizeof(T))));
std::copy_n(inputIt + threadStart, threadEnd - threadStart,
this->mVector.begin() + threadStart);
pMR_PROF_STOP_THREAD(this->mTimeCopy);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insertMT(Iterator inputIt,
int const threadID, int const threadCount)
{
return insertMT(inputIt, 0, {this->mVector.size()},
{threadID}, {threadCount});
}
#endif // pMR_SENDWINDOW_H
|
// Copyright 2016 Peter Georg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! @file sendwindow.hpp
//! @brief Public interface for SendWindow.
//!
//! @author Peter Georg
#ifndef pMR_SENDWINDOW_H
#define pMR_SENDWINDOW_H
#include <cstdint>
#include "config.hpp"
#include "sendmemorywindow.hpp"
#include "window.hpp"
#include "misc/thread.hpp"
#include "misc/numeric.hpp"
#include "misc/type.hpp"
namespace pMR
{
//! @brief Send Window.
template<typename T>
class SendWindow : public Window<T>
{
public:
//! @brief Window for data to send to target.
//! @details Creates a SendWindow for specified connection. Sends
//! count elements T, stored in contigious memory region
//! buffer points to, to target.
//! @param connection Connection to associate Window with.
//! @param buffer Pointer to memory region used as send buffer.
//! @param count Number of elements of type T in send buffer.
SendWindow(Connection const &connection,
T *buffer, std::uint32_t const count);
//! @brief Window for data to send to target.
//! @details Creates a SendWindow for specified connection. Sends
//! count elements T, stored in internal buffer, to target.
//! @param connection Connection to associate Window with.
//! @param count Number of elements of type T in send buffer.
SendWindow(Connection const &connection, std::uint32_t const count);
SendWindow(const SendWindow&) = delete;
SendWindow(SendWindow&&) = default;
SendWindow& operator=(const SendWindow&) = delete;
SendWindow& operator=(SendWindow&&) = default;
~SendWindow();
//! @brief Initialize a send routine.
//! @note Send buffer associated with this send window may still
//! be accessed - read and write.
//! @warning Any outstanding synchronization or previously
//! initiated send routine, associated with the same connection,
//! has to be finished before initializing a send routine.
//! @note Receive and send routines associated with the same
//! connection may be initialized simultaneously.
void init();
//! @brief Post previously initialized send routine.
//! @warning Send buffer associated with this send window may be
//! accessed read only as soon as send routine has been posted.
//! @note Depending on the used provider, this routine might be
//! blocking.
void post();
//! @brief Post previously initialized send routine, but only send
//! first sizeByte bytes.
//! @warning Send buffer associated with this send window may be
//! accessed read only as soon as send routine has been posted.
//! @note Depending on the used provider, this routine might be
//! blocking.
//! @param sizeByte First sizeByte Bytes of SendWindow to send.
void post(std::uint32_t const sizeByte);
//! @brief Wait for previously posted send routine to finish.
//! @note Write access to send buffer is allowed again after wait.
//! @note Blocking routine.
void wait();
//! @brief Copy data to internal buffer.
//! @details Copies data from storage - inputIt iterator points to -
//! to internal buffer starting at offset with bounds checking.
//! @param inputIt Iterator to source.
//! @param offset Offset for the internal buffer.
//! @param count Number of elements to copy.
template<class Iterator>
void insert(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count);
//! @brief Copy data to internal buffer.
//! @details Fills the internal buffer - starting at the beginning -
//! with data pointed to by inputIt.
//! @warning The container inputIt points to must be at least of the
//! same size as the internal buffer.
//! @param inputIt Iterator to source.
template<class Iterator>
void insert(Iterator inputIt);
//! @brief Multithreaded copy data to internal buffer.
//! @details Copies data from storage - inputIt iterator points to -
//! to internal buffer starting at offset with bounds checking.
//! The copy operation is shared among all threadCount threads
//! calling the function.
//! @warning threadID has to be in range [0, threadCount).
//! @warning The function has to be called with every threadID in
//! the range [0, threadCount).
//! @warning inputIt must be of type random access iterator.
//! @param inputIt Iterator to source.
//! @param offset Offset for the internal buffer.
//! @param count Number of elements to copy.
//! @param threadID ID of the current Thread.
//! @param threadCount Number of threads calling the function.
template<class Iterator>
void insertMT(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count,
int const threadID, int const threadCount);
//! @brief Multithreaded copy data to internal buffer.
//! @details Fills the internal buffer - starting at the beginning -
//! with data pointed to by inputIt. The copy operation is
//! shared among all threadCount threads calling the function.
//! @warning The container inputIt points to must be at least of the
//! same size as the internal buffer.
//! @warning threadID has to be in range [0, threadCount).
//! @warning The function has to be called with every threadID in
//! the range [0, threadCount).
//! @warning inputIt must be of type random access iterator.
//! @param inputIt Iterator to source.
//! @param threadID ID of the current Thread.
//! @param threadCount Number of threads calling the function.
template<class Iterator>
void insertMT(Iterator inputIt,
int const threadID, int const threadCount);
private:
SendMemoryWindow mMemoryWindow;
};
}
template<typename T>
pMR::SendWindow<T>::SendWindow(Connection const &connection,
T *const buffer, std::uint32_t const count)
: Window<T>(buffer, count),
mMemoryWindow(connection, buffer,
{static_cast<std::uint32_t>(count * sizeof(T))}) { }
template<typename T>
pMR::SendWindow<T>::SendWindow(Connection const &connection,
std::uint32_t const count)
: Window<T>(count),
mMemoryWindow(connection, this->mBuffer,
{static_cast<std::uint32_t>(count * sizeof(T))}) { }
template<typename T>
pMR::SendWindow<T>::~SendWindow()
{
#ifdef pMR_PROFILING
this->printStats("Send");
#endif // pMR_PROFILING
}
template<typename T>
void pMR::SendWindow<T>::init()
{
pMR_PROF_START(this->mTimeInit);
mMemoryWindow.init();
pMR_PROF_STOP(this->mTimeInit);
}
template<typename T>
void pMR::SendWindow<T>::post()
{
pMR_PROF_START(this->mTimePost);
mMemoryWindow.post();
pMR_PROF_STOP(this->mTimePost);
}
template<typename T>
void pMR::SendWindow<T>::post(std::uint32_t const sizeByte)
{
pMR_PROF_START(this->mTimePost);
mMemoryWindow.post({sizeByte});
pMR_PROF_STOP(this->mTimePost);
}
template<typename T>
void pMR::SendWindow<T>::wait()
{
pMR_PROF_START(this->mTimeWait);
mMemoryWindow.wait();
pMR_PROF_STOP(this->mTimeWait);
pMR_PROF_COUNT(this->mIterations);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insert(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count)
{
pMR_PROF_START(this->mTimeCopy);
this->checkBoundaries({offset}, {count});
std::copy_n(inputIt, count, this->mVector.begin() + offset);
pMR_PROF_STOP(this->mTimeCopy);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insert(Iterator inputIt)
{
return insert(inputIt, 0,
{static_cast<std::uint32_t>(this->mVector.size())});
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insertMT(Iterator inputIt,
std::uint32_t const offset, std::uint32_t const count,
int const threadID, int const threadCount)
{
pMR_PROF_START_THREAD(this->mTimeCopy);
this->checkBoundaries({offset}, {count});
static_assert(isRandomAccessIterator<Iterator>(),
"Iterator is not of random access type");
std::uint32_t threadStart;
std::uint32_t threadEnd;
splitWorkToThreads(offset, offset + count, threadID, threadCount,
threadStart, threadEnd,
getLeastCommonMultiple(static_cast<std::uint32_t>(alignment),
static_cast<std::uint32_t>(sizeof(T))));
std::copy_n(inputIt + threadStart, threadEnd - threadStart,
this->mVector.begin() + threadStart);
pMR_PROF_STOP_THREAD(this->mTimeCopy);
}
template<typename T>
template<class Iterator>
void pMR::SendWindow<T>::insertMT(Iterator inputIt,
int const threadID, int const threadCount)
{
return insertMT(inputIt, 0, {this->mVector.size()},
{threadID}, {threadCount});
}
#endif // pMR_SENDWINDOW_H
|
Add partial send to SendWindow
|
Add partial send to SendWindow
|
C++
|
apache-2.0
|
pjgeorg/pMR,pjgeorg/pMR,pjgeorg/pMR
|
d756dcf41e19cbe819a66fb482c8897d6effb0fe
|
src/statistics.hpp
|
src/statistics.hpp
|
#pragma once
#include <atomic>
#include <mutex>
#include <vector>
#include "transforms.hpp"
using namespace ranger;
// HEIGHT | VALUE > stdout
template <typename Block>
struct dumpOutputValuesOverHeight : public TransformBase<Block> {
void operator() (const Block& block) {
uint32_t height = 0xffffffff;
if (this->shouldSkip(block, nullptr, &height)) return;
std::array<uint8_t, 12> buffer;
serial::place<uint32_t>(buffer, height);
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& output : transaction.outputs) {
serial::place<uint64_t>(range(buffer).drop(4), output.value);
fwrite(buffer.begin(), buffer.size(), 1, stdout);
}
transactions.pop_front();
}
}
};
auto perc (uint64_t a, uint64_t ab) {
return static_cast<double>(a) / static_cast<double>(ab);
}
template <typename Block>
struct dumpStatistics : public TransformBase<Block> {
std::atomic_ulong inputs;
std::atomic_ulong outputs;
std::atomic_ulong transactions;
std::atomic_ulong version1;
std::atomic_ulong version2;
std::atomic_ulong locktimesGt0;
std::atomic_ulong nonFinalSequences;
dumpStatistics () {
this->inputs = 0;
this->outputs = 0;
this->transactions = 0;
this->version1 = 0;
this->version2 = 0;
this->locktimesGt0 = 0;
this->nonFinalSequences = 0;
}
virtual ~dumpStatistics () {
std::cout <<
"Transactions:\t" << this->transactions << '\n' <<
"-- Inputs:\t" << this->inputs << " (ratio " << perc(this->inputs, this->transactions) << ") \n" <<
"-- Outputs:\t" << this->outputs << " (ratio " << perc(this->outputs, this->transactions) << ") \n" <<
"-- Version1:\t" << this->version1 << " (" << perc(this->version1, this->transactions) * 100 << "%) \n" <<
"-- Version2:\t" << this->version2 << " (" << perc(this->version2, this->transactions) * 100 << "%) \n" <<
"-- Locktimes (>0):\t" << this->locktimesGt0 << " (" << perc(this->locktimesGt0, this->transactions) * 100 << "%) \n" <<
"-- Sequences (!= FINAL):\t" << this->nonFinalSequences << " (" << perc(this->nonFinalSequences, this->inputs) * 100 << "%) \n" <<
std::endl;
}
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
auto transactions = block.transactions();
this->transactions += transactions.size();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
this->inputs += transaction.inputs.size();
size_t nfs = 0;
for (const auto& input : transaction.inputs) {
if (input.sequence != 0xffffffff) nfs++;
}
this->nonFinalSequences += nfs;
this->outputs += transaction.outputs.size();
this->version1 += transaction.version == 1;
this->version2 += transaction.version == 2;
this->locktimesGt0 += transaction.locktime > 0;
transactions.pop_front();
}
}
};
// ASM > stdout
template <typename Block>
struct dumpASM : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::array<uint8_t, 1024*1024> buffer;
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& output : transaction.inputs) {
auto tmp = range(buffer);
putASM(tmp, output.script);
serial::put<char>(tmp, '\n');
const auto lineLength = buffer.size() - tmp.size();
// FIXME: stdout is non-atomic past 4096
if (lineLength > 4096) continue;
fwrite(buffer.begin(), lineLength, 1, stdout);
}
transactions.pop_front();
}
}
};
// BLOCK_HEADER > stdout
template <typename Block>
struct dumpHeaders : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
fwrite(block.header.begin(), 80, 1, stdout);
}
};
// SCRIPT_LENGTH | SCRIPT > stdout
template <typename Block>
struct dumpScripts : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::array<uint8_t, 4096> buffer;
const auto maxScriptLength = buffer.size() - sizeof(uint16_t);
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& input : transaction.inputs) {
if (input.script.size() > maxScriptLength) continue;
auto r = range(buffer);
serial::put<uint16_t>(r, static_cast<uint16_t>(input.script.size()));
r.put(input.script);
fwrite(buffer.begin(), buffer.size() - r.size(), 1, stdout);
}
for (const auto& output : transaction.outputs) {
if (output.script.size() > maxScriptLength) continue;
auto r = range(buffer);
serial::put<uint16_t>(r, static_cast<uint16_t>(output.script.size()));
r.put(output.script);
fwrite(buffer.begin(), buffer.size() - r.size(), 1, stdout);
}
transactions.pop_front();
}
}
};
typedef std::pair<std::vector<uint8_t>, uint64_t> TxoDetail;
typedef std::pair<uint256_t, uint32_t> Txin;
typedef std::pair<Txin, TxoDetail> Txo;
// HEIGHT | VALUE > stdout
template <typename Block>
struct dumpUnspents : public TransformBase<Block> {
static constexpr auto BLANK_TXIN = Txin{ {}, 0 };
std::mutex mutex;
HList<Txin, TxoDetail> unspents;
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::vector<Txin> txins;
std::vector<Txo> txos;
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
const auto txHash = transaction.hash();
for (const auto& input : transaction.inputs) {
uint256_t prevTxHash;
std::copy(input.hash.begin(), input.hash.end(), prevTxHash.begin());
txins.emplace_back(Txin{prevTxHash, input.vout});
}
uint32_t vout = 0;
for (const auto& output : transaction.outputs) {
std::vector<uint8_t> script;
script.resize(output.script.size());
std::copy(output.script.begin(), output.script.end(), script.begin());
txos.emplace_back(Txo({txHash, vout}, {script, output.value}));
++vout;
}
transactions.pop_front();
}
std::lock_guard<std::mutex>(this->mutex);
for (const auto& txo : txos) {
this->unspents.insort(txo.first, txo.second);
}
for (const auto& txin : txins) {
const auto iter = this->unspents.find(txin);
if (iter == this->unspents.end()) continue; // uh, maybe you are only doing part of the blockchain!
iter->first = BLANK_TXIN;
}
this->unspents.erase(std::remove_if(
this->unspents.begin(),
this->unspents.end(),
[](const auto& x) {
return x.first == BLANK_TXIN;
}
), this->unspents.end());
std::cout << this->unspents.size() << std::endl;
}
};
|
#pragma once
#include <atomic>
#include <mutex>
#include <vector>
#include "transforms.hpp"
using namespace ranger;
// HEIGHT | VALUE > stdout
template <typename Block>
struct dumpOutputValuesOverHeight : public TransformBase<Block> {
void operator() (const Block& block) {
uint32_t height = 0xffffffff;
if (this->shouldSkip(block, nullptr, &height)) return;
std::array<uint8_t, 12> buffer;
serial::place<uint32_t>(buffer, height);
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& output : transaction.outputs) {
serial::place<uint64_t>(range(buffer).drop(4), output.value);
fwrite(buffer.begin(), buffer.size(), 1, stdout);
}
transactions.pop_front();
}
}
};
auto perc (uint64_t a, uint64_t ab) {
return static_cast<double>(a) / static_cast<double>(ab);
}
template <typename Block>
struct dumpStatistics : public TransformBase<Block> {
std::atomic_ulong inputs;
std::atomic_ulong outputs;
std::atomic_ulong transactions;
std::atomic_ulong version1;
std::atomic_ulong version2;
std::atomic_ulong locktimesGt0;
std::atomic_ulong nonFinalSequences;
dumpStatistics () {
this->inputs = 0;
this->outputs = 0;
this->transactions = 0;
this->version1 = 0;
this->version2 = 0;
this->locktimesGt0 = 0;
this->nonFinalSequences = 0;
}
virtual ~dumpStatistics () {
std::cout <<
"Transactions:\t" << this->transactions << '\n' <<
"-- Inputs:\t" << this->inputs << " (ratio " << perc(this->inputs, this->transactions) << ") \n" <<
"-- Outputs:\t" << this->outputs << " (ratio " << perc(this->outputs, this->transactions) << ") \n" <<
"-- Version1:\t" << this->version1 << " (" << perc(this->version1, this->transactions) * 100 << "%) \n" <<
"-- Version2:\t" << this->version2 << " (" << perc(this->version2, this->transactions) * 100 << "%) \n" <<
"-- Locktimes (>0):\t" << this->locktimesGt0 << " (" << perc(this->locktimesGt0, this->transactions) * 100 << "%) \n" <<
"-- Sequences (!= FINAL):\t" << this->nonFinalSequences << " (" << perc(this->nonFinalSequences, this->inputs) * 100 << "%) \n" <<
std::endl;
}
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
auto transactions = block.transactions();
this->transactions += transactions.size();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
this->inputs += transaction.inputs.size();
size_t nfs = 0;
for (const auto& input : transaction.inputs) {
if (input.sequence != 0xffffffff) nfs++;
}
this->nonFinalSequences += nfs;
this->outputs += transaction.outputs.size();
this->version1 += transaction.version == 1;
this->version2 += transaction.version == 2;
this->locktimesGt0 += transaction.locktime > 0;
transactions.pop_front();
}
}
};
// ASM > stdout
template <typename Block>
struct dumpASM : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::array<uint8_t, 1024*1024> buffer;
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& output : transaction.inputs) {
auto tmp = range(buffer);
putASM(tmp, output.script);
serial::put<char>(tmp, '\n');
const auto lineLength = buffer.size() - tmp.size();
// FIXME: stdout is non-atomic past 4096
if (lineLength > 4096) continue;
fwrite(buffer.begin(), lineLength, 1, stdout);
}
transactions.pop_front();
}
}
};
// BLOCK_HEADER > stdout
template <typename Block>
struct dumpHeaders : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
fwrite(block.header.begin(), 80, 1, stdout);
}
};
// SCRIPT_LENGTH | SCRIPT > stdout
template <typename Block>
struct dumpScripts : public TransformBase<Block> {
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::array<uint8_t, 4096> buffer;
const auto maxScriptLength = buffer.size() - sizeof(uint16_t);
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
for (const auto& input : transaction.inputs) {
if (input.script.size() > maxScriptLength) continue;
auto r = range(buffer);
serial::put<uint16_t>(r, static_cast<uint16_t>(input.script.size()));
r.put(input.script);
fwrite(buffer.begin(), buffer.size() - r.size(), 1, stdout);
}
for (const auto& output : transaction.outputs) {
if (output.script.size() > maxScriptLength) continue;
auto r = range(buffer);
serial::put<uint16_t>(r, static_cast<uint16_t>(output.script.size()));
r.put(output.script);
fwrite(buffer.begin(), buffer.size() - r.size(), 1, stdout);
}
transactions.pop_front();
}
}
};
typedef std::pair<std::vector<uint8_t>, uint64_t> TxoDetail;
typedef std::pair<uint256_t, uint32_t> Txin;
typedef std::pair<Txin, TxoDetail> Txo;
// HEIGHT | VALUE > stdout
template <typename Block>
struct dumpUnspents : public TransformBase<Block> {
static constexpr auto BLANK_TXIN = Txin{ {}, 0 };
std::mutex mutex;
HList<Txin, TxoDetail> unspents;
void operator() (const Block& block) {
if (this->shouldSkip(block)) return;
std::vector<Txin> txins;
std::vector<Txo> txos;
auto transactions = block.transactions();
while (not transactions.empty()) {
const auto& transaction = transactions.front();
const auto txHash = transaction.hash();
for (const auto& input : transaction.inputs) {
uint256_t prevTxHash;
std::copy(input.hash.begin(), input.hash.end(), prevTxHash.begin());
txins.emplace_back(Txin{prevTxHash, input.vout});
}
uint32_t vout = 0;
for (const auto& output : transaction.outputs) {
std::vector<uint8_t> script;
script.resize(output.script.size());
std::copy(output.script.begin(), output.script.end(), script.begin());
txos.emplace_back(Txo({txHash, vout}, {script, output.value}));
++vout;
}
transactions.pop_front();
}
std::lock_guard<std::mutex> lock(this->mutex);
for (const auto& txo : txos) {
this->unspents.insort(txo.first, txo.second);
}
for (const auto& txin : txins) {
const auto iter = this->unspents.find(txin);
if (iter == this->unspents.end()) continue; // uh, maybe you are only doing part of the blockchain!
iter->first = BLANK_TXIN;
}
this->unspents.erase(std::remove_if(
this->unspents.begin(),
this->unspents.end(),
[](const auto& x) {
return x.first == BLANK_TXIN;
}
), this->unspents.end());
std::cout << this->unspents.size() << std::endl;
}
};
|
Fix missing lock guard (#30)
|
Fix missing lock guard (#30)
This commit fixes a bug where the lock guard (for concurrently accessing
the same scope from different threads) had basically no effect, due to
being bound to a temporary only.
|
C++
|
isc
|
dcousens/fast-dat-parser,dcousens/fast-dat-parser,dcousens/fast-dat-parser
|
f0c1b240348d4fc6ada47452883a22cea891350e
|
src/program.cpp
|
src/program.cpp
|
/*! @file program.cpp
@brief Implementation of Program class
*/
#include "version.hpp"
#include "program.hpp"
#include "pathtype.hpp"
#include "genotype.hpp"
#include "gridsearch.hpp"
#include "gradient_descent.hpp"
#include <wtl/exception.hpp>
#include <wtl/debug.hpp>
#include <wtl/iostr.hpp>
#include <wtl/chrono.hpp>
#include <wtl/getopt.hpp>
#include <wtl/zfstream.hpp>
#include <boost/filesystem.hpp>
#include <regex>
namespace likeligrid {
namespace fs = boost::filesystem;
namespace po = boost::program_options;
inline po::options_description general_desc() {HERE;
po::options_description description("General");
description.add_options()
("help,h", po::bool_switch(), "print this help")
("verbose,v", po::bool_switch(), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1));
return description;
}
po::options_description Program::options_desc() {HERE;
po::options_description description("Program");
description.add_options()
("parallel,j", po::value(&CONCURRENCY)->default_value(CONCURRENCY))
("max-sites,s", po::value(&MAX_SITES)->default_value(MAX_SITES))
("gradient,g", po::bool_switch(&GRADIENT_MODE))
("epistasis,e", po::value(&EPISTASIS_PAIR)->default_value(EPISTASIS_PAIR)->multitoken())
("pleiotropy,p", po::bool_switch(&PLEIOTROPY));
return description;
}
po::options_description Program::positional_desc() {HERE;
po::options_description description("Positional");
description.add_options()
("infile", po::value(&INFILE)->default_value(INFILE));
return description;
}
[[noreturn]] void Program::help_and_exit() {HERE;
auto description = general_desc();
description.add(options_desc());
// do not print positional arguments as options
std::cout << "commit " << GIT_COMMIT_HASH
<< " [" << GIT_BRANCH << "]\n"
<< "Date: " << GIT_COMMIT_TIME << std::endl; std::cout << "Usage: tek [options]\n" << std::endl;
std::cout << "Usage: likeligrid [options] infile\n" << std::endl;
description.print(std::cout);
throw wtl::ExitSuccess();
}
//! Unit test for each class
void Program::test(const int flag) {HERE;
switch (flag) {
case 0:
break;
case 1:
GridSearch::test();
GradientDescent::test();
throw wtl::ExitSuccess();
case 2:
GenotypeModel::test();
PathtypeModel::test();
throw wtl::ExitSuccess();
case 3: {
wtl::izfstream ist(INFILE);
GenotypeModel model(ist, MAX_SITES);
model.benchmark(CONCURRENCY);
throw wtl::ExitSuccess();
}
default:
throw std::runtime_error("Unknown argument for --test");
}
}
Program::Program(const std::vector<std::string>& arguments) {HERE;
wtl::join(arguments, std::cout, " ") << std::endl;
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(15);
std::cerr.precision(6);
wtl::set_SIGINT_handler();
auto description = general_desc();
description.add(options_desc());
description.add(positional_desc());
po::positional_options_description positional;
positional.add("infile", 1);
po::variables_map vm;
po::store(po::command_line_parser({arguments.begin() + 1, arguments.end()}).
options(description).
positional(positional).run(), vm);
if (vm["help"].as<bool>()) {help_and_exit();}
po::notify(vm);
if (EPISTASIS_PAIR.size() != 2u) {
throw std::runtime_error("EPISTASIS_PAIR.size() != 2U");
}
if (vm["verbose"].as<bool>()) {
std::cerr << wtl::iso8601datetime() << std::endl;
std::cerr << wtl::flags_into_string(vm) << std::endl;
}
test(vm["test"].as<int>());
}
void Program::run() {HERE;
std::pair<size_t, size_t> epistasis{EPISTASIS_PAIR[0u], EPISTASIS_PAIR[1u]};
if (PLEIOTROPY && (epistasis.first == epistasis.second)) {
throw std::runtime_error("PLEIOTROPY && (epistasis.first == epistasis.second)");
}
try {
if (GRADIENT_MODE) {
GradientDescent searcher(INFILE, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
const auto outfile = fs::path(make_outdir()) / searcher.outfile();
std::cerr << "outfile: " << outfile << std::endl;
wtl::ozfstream ost(outfile.string());
ost.precision(std::cout.precision());
searcher.run(ost);
} else if (INFILE == "-") {
GridSearch searcher(std::cin, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
searcher.run(false);
} else {
GridSearch searcher(INFILE, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
// after constructor success
const std::string outdir = make_outdir();
fs::current_path(outdir);
searcher.run(true);
}
} catch (const wtl::KeyboardInterrupt& e) {
std::cerr << e.what() << std::endl;
}
}
std::string Program::make_outdir() const {
std::smatch mobj;
std::regex_search(INFILE, mobj, std::regex("([^/]+?)\\.[^/]+$"));
std::ostringstream oss;
oss << mobj.str(1) << "-s" << MAX_SITES;
if (GRADIENT_MODE) {oss << "-g";}
if (EPISTASIS_PAIR[0u] != EPISTASIS_PAIR[1u]) {
oss << "-e" << EPISTASIS_PAIR[0u]
<< "x" << EPISTASIS_PAIR[1u];
}
if (PLEIOTROPY) {oss << "-p";}
const std::string outdir = oss.str();
fs::create_directory(outdir);
return outdir;
}
} // namespace likeligrid
|
/*! @file program.cpp
@brief Implementation of Program class
*/
#include "version.hpp"
#include "program.hpp"
#include "pathtype.hpp"
#include "genotype.hpp"
#include "gridsearch.hpp"
#include "gradient_descent.hpp"
#include <wtl/exception.hpp>
#include <wtl/debug.hpp>
#include <wtl/iostr.hpp>
#include <wtl/chrono.hpp>
#include <wtl/getopt.hpp>
#include <wtl/zfstream.hpp>
#include <boost/filesystem.hpp>
#include <regex>
namespace likeligrid {
namespace fs = boost::filesystem;
namespace po = boost::program_options;
inline po::options_description general_desc() {HERE;
po::options_description description("General");
description.add_options()
("help,h", po::bool_switch(), "print this help")
("verbose,v", po::bool_switch(), "verbose output")
("test", po::value<int>()->default_value(0)->implicit_value(1));
return description;
}
po::options_description Program::options_desc() {HERE;
po::options_description description("Program");
description.add_options()
("parallel,j", po::value(&CONCURRENCY)->default_value(CONCURRENCY))
("max-sites,s", po::value(&MAX_SITES)->default_value(MAX_SITES))
("gradient,g", po::bool_switch(&GRADIENT_MODE))
("epistasis,e", po::value(&EPISTASIS_PAIR)->default_value(EPISTASIS_PAIR)->multitoken())
("pleiotropy,p", po::bool_switch(&PLEIOTROPY));
return description;
}
po::options_description Program::positional_desc() {HERE;
po::options_description description("Positional");
description.add_options()
("infile", po::value(&INFILE)->default_value(INFILE));
return description;
}
[[noreturn]] void Program::help_and_exit() {HERE;
auto description = general_desc();
description.add(options_desc());
// do not print positional arguments as options
std::cout << "commit " << GIT_COMMIT_HASH
<< " [" << GIT_BRANCH << "]\n"
<< "Date: " << GIT_COMMIT_TIME << std::endl; std::cout << "Usage: tek [options]\n" << std::endl;
std::cout << "Usage: likeligrid [options] infile\n" << std::endl;
description.print(std::cout);
throw wtl::ExitSuccess();
}
//! Unit test for each class
void Program::test(const int flag) {HERE;
switch (flag) {
case 0:
break;
case 1:
GridSearch::test();
GradientDescent::test();
throw wtl::ExitSuccess();
case 2:
GenotypeModel::test();
PathtypeModel::test();
throw wtl::ExitSuccess();
case 3: {
wtl::izfstream ist(INFILE);
GenotypeModel model(ist, MAX_SITES);
model.benchmark(CONCURRENCY);
throw wtl::ExitSuccess();
}
default:
throw std::runtime_error("Unknown argument for --test");
}
}
Program::Program(const std::vector<std::string>& arguments) {HERE;
wtl::join(arguments, std::cout, " ") << std::endl;
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.precision(15);
std::cerr.precision(6);
wtl::set_SIGINT_handler();
auto description = general_desc();
description.add(options_desc());
description.add(positional_desc());
po::positional_options_description positional;
positional.add("infile", 1);
po::variables_map vm;
po::store(po::command_line_parser({arguments.begin() + 1, arguments.end()}).
options(description).
positional(positional).run(), vm);
if (vm["help"].as<bool>()) {help_and_exit();}
po::notify(vm);
if (EPISTASIS_PAIR.size() != 2u) {
throw std::runtime_error("EPISTASIS_PAIR.size() != 2U");
}
if (vm["verbose"].as<bool>()) {
std::cerr << wtl::iso8601datetime() << std::endl;
std::cerr << wtl::flags_into_string(vm) << std::endl;
}
test(vm["test"].as<int>());
}
void Program::run() {HERE;
std::pair<size_t, size_t> epistasis{EPISTASIS_PAIR[0u], EPISTASIS_PAIR[1u]};
if (PLEIOTROPY && (epistasis.first == epistasis.second)) {
throw std::runtime_error("PLEIOTROPY && (epistasis.first == epistasis.second)");
}
try {
if (GRADIENT_MODE) {
if (INFILE == "-") {
GradientDescent searcher(std::cin, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
searcher.run(std::cout);
return;
}
GradientDescent searcher(INFILE, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
const auto outfile = fs::path(make_outdir()) / searcher.outfile();
std::cerr << "outfile: " << outfile << std::endl;
wtl::ozfstream ost(outfile.string());
ost.precision(std::cout.precision());
searcher.run(ost);
} else if (INFILE == "-") {
GridSearch searcher(std::cin, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
searcher.run(false);
} else {
GridSearch searcher(INFILE, MAX_SITES, epistasis, PLEIOTROPY, CONCURRENCY);
// after constructor success
const std::string outdir = make_outdir();
fs::current_path(outdir);
searcher.run(true);
}
} catch (const wtl::KeyboardInterrupt& e) {
std::cerr << e.what() << std::endl;
}
}
std::string Program::make_outdir() const {
std::smatch mobj;
std::regex_search(INFILE, mobj, std::regex("([^/]+?)\\.[^/]+$"));
std::ostringstream oss;
oss << mobj.str(1) << "-s" << MAX_SITES;
if (GRADIENT_MODE) {oss << "-g";}
if (EPISTASIS_PAIR[0u] != EPISTASIS_PAIR[1u]) {
oss << "-e" << EPISTASIS_PAIR[0u]
<< "x" << EPISTASIS_PAIR[1u];
}
if (PLEIOTROPY) {oss << "-p";}
const std::string outdir = oss.str();
fs::create_directory(outdir);
return outdir;
}
} // namespace likeligrid
|
Support stdin with -g
|
:sparkles: Support stdin with -g
|
C++
|
mit
|
heavywatal/likeligrid,heavywatal/likeligrid
|
0783becfdd063bc410a9aff820933c7fd36dc48b
|
storage/src/vespa/storage/distributor/operations/external/updateoperation.cpp
|
storage/src/vespa/storage/distributor/operations/external/updateoperation.cpp
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "updateoperation.h"
#include <vespa/document/fieldvalue/document.h>
#include <vespa/storageapi/message/bucket.h>
#include <vespa/storageapi/message/persistence.h>
#include <vespa/storage/distributor/distributormetricsset.h>
#include <vespa/storage/distributor/distributor_bucket_space.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".distributor.callback.doc.update");
using namespace storage::distributor;
using namespace storage;
using document::BucketSpace;
UpdateOperation::UpdateOperation(DistributorComponent& manager,
DistributorBucketSpace &bucketSpace,
const std::shared_ptr<api::UpdateCommand> & msg,
UpdateMetricSet& metric)
: Operation(),
_trackerInstance(metric, std::make_shared<api::UpdateReply>(*msg),
manager, msg->getTimestamp()),
_tracker(_trackerInstance),
_msg(msg),
_manager(manager),
_bucketSpace(bucketSpace),
_newestTimestampLocation(),
_infoAtSendTime(),
_metrics(metric)
{
}
bool
UpdateOperation::anyStorageNodesAvailable() const
{
const auto& clusterState(_bucketSpace.getClusterState());
const auto storageNodeCount(
clusterState.getNodeCount(lib::NodeType::STORAGE));
for (uint16_t i = 0; i < storageNodeCount; ++i) {
const auto& ns(clusterState.getNodeState(
lib::Node(lib::NodeType::STORAGE, i)));
if (ns.getState() == lib::State::UP
|| ns.getState() == lib::State::RETIRED)
{
return true;
}
}
return false;
}
void
UpdateOperation::onStart(DistributorMessageSender& sender)
{
LOG(debug, "Received UPDATE %s for bucket %" PRIx64,
_msg->getDocumentId().toString().c_str(),
_manager.getBucketIdFactory().getBucketId(
_msg->getDocumentId()).getRawId());
// Don't do anything if all nodes are down.
if (!anyStorageNodesAvailable()) {
_tracker.fail(sender,
api::ReturnCode(api::ReturnCode::NOT_CONNECTED,
"Can't store document: No storage nodes "
"available"));
return;
}
document::BucketId bucketId(
_manager.getBucketIdFactory().getBucketId(
_msg->getDocumentId()));
std::vector<BucketDatabase::Entry> entries;
_bucketSpace.getBucketDatabase().getParents(bucketId, entries);
if (entries.empty()) {
_tracker.fail(sender,
api::ReturnCode(api::ReturnCode::OK,
"No buckets found for given document update"));
return;
}
// An UpdateOperation should only be started iff all replicas are consistent
// with each other, so sampling a single replica should be equal to sampling them all.
assert(entries[0].getBucketInfo().getNodeCount() > 0); // Empty buckets are not allowed
_infoAtSendTime = entries[0].getBucketInfo().getNodeRef(0).getBucketInfo();
// FIXME(vekterli): this loop will happily update all replicas in the
// bucket sub-tree, but there is nothing here at all which will fail the
// update if we cannot satisfy a desired replication level (not even for
// n-of-m operations).
for (uint32_t j = 0; j < entries.size(); ++j) {
LOG(spam, "Found bucket %s", entries[j].toString().c_str());
const std::vector<uint16_t>& nodes = entries[j]->getNodes();
std::vector<MessageTracker::ToSend> messages;
for (uint32_t i = 0; i < nodes.size(); i++) {
std::shared_ptr<api::UpdateCommand> command(
new api::UpdateCommand(document::Bucket(_msg->getBucket().getBucketSpace(), entries[j].getBucketId()),
_msg->getUpdate(),
_msg->getTimestamp()));
copyMessageSettings(*_msg, *command);
command->setOldTimestamp(_msg->getOldTimestamp());
command->setCondition(_msg->getCondition());
messages.push_back(MessageTracker::ToSend(command, nodes[i]));
}
_tracker.queueMessageBatch(messages);
}
_tracker.flushQueue(sender);
_msg = std::shared_ptr<api::UpdateCommand>();
};
void
UpdateOperation::onReceive(DistributorMessageSender& sender,
const std::shared_ptr<api::StorageReply> & msg)
{
auto& reply = static_cast<api::UpdateReply&>(*msg);
if (msg->getType() == api::MessageType::UPDATE_REPLY) {
uint16_t node = _tracker.handleReply(reply);
if (node != (uint16_t)-1) {
if (reply.getResult().getResult() == api::ReturnCode::OK) {
_results.emplace_back(reply.getBucketId(), reply.getBucketInfo(), reply.getOldTimestamp(), node);
}
if (_tracker.getReply().get()) {
auto& replyToSend = static_cast<api::UpdateReply&>(*_tracker.getReply());
uint64_t oldTs = 0;
uint64_t goodNode = 0;
// Find the highest old timestamp.
for (uint32_t i = 0; i < _results.size(); i++) {
if (_results[i].oldTs > oldTs) {
oldTs = _results[i].oldTs;
goodNode = i;
}
}
replyToSend.setOldTimestamp(oldTs);
for (uint32_t i = 0; i < _results.size(); i++) {
if (_results[i].oldTs < oldTs) {
LOG(warning, "Update operation for '%s' in bucket %s updated documents with different timestamps. "
"This should not happen and may indicate undetected replica divergence. "
"Found ts=%" PRIu64 " on node %u, ts=%" PRIu64 " on node %u",
reply.getDocumentId().toString().c_str(),
reply.getBucket().toString().c_str(),
_results[i].oldTs, _results[i].nodeId,
_results[goodNode].oldTs, _results[goodNode].nodeId);
_metrics.diverging_timestamp_updates.inc();
replyToSend.setNodeWithNewestTimestamp(_results[goodNode].nodeId);
_newestTimestampLocation.first = _results[goodNode].bucketId;
_newestTimestampLocation.second = _results[goodNode].nodeId;
LOG(warning, "Bucket info prior to update operation was: %s. After update, "
"info on node %u is %s, info on node %u is %s",
_infoAtSendTime.toString().c_str(),
_results[i].nodeId, _results[i].bucketInfo.toString().c_str(),
_results[goodNode].nodeId, _results[goodNode].bucketInfo.toString().c_str());
break;
}
}
}
_tracker.updateFromReply(sender, reply, node);
}
} else {
_tracker.receiveReply(sender, static_cast<api::BucketInfoReply&>(*msg));
}
}
void
UpdateOperation::onClose(DistributorMessageSender& sender)
{
_tracker.fail(sender, api::ReturnCode(api::ReturnCode::ABORTED, "Process is shutting down"));
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "updateoperation.h"
#include <vespa/document/fieldvalue/document.h>
#include <vespa/storageapi/message/bucket.h>
#include <vespa/storageapi/message/persistence.h>
#include <vespa/storage/distributor/distributormetricsset.h>
#include <vespa/storage/distributor/distributor_bucket_space.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".distributor.callback.doc.update");
using namespace storage::distributor;
using namespace storage;
using document::BucketSpace;
UpdateOperation::UpdateOperation(DistributorComponent& manager,
DistributorBucketSpace &bucketSpace,
const std::shared_ptr<api::UpdateCommand> & msg,
UpdateMetricSet& metric)
: Operation(),
_trackerInstance(metric, std::make_shared<api::UpdateReply>(*msg),
manager, msg->getTimestamp()),
_tracker(_trackerInstance),
_msg(msg),
_manager(manager),
_bucketSpace(bucketSpace),
_newestTimestampLocation(),
_infoAtSendTime(),
_metrics(metric)
{
}
bool
UpdateOperation::anyStorageNodesAvailable() const
{
const auto& clusterState(_bucketSpace.getClusterState());
const auto storageNodeCount(
clusterState.getNodeCount(lib::NodeType::STORAGE));
for (uint16_t i = 0; i < storageNodeCount; ++i) {
const auto& ns(clusterState.getNodeState(
lib::Node(lib::NodeType::STORAGE, i)));
if (ns.getState() == lib::State::UP
|| ns.getState() == lib::State::RETIRED)
{
return true;
}
}
return false;
}
void
UpdateOperation::onStart(DistributorMessageSender& sender)
{
LOG(debug, "Received UPDATE %s for bucket %" PRIx64,
_msg->getDocumentId().toString().c_str(),
_manager.getBucketIdFactory().getBucketId(
_msg->getDocumentId()).getRawId());
// Don't do anything if all nodes are down.
if (!anyStorageNodesAvailable()) {
_tracker.fail(sender,
api::ReturnCode(api::ReturnCode::NOT_CONNECTED,
"Can't store document: No storage nodes "
"available"));
return;
}
document::BucketId bucketId(
_manager.getBucketIdFactory().getBucketId(
_msg->getDocumentId()));
std::vector<BucketDatabase::Entry> entries;
_bucketSpace.getBucketDatabase().getParents(bucketId, entries);
if (entries.empty()) {
_tracker.fail(sender,
api::ReturnCode(api::ReturnCode::OK,
"No buckets found for given document update"));
return;
}
// An UpdateOperation should only be started iff all replicas are consistent
// with each other, so sampling a single replica should be equal to sampling them all.
assert(entries[0].getBucketInfo().getNodeCount() > 0); // Empty buckets are not allowed
_infoAtSendTime = entries[0].getBucketInfo().getNodeRef(0).getBucketInfo();
// FIXME(vekterli): this loop will happily update all replicas in the
// bucket sub-tree, but there is nothing here at all which will fail the
// update if we cannot satisfy a desired replication level (not even for
// n-of-m operations).
for (uint32_t j = 0; j < entries.size(); ++j) {
LOG(spam, "Found bucket %s", entries[j].toString().c_str());
const std::vector<uint16_t>& nodes = entries[j]->getNodes();
std::vector<MessageTracker::ToSend> messages;
for (uint32_t i = 0; i < nodes.size(); i++) {
std::shared_ptr<api::UpdateCommand> command(
new api::UpdateCommand(document::Bucket(_msg->getBucket().getBucketSpace(), entries[j].getBucketId()),
_msg->getUpdate(),
_msg->getTimestamp()));
copyMessageSettings(*_msg, *command);
command->setOldTimestamp(_msg->getOldTimestamp());
command->setCondition(_msg->getCondition());
messages.push_back(MessageTracker::ToSend(command, nodes[i]));
}
_tracker.queueMessageBatch(messages);
}
_tracker.flushQueue(sender);
_msg = std::shared_ptr<api::UpdateCommand>();
};
void
UpdateOperation::onReceive(DistributorMessageSender& sender,
const std::shared_ptr<api::StorageReply> & msg)
{
auto& reply = static_cast<api::UpdateReply&>(*msg);
if (msg->getType() == api::MessageType::UPDATE_REPLY) {
uint16_t node = _tracker.handleReply(reply);
if (node != (uint16_t)-1) {
if (reply.getResult().getResult() == api::ReturnCode::OK) {
_results.emplace_back(reply.getBucketId(), reply.getBucketInfo(), reply.getOldTimestamp(), node);
}
if (_tracker.getReply().get()) {
auto& replyToSend = static_cast<api::UpdateReply&>(*_tracker.getReply());
uint64_t oldTs = 0;
uint64_t goodNode = 0;
// Find the highest old timestamp.
for (uint32_t i = 0; i < _results.size(); i++) {
if (_results[i].oldTs > oldTs) {
oldTs = _results[i].oldTs;
goodNode = i;
}
}
replyToSend.setOldTimestamp(oldTs);
for (uint32_t i = 0; i < _results.size(); i++) {
if (_results[i].oldTs < oldTs) {
LOG(error, "Update operation for '%s' in bucket %s updated documents with different timestamps. "
"This should not happen and may indicate undetected replica divergence. "
"Found ts=%" PRIu64 " on node %u, ts=%" PRIu64 " on node %u",
reply.getDocumentId().toString().c_str(),
reply.getBucket().toString().c_str(),
_results[i].oldTs, _results[i].nodeId,
_results[goodNode].oldTs, _results[goodNode].nodeId);
_metrics.diverging_timestamp_updates.inc();
replyToSend.setNodeWithNewestTimestamp(_results[goodNode].nodeId);
_newestTimestampLocation.first = _results[goodNode].bucketId;
_newestTimestampLocation.second = _results[goodNode].nodeId;
LOG(warning, "Bucket info prior to update operation was: %s. After update, "
"info on node %u is %s, info on node %u is %s",
_infoAtSendTime.toString().c_str(),
_results[i].nodeId, _results[i].bucketInfo.toString().c_str(),
_results[goodNode].nodeId, _results[goodNode].bucketInfo.toString().c_str());
break;
}
}
}
_tracker.updateFromReply(sender, reply, node);
}
} else {
_tracker.receiveReply(sender, static_cast<api::BucketInfoReply&>(*msg));
}
}
void
UpdateOperation::onClose(DistributorMessageSender& sender)
{
_tracker.fail(sender, api::ReturnCode(api::ReturnCode::ABORTED, "Process is shutting down"));
}
|
Upgrade log level to error for detected update inconstencies
|
Upgrade log level to error for detected update inconstencies
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
2584f41e80ac96ccd58293acd9187169054e8bee
|
chrome/browser/gtk/infobar_gtk.cc
|
chrome/browser/gtk/infobar_gtk.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/infobar_gtk.h"
#include <gtk/gtk.h>
#include "base/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/gtk/link_button_gtk.h"
#include "chrome/common/gtk_util.h"
namespace {
// TODO(estade): The background should be a gradient. For now we just use this
// solid color.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(250, 230, 145);
// Border color (the top pixel of the infobar).
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// Set the top border and background color.
gtk_widget_modify_bg(bg_box, GTK_STATE_NORMAL, &kBackgroundColor);
border_bin_.Own(gfx::CreateGtkBorderBin(bg_box, &kBorderColor,
0, 1, 0, 0));
gtk_widget_set_size_request(border_bin_.get(), -1, kInfoBarHeight);
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
close_button_.reset(CustomDrawButton::AddBarCloseButton(hbox_, 0));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
if (border_bin_.get()->window)
gdk_window_lower(border_bin_.get()->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
link_button_.reset(new LinkButtonGtk(WideToUTF8(link_text).c_str()));
g_signal_connect(link_button_->widget(), "clicked",
G_CALLBACK(OnLinkClick), this);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button_->widget(), FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), link_button_->widget(),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
// TODO(estade): we need an equivalent for DispositionFromEventFlags().
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(CURRENT_TAB)) {
link_info_bar->RemoveInfoBar();
}
}
// The clickable link text.
scoped_ptr<LinkButtonGtk> link_button_;
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
GtkWidget* centering_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(centering_vbox), button, TRUE, FALSE, 0);
gtk_box_pack_end(GTK_BOX(hbox_), centering_vbox, FALSE, FALSE, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
|
// 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/infobar_gtk.h"
#include <gtk/gtk.h>
#include "base/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/gtk/link_button_gtk.h"
#include "chrome/common/gtk_util.h"
namespace {
// TODO(estade): The background should be a gradient. For now we just use this
// solid color.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(250, 230, 145);
// Border color (the top pixel of the infobar).
const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4);
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// Set the top border and background color.
gtk_widget_modify_bg(bg_box, GTK_STATE_NORMAL, &kBackgroundColor);
border_bin_.Own(gfx::CreateGtkBorderBin(bg_box, &kBorderColor,
0, 1, 0, 0));
gtk_widget_set_size_request(border_bin_.get(), -1, kInfoBarHeight);
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
close_button_.reset(CustomDrawButton::AddBarCloseButton(hbox_, 0));
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
if (border_bin_.get()->window)
gdk_window_lower(border_bin_.get()->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
link_button_.reset(new LinkButtonGtk(WideToUTF8(link_text).c_str()));
g_signal_connect(link_button_->widget(), "clicked",
G_CALLBACK(OnLinkClick), this);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button_->widget(), FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), link_button_->widget(),
FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
// TODO(estade): we need an equivalent for DispositionFromEventFlags().
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(CURRENT_TAB)) {
link_info_bar->RemoveInfoBar();
}
}
// The clickable link text.
scoped_ptr<LinkButtonGtk> link_button_;
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
GtkWidget* centering_vbox = gtk_vbox_new(FALSE, 0);
gtk_box_pack_end(GTK_BOX(centering_vbox), button, TRUE, FALSE, 0);
gtk_box_pack_end(GTK_BOX(hbox_), centering_vbox, FALSE, FALSE, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
|
Set infobar text to black (overriding system default color).
|
Set infobar text to black (overriding system default color).
Since we set the background color, we can't go letting the theme choose the text color unless we want to potentially end up with white on yellow.
Review URL: http://codereview.chromium.org/108034
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@15320 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
pozdnyakov/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,robclark/chromium,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,dednal/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,robclark/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,keishi/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,rogerwang/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,Chilledheart/chromium,keishi/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,robclark/chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dednal/chromium.src,ltilve/chromium,keishi/chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,ltilve/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,Chilledheart/chromium,dushu1203/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,rogerwang/chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,patrickm/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,timopulkkinen/BubbleFish,rogerwang/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,robclark/chromium,Chilledheart/chromium,zcbenz/cefode-chromium,keishi/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,robclark/chromium,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,ltilve/chromium,ltilve/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,dushu1203/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,robclark/chromium,robclark/chromium,ondra-novak/chromium.src,rogerwang/chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,dednal/chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,dednal/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,ltilve/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,Chilledheart/chromium,ltilve/chromium,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,keishi/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,littlstar/chromium.src,robclark/chromium,Just-D/chromium-1
|
4bafafbe624f1d56ff6a74c01efdea2ce39aca49
|
chrome/browser/net/cache_stats.cc
|
chrome/browser/net/cache_stats.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/cache_stats.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/timer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "net/url_request/url_request.h"
using content::BrowserThread;
using content::RenderViewHost;
using content::ResourceRequestInfo;
#if defined(COMPILER_GCC)
namespace BASE_HASH_NAMESPACE {
template <>
struct hash<const net::URLRequest*> {
std::size_t operator()(const net::URLRequest* value) const {
return reinterpret_cast<std::size_t>(value);
}
};
}
#endif
namespace {
bool GetRenderView(const net::URLRequest& request,
int* process_id, int* route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(&request);
if (!info)
return false;
return info->GetAssociatedRenderView(process_id, route_id);
}
void CallCacheStatsTabEventOnIOThread(
std::pair<int, int> render_view_id,
chrome_browser_net::CacheStats::TabEvent event,
IOThread* io_thread) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (io_thread)
io_thread->globals()->cache_stats->OnTabEvent(render_view_id, event);
}
// Times after a load has started at which stats are collected.
const int kStatsCollectionTimesMs[] = {
500,
1000,
2000,
3000,
4000,
5000,
7500,
10000,
15000,
20000
};
static int kTabLoadStatsAutoCleanupTimeoutSeconds = 30;
} // namespace
namespace chrome_browser_net {
// Helper struct keeping stats about the page load progress & cache usage
// stats during the pageload so far for a given RenderView, identified
// by a pair of process id and route id.
struct CacheStats::TabLoadStats {
TabLoadStats(std::pair<int, int> render_view_id, CacheStats* owner)
: render_view_id(render_view_id),
num_active(0),
spinner_started(false),
next_timer_index(0),
timer(false, false) {
// Initialize the timer to do an automatic cleanup. If a pageload is
// started for the TabLoadStats within that timeframe, CacheStats
// will start using the timer, thereby cancelling the cleanup.
// Once CacheStats starts the timer, the object is guaranteed to be
// destroyed eventually, so there is no more need for automatic cleanup at
// that point.
timer.Start(FROM_HERE,
base::TimeDelta::FromSeconds(
kTabLoadStatsAutoCleanupTimeoutSeconds),
base::Bind(&CacheStats::RemoveTabLoadStats,
base::Unretained(owner),
render_view_id));
}
std::pair<int, int> render_view_id;
int num_active;
bool spinner_started;
base::TimeTicks load_start_time;
base::TimeTicks cache_start_time;
base::TimeDelta cache_total_time;
int next_timer_index;
base::Timer timer;
// URLRequest's for which there are outstanding cache transactions.
base::hash_set<const net::URLRequest*> active_requests;
};
CacheStatsTabHelper::CacheStatsTabHelper(TabContents* tab)
: content::WebContentsObserver(tab->web_contents()),
cache_stats_(NULL) {
is_otr_profile_ = tab->profile()->IsOffTheRecord();
}
CacheStatsTabHelper::~CacheStatsTabHelper() {
}
void CacheStatsTabHelper::DidStartProvisionalLoadForFrame(
int64 frame_id,
bool is_main_frame,
const GURL& validated_url,
bool is_error_page,
content::RenderViewHost* render_view_host) {
if (!is_main_frame)
return;
if (!validated_url.SchemeIs("http"))
return;
NotifyCacheStats(CacheStats::SPINNER_START, render_view_host);
}
void CacheStatsTabHelper::DidStopLoading(RenderViewHost* render_view_host) {
NotifyCacheStats(CacheStats::SPINNER_STOP, render_view_host);
}
void CacheStatsTabHelper::NotifyCacheStats(
CacheStats::TabEvent event,
RenderViewHost* render_view_host) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (is_otr_profile_)
return;
int process_id = render_view_host->GetProcess()->GetID();
int route_id = render_view_host->GetRoutingID();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&CallCacheStatsTabEventOnIOThread,
std::pair<int, int>(process_id, route_id),
event,
base::Unretained(g_browser_process->io_thread())));
}
CacheStats::CacheStats() {
for (int i = 0;
i < static_cast<int>(arraysize(kStatsCollectionTimesMs));
i++) {
final_histograms_.push_back(
base::LinearHistogram::FactoryGet(
"CacheStats.FractionCacheUseFinalPLT_" +
base::IntToString(kStatsCollectionTimesMs[i]),
0, 101, 102, base::Histogram::kUmaTargetedHistogramFlag));
intermediate_histograms_.push_back(
base::LinearHistogram::FactoryGet(
"DiskCache.FractionCacheUseIntermediatePLT_" +
base::IntToString(kStatsCollectionTimesMs[i]),
0, 101, 102, base::Histogram::kNoFlags));
}
DCHECK_EQ(final_histograms_.size(), arraysize(kStatsCollectionTimesMs));
DCHECK_EQ(intermediate_histograms_.size(),
arraysize(kStatsCollectionTimesMs));
}
CacheStats::~CacheStats() {
STLDeleteValues(&tab_load_stats_);
}
CacheStats::TabLoadStats* CacheStats::GetTabLoadStats(
std::pair<int, int> render_view_id) {
TabLoadStatsMap::const_iterator it = tab_load_stats_.find(render_view_id);
if (it != tab_load_stats_.end())
return it->second;
TabLoadStats* new_tab_load_stats = new TabLoadStats(render_view_id, this);
tab_load_stats_[render_view_id] = new_tab_load_stats;
return new_tab_load_stats;
}
void CacheStats::RemoveTabLoadStats(std::pair<int, int> render_view_id) {
TabLoadStatsMap::iterator it = tab_load_stats_.find(render_view_id);
if (it != tab_load_stats_.end()) {
delete it->second;
tab_load_stats_.erase(it);
}
}
void CacheStats::OnCacheWaitStateChange(
const net::URLRequest& request,
net::NetworkDelegate::CacheWaitState state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (main_request_contexts_.count(request.context()) < 1)
return;
int process_id, route_id;
if (!GetRenderView(request, &process_id, &route_id))
return;
TabLoadStats* stats =
GetTabLoadStats(std::pair<int, int>(process_id, route_id));
bool newly_started = false;
bool newly_finished = false;
switch (state) {
case net::NetworkDelegate::CACHE_WAIT_STATE_START:
DCHECK(stats->active_requests.count(&request) == 0);
newly_started = true;
stats->active_requests.insert(&request);
break;
case net::NetworkDelegate::CACHE_WAIT_STATE_FINISH:
if (stats->active_requests.count(&request) > 0) {
stats->active_requests.erase(&request);
newly_finished = true;
}
break;
case net::NetworkDelegate::CACHE_WAIT_STATE_RESET:
if (stats->active_requests.count(&request) > 0) {
stats->active_requests.erase(&request);
newly_finished = true;
}
break;
}
DCHECK_GE(stats->num_active, 0);
if (newly_started) {
DCHECK(!newly_finished);
if (stats->num_active == 0) {
stats->cache_start_time = base::TimeTicks::Now();
}
stats->num_active++;
}
if (newly_finished) {
DCHECK(!newly_started);
if (stats->num_active == 1) {
stats->cache_total_time +=
base::TimeTicks::Now() - stats->cache_start_time;
}
stats->num_active--;
}
DCHECK_GE(stats->num_active, 0);
}
void CacheStats::OnTabEvent(std::pair<int, int> render_view_id,
TabEvent event) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
TabLoadStats* stats = GetTabLoadStats(render_view_id);
if (event == SPINNER_START) {
stats->spinner_started = true;
stats->cache_total_time = base::TimeDelta();
stats->cache_start_time = base::TimeTicks::Now();
stats->load_start_time = base::TimeTicks::Now();
stats->next_timer_index = 0;
ScheduleTimer(stats);
} else {
DCHECK_EQ(event, SPINNER_STOP);
if (stats->spinner_started) {
stats->spinner_started = false;
base::TimeDelta load_time =
base::TimeTicks::Now() - stats->load_start_time;
if (stats->num_active > 1)
stats->cache_total_time +=
base::TimeTicks::Now() - stats->cache_start_time;
RecordCacheFractionHistogram(load_time, stats->cache_total_time, true,
stats->next_timer_index);
}
RemoveTabLoadStats(render_view_id);
}
}
void CacheStats::ScheduleTimer(TabLoadStats* stats) {
int timer_index = stats->next_timer_index;
DCHECK(timer_index >= 0 &&
timer_index < static_cast<int>(arraysize(kStatsCollectionTimesMs)));
base::TimeDelta delta =
base::TimeDelta::FromMilliseconds(kStatsCollectionTimesMs[timer_index]);
delta -= base::TimeTicks::Now() - stats->load_start_time;
stats->timer.Start(FROM_HERE,
delta,
base::Bind(&CacheStats::TimerCallback,
base::Unretained(this),
base::Unretained(stats)));
}
void CacheStats::TimerCallback(TabLoadStats* stats) {
DCHECK(stats->spinner_started);
base::TimeDelta load_time = base::TimeTicks::Now() - stats->load_start_time;
base::TimeDelta cache_time = stats->cache_total_time;
if (stats->num_active > 1)
cache_time += base::TimeTicks::Now() - stats->cache_start_time;
RecordCacheFractionHistogram(load_time, cache_time, false,
stats->next_timer_index);
stats->next_timer_index++;
if (stats->next_timer_index <
static_cast<int>(arraysize(kStatsCollectionTimesMs))) {
ScheduleTimer(stats);
} else {
RemoveTabLoadStats(stats->render_view_id);
}
}
void CacheStats::RecordCacheFractionHistogram(base::TimeDelta elapsed,
base::TimeDelta cache_time,
bool is_load_done,
int timer_index) {
DCHECK(timer_index >= 0 &&
timer_index < static_cast<int>(arraysize(kStatsCollectionTimesMs)));
if (elapsed.InMilliseconds() <= 0)
return;
int64 cache_fraction_percentage =
100 * cache_time.InMilliseconds() / elapsed.InMilliseconds();
DCHECK(cache_fraction_percentage >= 0 && cache_fraction_percentage <= 100);
if (is_load_done) {
final_histograms_[timer_index]->Add(cache_fraction_percentage);
} else {
intermediate_histograms_[timer_index]->Add(cache_fraction_percentage);
}
}
void CacheStats::RegisterURLRequestContext(
const net::URLRequestContext* context,
ChromeURLRequestContext::ContextType type) {
if (type == ChromeURLRequestContext::CONTEXT_TYPE_MAIN)
main_request_contexts_.insert(context);
}
void CacheStats::UnregisterURLRequestContext(
const net::URLRequestContext* context) {
main_request_contexts_.erase(context);
}
} // namespace chrome_browser_net
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/cache_stats.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/timer.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h"
#include "net/url_request/url_request.h"
using content::BrowserThread;
using content::RenderViewHost;
using content::ResourceRequestInfo;
#if defined(COMPILER_GCC)
namespace BASE_HASH_NAMESPACE {
template <>
struct hash<const net::URLRequest*> {
std::size_t operator()(const net::URLRequest* value) const {
return reinterpret_cast<std::size_t>(value);
}
};
}
#endif
namespace {
bool GetRenderView(const net::URLRequest& request,
int* process_id, int* route_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(&request);
if (!info)
return false;
return info->GetAssociatedRenderView(process_id, route_id);
}
void CallCacheStatsTabEventOnIOThread(
std::pair<int, int> render_view_id,
chrome_browser_net::CacheStats::TabEvent event,
IOThread* io_thread) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (io_thread)
io_thread->globals()->cache_stats->OnTabEvent(render_view_id, event);
}
// Times after a load has started at which stats are collected.
const int kStatsCollectionTimesMs[] = {
500,
1000,
2000,
3000,
4000,
5000,
7500,
10000,
15000,
20000
};
static int kTabLoadStatsAutoCleanupTimeoutSeconds = 30;
} // namespace
namespace chrome_browser_net {
// Helper struct keeping stats about the page load progress & cache usage
// stats during the pageload so far for a given RenderView, identified
// by a pair of process id and route id.
struct CacheStats::TabLoadStats {
TabLoadStats(std::pair<int, int> render_view_id, CacheStats* owner)
: render_view_id(render_view_id),
num_active(0),
spinner_started(false),
next_timer_index(0),
timer(false, false) {
// Initialize the timer to do an automatic cleanup. If a pageload is
// started for the TabLoadStats within that timeframe, CacheStats
// will start using the timer, thereby cancelling the cleanup.
// Once CacheStats starts the timer, the object is guaranteed to be
// destroyed eventually, so there is no more need for automatic cleanup at
// that point.
timer.Start(FROM_HERE,
base::TimeDelta::FromSeconds(
kTabLoadStatsAutoCleanupTimeoutSeconds),
base::Bind(&CacheStats::RemoveTabLoadStats,
base::Unretained(owner),
render_view_id));
}
std::pair<int, int> render_view_id;
int num_active;
bool spinner_started;
base::TimeTicks load_start_time;
base::TimeTicks cache_start_time;
base::TimeDelta cache_total_time;
int next_timer_index;
base::Timer timer;
// URLRequest's for which there are outstanding cache transactions.
base::hash_set<const net::URLRequest*> active_requests;
};
CacheStatsTabHelper::CacheStatsTabHelper(TabContents* tab)
: content::WebContentsObserver(tab->web_contents()),
cache_stats_(NULL) {
is_otr_profile_ = tab->profile()->IsOffTheRecord();
}
CacheStatsTabHelper::~CacheStatsTabHelper() {
}
void CacheStatsTabHelper::DidStartProvisionalLoadForFrame(
int64 frame_id,
bool is_main_frame,
const GURL& validated_url,
bool is_error_page,
content::RenderViewHost* render_view_host) {
if (!is_main_frame)
return;
if (!validated_url.SchemeIs("http"))
return;
NotifyCacheStats(CacheStats::SPINNER_START, render_view_host);
}
void CacheStatsTabHelper::DidStopLoading(RenderViewHost* render_view_host) {
NotifyCacheStats(CacheStats::SPINNER_STOP, render_view_host);
}
void CacheStatsTabHelper::NotifyCacheStats(
CacheStats::TabEvent event,
RenderViewHost* render_view_host) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (is_otr_profile_)
return;
int process_id = render_view_host->GetProcess()->GetID();
int route_id = render_view_host->GetRoutingID();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&CallCacheStatsTabEventOnIOThread,
std::pair<int, int>(process_id, route_id),
event,
base::Unretained(g_browser_process->io_thread())));
}
CacheStats::CacheStats() {
for (int i = 0;
i < static_cast<int>(arraysize(kStatsCollectionTimesMs));
i++) {
final_histograms_.push_back(
base::LinearHistogram::FactoryGet(
"CacheStats.FractionCacheUseFinalPLT_" +
base::IntToString(kStatsCollectionTimesMs[i]),
0, 101, 102, base::Histogram::kUmaTargetedHistogramFlag));
intermediate_histograms_.push_back(
base::LinearHistogram::FactoryGet(
"CacheStats.FractionCacheUseIntermediatePLT_" +
base::IntToString(kStatsCollectionTimesMs[i]),
0, 101, 102, base::Histogram::kUmaTargetedHistogramFlag));
}
DCHECK_EQ(final_histograms_.size(), arraysize(kStatsCollectionTimesMs));
DCHECK_EQ(intermediate_histograms_.size(),
arraysize(kStatsCollectionTimesMs));
}
CacheStats::~CacheStats() {
STLDeleteValues(&tab_load_stats_);
}
CacheStats::TabLoadStats* CacheStats::GetTabLoadStats(
std::pair<int, int> render_view_id) {
TabLoadStatsMap::const_iterator it = tab_load_stats_.find(render_view_id);
if (it != tab_load_stats_.end())
return it->second;
TabLoadStats* new_tab_load_stats = new TabLoadStats(render_view_id, this);
tab_load_stats_[render_view_id] = new_tab_load_stats;
return new_tab_load_stats;
}
void CacheStats::RemoveTabLoadStats(std::pair<int, int> render_view_id) {
TabLoadStatsMap::iterator it = tab_load_stats_.find(render_view_id);
if (it != tab_load_stats_.end()) {
delete it->second;
tab_load_stats_.erase(it);
}
}
void CacheStats::OnCacheWaitStateChange(
const net::URLRequest& request,
net::NetworkDelegate::CacheWaitState state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (main_request_contexts_.count(request.context()) < 1)
return;
int process_id, route_id;
if (!GetRenderView(request, &process_id, &route_id))
return;
TabLoadStats* stats =
GetTabLoadStats(std::pair<int, int>(process_id, route_id));
bool newly_started = false;
bool newly_finished = false;
switch (state) {
case net::NetworkDelegate::CACHE_WAIT_STATE_START:
DCHECK(stats->active_requests.count(&request) == 0);
newly_started = true;
stats->active_requests.insert(&request);
break;
case net::NetworkDelegate::CACHE_WAIT_STATE_FINISH:
if (stats->active_requests.count(&request) > 0) {
stats->active_requests.erase(&request);
newly_finished = true;
}
break;
case net::NetworkDelegate::CACHE_WAIT_STATE_RESET:
if (stats->active_requests.count(&request) > 0) {
stats->active_requests.erase(&request);
newly_finished = true;
}
break;
}
DCHECK_GE(stats->num_active, 0);
if (newly_started) {
DCHECK(!newly_finished);
if (stats->num_active == 0) {
stats->cache_start_time = base::TimeTicks::Now();
}
stats->num_active++;
}
if (newly_finished) {
DCHECK(!newly_started);
if (stats->num_active == 1) {
stats->cache_total_time +=
base::TimeTicks::Now() - stats->cache_start_time;
}
stats->num_active--;
}
DCHECK_GE(stats->num_active, 0);
}
void CacheStats::OnTabEvent(std::pair<int, int> render_view_id,
TabEvent event) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
TabLoadStats* stats = GetTabLoadStats(render_view_id);
if (event == SPINNER_START) {
stats->spinner_started = true;
stats->cache_total_time = base::TimeDelta();
stats->cache_start_time = base::TimeTicks::Now();
stats->load_start_time = base::TimeTicks::Now();
stats->next_timer_index = 0;
ScheduleTimer(stats);
} else {
DCHECK_EQ(event, SPINNER_STOP);
if (stats->spinner_started) {
stats->spinner_started = false;
base::TimeDelta load_time =
base::TimeTicks::Now() - stats->load_start_time;
if (stats->num_active > 1)
stats->cache_total_time +=
base::TimeTicks::Now() - stats->cache_start_time;
RecordCacheFractionHistogram(load_time, stats->cache_total_time, true,
stats->next_timer_index);
}
RemoveTabLoadStats(render_view_id);
}
}
void CacheStats::ScheduleTimer(TabLoadStats* stats) {
int timer_index = stats->next_timer_index;
DCHECK(timer_index >= 0 &&
timer_index < static_cast<int>(arraysize(kStatsCollectionTimesMs)));
base::TimeDelta delta =
base::TimeDelta::FromMilliseconds(kStatsCollectionTimesMs[timer_index]);
delta -= base::TimeTicks::Now() - stats->load_start_time;
stats->timer.Start(FROM_HERE,
delta,
base::Bind(&CacheStats::TimerCallback,
base::Unretained(this),
base::Unretained(stats)));
}
void CacheStats::TimerCallback(TabLoadStats* stats) {
DCHECK(stats->spinner_started);
base::TimeDelta load_time = base::TimeTicks::Now() - stats->load_start_time;
base::TimeDelta cache_time = stats->cache_total_time;
if (stats->num_active > 1)
cache_time += base::TimeTicks::Now() - stats->cache_start_time;
RecordCacheFractionHistogram(load_time, cache_time, false,
stats->next_timer_index);
stats->next_timer_index++;
if (stats->next_timer_index <
static_cast<int>(arraysize(kStatsCollectionTimesMs))) {
ScheduleTimer(stats);
} else {
RemoveTabLoadStats(stats->render_view_id);
}
}
void CacheStats::RecordCacheFractionHistogram(base::TimeDelta elapsed,
base::TimeDelta cache_time,
bool is_load_done,
int timer_index) {
DCHECK(timer_index >= 0 &&
timer_index < static_cast<int>(arraysize(kStatsCollectionTimesMs)));
if (elapsed.InMilliseconds() <= 0)
return;
int64 cache_fraction_percentage =
100 * cache_time.InMilliseconds() / elapsed.InMilliseconds();
DCHECK(cache_fraction_percentage >= 0 && cache_fraction_percentage <= 100);
if (is_load_done) {
final_histograms_[timer_index]->Add(cache_fraction_percentage);
} else {
intermediate_histograms_[timer_index]->Add(cache_fraction_percentage);
}
}
void CacheStats::RegisterURLRequestContext(
const net::URLRequestContext* context,
ChromeURLRequestContext::ContextType type) {
if (type == ChromeURLRequestContext::CONTEXT_TYPE_MAIN)
main_request_contexts_.insert(context);
}
void CacheStats::UnregisterURLRequestContext(
const net::URLRequestContext* context) {
main_request_contexts_.erase(context);
}
} // namespace chrome_browser_net
|
Fix CacheStats histogram name. [email protected] Review URL: https://chromiumcodereview.appspot.com/10829113
|
Fix CacheStats histogram name.
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10829113
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@149339 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,littlstar/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,dushu1203/chromium.src,jaruba/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,dednal/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,ltilve/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,ondra-novak/chromium.src,Just-D/chromium-1,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,hujiajie/pa-chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,dednal/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,Jonekee/chromium.src,Just-D/chromium-1,ltilve/chromium,jaruba/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,Just-D/chromium-1,Chilledheart/chromium,littlstar/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,M4sse/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,Jonekee/chromium.src,Chilledheart/chromium,anirudhSK/chromium,dednal/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,ltilve/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Chilledheart/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk
|
888baff5b4265625d15ec74b4394b351cf2ec776
|
chrome/renderer/blocked_plugin.cc
|
chrome/renderer/blocked_plugin.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/renderer/blocked_plugin.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_piece.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"
using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;
static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;
BlockedPlugin::BlockedPlugin(RenderView* render_view,
WebFrame* frame,
const webkit::npapi::PluginGroup& info,
const WebPluginParams& params,
const WebPreferences& preferences,
int template_id,
const string16& message)
: RenderViewObserver(render_view),
frame_(frame),
plugin_params_(params),
custom_menu_showing_(false) {
const base::StringPiece template_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));
DCHECK(!template_html.empty()) << "unable to load template. ID: "
<< template_id;
DictionaryValue values;
values.SetString("message", message);
name_ = info.GetGroupName();
values.SetString("name", name_);
// "t" is the id of the templates root node.
std::string html_data = jstemplate_builder::GetTemplatesHtml(
template_html, &values, "t");
plugin_ = webkit::npapi::WebViewPlugin::Create(this,
preferences,
html_data,
GURL(kBlockedPluginDataURL));
}
BlockedPlugin::~BlockedPlugin() {
}
void BlockedPlugin::BindWebFrame(WebFrame* frame) {
BindToJavascript(frame, "plugin");
BindMethod("load", &BlockedPlugin::Load);
BindMethod("hide", &BlockedPlugin::Hide);
}
void BlockedPlugin::WillDestroyPlugin() {
delete this;
}
void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
WebContextMenuData menu_data;
WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));
WebMenuItemInfo name_item;
name_item.label = name_;
custom_items[0] = name_item;
WebMenuItemInfo separator_item;
separator_item.type = WebMenuItemInfo::Separator;
custom_items[1] = separator_item;
WebMenuItemInfo run_item;
run_item.action = kMenuActionLoad;
run_item.enabled = true;
run_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
custom_items[2] = run_item;
WebMenuItemInfo hide_item;
hide_item.action = kMenuActionRemove;
hide_item.enabled = true;
hide_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
custom_items[3] = hide_item;
menu_data.customItems.swap(custom_items);
menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
render_view()->showContextMenu(NULL, menu_data);
custom_menu_showing_ = true;
}
bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
if (custom_menu_showing_ &&
message.type() == ViewMsg_CustomContextMenuAction::ID) {
ViewMsg_CustomContextMenuAction::Dispatch(
&message, this, this, &BlockedPlugin::OnMenuItemSelected);
return true;
}
// Don't want to swallow these messages.
if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
LoadPlugin();
} else if (message.type() == ViewMsg_ContextMenuClosed::ID) {
custom_menu_showing_ = false;
}
return false;
}
void BlockedPlugin::OnMenuItemSelected(unsigned id) {
if (id == kMenuActionLoad) {
LoadPlugin();
} else if (id == kMenuActionRemove) {
HidePlugin();
} else {
NOTREACHED();
}
}
void BlockedPlugin::LoadPlugin() {
CHECK(plugin_);
WebPluginContainer* container = plugin_->container();
WebPlugin* new_plugin =
render_view()->CreatePluginNoCheck(frame_, plugin_params_);
if (new_plugin && new_plugin->initialize(container)) {
container->setPlugin(new_plugin);
container->invalidate();
container->reportGeometry();
plugin_->ReplayReceivedData(new_plugin);
plugin_->destroy();
}
}
void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
LoadPlugin();
}
void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
HidePlugin();
}
void BlockedPlugin::HidePlugin() {
CHECK(plugin_);
WebPluginContainer* container = plugin_->container();
WebElement element = container->element();
element.setAttribute("style", "display: none;");
// If we have a width and height, search for a parent (often <div>) with the
// same dimensions. If we find such a parent, hide that as well.
// This makes much more uncovered page content usable (including clickable)
// as opposed to merely visible.
// TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
// now for these reasons:
// 1) Makes the user experience better.
// 2) Foulness is encapsulated within this single function.
// 3) Confidence in no fasle positives.
// 4) Seems to have a good / low false negative rate at this time.
if (element.hasAttribute("width") && element.hasAttribute("height")) {
std::string width_str("width:[\\s]*");
width_str += element.getAttribute("width").utf8().data();
width_str += "[\\s]*px";
WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
WebKit::WebTextCaseSensitive);
std::string height_str("height:[\\s]*");
height_str += element.getAttribute("height").utf8().data();
height_str += "[\\s]*px";
WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
WebKit::WebTextCaseSensitive);
WebNode parent = element;
while (!parent.parentNode().isNull()) {
parent = parent.parentNode();
if (!parent.isElementNode())
continue;
element = parent.toConst<WebElement>();
if (element.hasAttribute("style")) {
WebString style_str = element.getAttribute("style");
if (width_regex.match(style_str) >= 0 &&
height_regex.match(style_str) >= 0)
element.setAttribute("style", "display: none;");
}
}
}
}
|
// 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/renderer/blocked_plugin.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_view.h"
#include "grit/generated_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMenuItemInfo.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRegularExpression.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextCaseSensitivity.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebVector.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/webview_plugin.h"
using WebKit::WebContextMenuData;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebMenuItemInfo;
using WebKit::WebNode;
using WebKit::WebPlugin;
using WebKit::WebPluginContainer;
using WebKit::WebPluginParams;
using WebKit::WebPoint;
using WebKit::WebRegularExpression;
using WebKit::WebString;
using WebKit::WebVector;
static const char* const kBlockedPluginDataURL = "chrome://blockedplugindata/";
static const unsigned kMenuActionLoad = 1;
static const unsigned kMenuActionRemove = 2;
BlockedPlugin::BlockedPlugin(RenderView* render_view,
WebFrame* frame,
const webkit::npapi::PluginGroup& info,
const WebPluginParams& params,
const WebPreferences& preferences,
int template_id,
const string16& message)
: RenderViewObserver(render_view),
frame_(frame),
plugin_params_(params),
custom_menu_showing_(false) {
const base::StringPiece template_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(template_id));
DCHECK(!template_html.empty()) << "unable to load template. ID: "
<< template_id;
DictionaryValue values;
values.SetString("message", message);
name_ = info.GetGroupName();
values.SetString("name", name_);
// "t" is the id of the templates root node.
std::string html_data = jstemplate_builder::GetTemplatesHtml(
template_html, &values, "t");
plugin_ = webkit::npapi::WebViewPlugin::Create(this,
preferences,
html_data,
GURL(kBlockedPluginDataURL));
}
BlockedPlugin::~BlockedPlugin() {
}
void BlockedPlugin::BindWebFrame(WebFrame* frame) {
BindToJavascript(frame, "plugin");
BindMethod("load", &BlockedPlugin::Load);
BindMethod("hide", &BlockedPlugin::Hide);
}
void BlockedPlugin::WillDestroyPlugin() {
delete this;
}
void BlockedPlugin::ShowContextMenu(const WebKit::WebMouseEvent& event) {
WebContextMenuData menu_data;
WebVector<WebMenuItemInfo> custom_items(static_cast<size_t>(4));
WebMenuItemInfo name_item;
name_item.label = name_;
custom_items[0] = name_item;
WebMenuItemInfo separator_item;
separator_item.type = WebMenuItemInfo::Separator;
custom_items[1] = separator_item;
WebMenuItemInfo run_item;
run_item.action = kMenuActionLoad;
run_item.enabled = true;
run_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_RUN).c_str());
custom_items[2] = run_item;
WebMenuItemInfo hide_item;
hide_item.action = kMenuActionRemove;
hide_item.enabled = true;
hide_item.label = WebString::fromUTF8(
l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_PLUGIN_HIDE).c_str());
custom_items[3] = hide_item;
menu_data.customItems.swap(custom_items);
menu_data.mousePosition = WebPoint(event.windowX, event.windowY);
render_view()->showContextMenu(NULL, menu_data);
custom_menu_showing_ = true;
}
bool BlockedPlugin::OnMessageReceived(const IPC::Message& message) {
if (custom_menu_showing_ &&
message.type() == ViewMsg_CustomContextMenuAction::ID) {
ViewMsg_CustomContextMenuAction::Dispatch(
&message, this, this, &BlockedPlugin::OnMenuItemSelected);
return true;
}
// Don't want to swallow these messages.
if (message.type() == ViewMsg_LoadBlockedPlugins::ID) {
LoadPlugin();
} else if (message.type() == ViewMsg_ContextMenuClosed::ID) {
custom_menu_showing_ = false;
}
return false;
}
void BlockedPlugin::OnMenuItemSelected(unsigned id) {
if (id == kMenuActionLoad) {
LoadPlugin();
} else if (id == kMenuActionRemove) {
HidePlugin();
} else {
NOTREACHED();
}
}
void BlockedPlugin::LoadPlugin() {
CHECK(plugin_);
WebPluginContainer* container = plugin_->container();
WebPlugin* new_plugin =
render_view()->CreatePluginNoCheck(frame_, plugin_params_);
if (new_plugin && new_plugin->initialize(container)) {
container->setPlugin(new_plugin);
container->invalidate();
container->reportGeometry();
plugin_->ReplayReceivedData(new_plugin);
plugin_->destroy();
}
}
void BlockedPlugin::Load(const CppArgumentList& args, CppVariant* result) {
LoadPlugin();
}
void BlockedPlugin::Hide(const CppArgumentList& args, CppVariant* result) {
HidePlugin();
}
void BlockedPlugin::HidePlugin() {
CHECK(plugin_);
WebPluginContainer* container = plugin_->container();
WebElement element = container->element();
element.setAttribute("style", "display: none;");
// If we have a width and height, search for a parent (often <div>) with the
// same dimensions. If we find such a parent, hide that as well.
// This makes much more uncovered page content usable (including clickable)
// as opposed to merely visible.
// TODO(cevans) -- it's a foul heurisitc but we're going to tolerate it for
// now for these reasons:
// 1) Makes the user experience better.
// 2) Foulness is encapsulated within this single function.
// 3) Confidence in no fasle positives.
// 4) Seems to have a good / low false negative rate at this time.
if (element.hasAttribute("width") && element.hasAttribute("height")) {
std::string width_str("width:[\\s]*");
width_str += element.getAttribute("width").utf8().data();
if (EndsWith(width_str, "px", false)) {
width_str = width_str.substr(0, width_str.length() - 2);
}
TrimWhitespace(width_str, TRIM_TRAILING, &width_str);
width_str += "[\\s]*px";
WebRegularExpression width_regex(WebString::fromUTF8(width_str.c_str()),
WebKit::WebTextCaseSensitive);
std::string height_str("height:[\\s]*");
height_str += element.getAttribute("height").utf8().data();
if (EndsWith(height_str, "px", false)) {
height_str = height_str.substr(0, height_str.length() - 2);
}
TrimWhitespace(height_str, TRIM_TRAILING, &height_str);
height_str += "[\\s]*px";
WebRegularExpression height_regex(WebString::fromUTF8(height_str.c_str()),
WebKit::WebTextCaseSensitive);
WebNode parent = element;
while (!parent.parentNode().isNull()) {
parent = parent.parentNode();
if (!parent.isElementNode())
continue;
element = parent.toConst<WebElement>();
if (element.hasAttribute("style")) {
WebString style_str = element.getAttribute("style");
if (width_regex.match(style_str) >= 0 &&
height_regex.match(style_str) >= 0)
element.setAttribute("style", "display: none;");
}
}
}
}
|
Tweak heuristic to hide fixed-size parent <div>s for one more case.
|
Tweak heuristic to hide fixed-size parent <div>s for one more case.
BUG=http://code.google.com/p/chromium/issues/detail?id=63695
TEST=http://www.zontera.com/banners/clients_work/floating_flash/centered/dove/
Review URL: http://codereview.chromium.org/6266009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@71761 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,Chilledheart/chromium,keishi/chromium,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,rogerwang/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,dednal/chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,ChromiumWebApps/chromium,keishi/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,M4sse/chromium.src,keishi/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,robclark/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,robclark/chromium,dednal/chromium.src,M4sse/chromium.src,rogerwang/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,robclark/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,ltilve/chromium,anirudhSK/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,patrickm/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,robclark/chromium,rogerwang/chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,keishi/chromium,fujunwei/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,markYoungH/chromium.src,dednal/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,dednal/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,ltilve/chromium,patrickm/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,keishi/chromium,M4sse/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,keishi/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,ltilve/chromium,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,rogerwang/chromium,jaruba/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,keishi/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,Just-D/chromium-1,nacl-webkit/chrome_deps,rogerwang/chromium,dednal/chromium.src,littlstar/chromium.src,rogerwang/chromium,nacl-webkit/chrome_deps,dednal/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,robclark/chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,markYoungH/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,robclark/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,littlstar/chromium.src
|
2cd2bdff2124eeb3c2980f829d6577e784a22608
|
lib/primesieve/src/PrimeGenerator.cpp
|
lib/primesieve/src/PrimeGenerator.cpp
|
///
/// @file PrimeGenerator.cpp
/// Generates the primes inside [start, stop] and stores them
/// in a vector. After the primes have been stored in the
/// vector primesieve::iterator iterates over the vector and
/// returns the primes. When there are no more primes left in
/// the vector PrimeGenerator generates new primes.
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/Erat.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/SievingPrimes.hpp>
#include <primesieve/types.hpp>
#include <stdint.h>
#include <algorithm>
#include <array>
#include <vector>
using namespace std;
namespace primesieve {
/// First 64 primes
const array<uint64_t, 64> PrimeGenerator::smallPrimes =
{
2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263,
269, 271, 277, 281, 283, 293, 307, 311
};
/// Number of primes <= n
const array<uint8_t, 312> PrimeGenerator::primePi =
{
0, 0, 1, 2, 2, 3, 3, 4, 4, 4,
4, 5, 5, 6, 6, 6, 6, 7, 7, 8,
8, 8, 8, 9, 9, 9, 9, 9, 9, 10,
10, 11, 11, 11, 11, 11, 11, 12, 12, 12,
12, 13, 13, 14, 14, 14, 14, 15, 15, 15,
15, 15, 15, 16, 16, 16, 16, 16, 16, 17,
17, 18, 18, 18, 18, 18, 18, 19, 19, 19,
19, 20, 20, 21, 21, 21, 21, 21, 21, 22,
22, 22, 22, 23, 23, 23, 23, 23, 23, 24,
24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
25, 26, 26, 27, 27, 27, 27, 28, 28, 29,
29, 29, 29, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 31, 31, 31,
31, 32, 32, 32, 32, 32, 32, 33, 33, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 35,
35, 36, 36, 36, 36, 36, 36, 37, 37, 37,
37, 37, 37, 38, 38, 38, 38, 39, 39, 39,
39, 39, 39, 40, 40, 40, 40, 40, 40, 41,
41, 42, 42, 42, 42, 42, 42, 42, 42, 42,
42, 43, 43, 44, 44, 44, 44, 45, 45, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 47, 47, 47, 47, 47, 47, 47, 47, 47,
47, 47, 47, 48, 48, 48, 48, 49, 49, 50,
50, 50, 50, 51, 51, 51, 51, 51, 51, 52,
52, 53, 53, 53, 53, 53, 53, 53, 53, 53,
53, 54, 54, 54, 54, 54, 54, 55, 55, 55,
55, 55, 55, 56, 56, 56, 56, 56, 56, 57,
57, 58, 58, 58, 58, 58, 58, 59, 59, 59,
59, 60, 60, 61, 61, 61, 61, 61, 61, 61,
61, 61, 61, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 63, 63, 63,
63, 64
};
PrimeGenerator::PrimeGenerator(uint64_t start, uint64_t stop) :
Erat(start, stop),
preSieve_(start, stop)
{ }
void PrimeGenerator::init()
{
// sieving is used > max(SmallPrime)
uint64_t sieving = smallPrimes.back() + 1;
uint64_t sieveSize = get_sieve_size();
start_ = max(start_, sieving);
Erat::init(start_, stop_, sieveSize, preSieve_);
sievingPrimes_.init(this, preSieve_);
isInit_ = true;
}
size_t PrimeGenerator::getStartIdx() const
{
size_t startIdx = 0;
if (start_ > 1)
startIdx = primePi[start_ - 1];
return startIdx;
}
size_t PrimeGenerator::getStopIdx() const
{
size_t stopIdx = 0;
if (stop_ < smallPrimes.back())
stopIdx = primePi[stop_];
else
stopIdx = smallPrimes.size();
return stopIdx;
}
void PrimeGenerator::init(vector<uint64_t>& primes)
{
size_t size = primeCountApprox(start_, stop_);
primes.reserve(size);
if (start_ <= smallPrimes.back())
{
size_t a = getStartIdx();
size_t b = getStopIdx();
primes.insert(primes.end(),
smallPrimes.begin() + a,
smallPrimes.begin() + b);
}
init();
}
void PrimeGenerator::init(vector<uint64_t>& primes, size_t* size)
{
if (start_ <= smallPrimes.back())
{
size_t a = getStartIdx();
size_t b = getStopIdx();
*size = b - a;
copy(smallPrimes.begin() + a,
smallPrimes.begin() + b,
primes.begin());
}
init();
}
bool PrimeGenerator::sieveSegment(vector<uint64_t>& primes)
{
if (!isInit_)
init(primes);
if (!hasNextSegment())
return false;
sieveSegment();
return true;
}
bool PrimeGenerator::sieveSegment(vector<uint64_t>& primes, size_t* size)
{
if (!isInit_)
{
init(primes, size);
if (*size > 0)
return false;
}
if (!hasNextSegment())
{
*size = 1;
primes[0] = ~0ull;
finished_ = (primes[0] > stop_);
return false;
}
sieveSegment();
return true;
}
void PrimeGenerator::sieveSegment()
{
uint64_t sqrtHigh = isqrt(segmentHigh_);
sieveIdx_ = 0;
low_ = segmentLow_;
if (!prime_)
prime_ = sievingPrimes_.next();
while (prime_ <= sqrtHigh)
{
addSievingPrime(prime_);
prime_ = sievingPrimes_.next();
}
Erat::sieveSegment();
}
void PrimeGenerator::fill(vector<uint64_t>& primes)
{
while (true)
{
if (sieveIdx_ >= sieveSize_)
if (!sieveSegment(primes))
return;
auto bits = littleendian_cast<uint64_t>(&sieve_[sieveIdx_]);
sieveIdx_ += 8;
while (bits)
{
auto prime = nextPrime(&bits, low_);
primes.push_back(prime);
}
low_ += 8 * 30;
}
}
} // namespace
|
///
/// @file PrimeGenerator.cpp
/// Generates the primes inside [start, stop] and stores them
/// in a vector. After the primes have been stored in the
/// vector primesieve::iterator iterates over the vector and
/// returns the primes. When there are no more primes left in
/// the vector PrimeGenerator generates new primes.
///
/// Copyright (C) 2018 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/Erat.hpp>
#include <primesieve/PreSieve.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <primesieve/pmath.hpp>
#include <primesieve/SievingPrimes.hpp>
#include <primesieve/types.hpp>
#include <stdint.h>
#include <algorithm>
#include <array>
#include <vector>
using namespace std;
namespace primesieve {
/// First 64 primes
const array<uint64_t, 64> PrimeGenerator::smallPrimes =
{
2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131,
137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223,
227, 229, 233, 239, 241, 251, 257, 263,
269, 271, 277, 281, 283, 293, 307, 311
};
/// Number of primes <= n
const array<uint8_t, 312> PrimeGenerator::primePi =
{
0, 0, 1, 2, 2, 3, 3, 4, 4, 4,
4, 5, 5, 6, 6, 6, 6, 7, 7, 8,
8, 8, 8, 9, 9, 9, 9, 9, 9, 10,
10, 11, 11, 11, 11, 11, 11, 12, 12, 12,
12, 13, 13, 14, 14, 14, 14, 15, 15, 15,
15, 15, 15, 16, 16, 16, 16, 16, 16, 17,
17, 18, 18, 18, 18, 18, 18, 19, 19, 19,
19, 20, 20, 21, 21, 21, 21, 21, 21, 22,
22, 22, 22, 23, 23, 23, 23, 23, 23, 24,
24, 24, 24, 24, 24, 24, 24, 25, 25, 25,
25, 26, 26, 27, 27, 27, 27, 28, 28, 29,
29, 29, 29, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 31, 31, 31,
31, 32, 32, 32, 32, 32, 32, 33, 33, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 35,
35, 36, 36, 36, 36, 36, 36, 37, 37, 37,
37, 37, 37, 38, 38, 38, 38, 39, 39, 39,
39, 39, 39, 40, 40, 40, 40, 40, 40, 41,
41, 42, 42, 42, 42, 42, 42, 42, 42, 42,
42, 43, 43, 44, 44, 44, 44, 45, 45, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 47, 47, 47, 47, 47, 47, 47, 47, 47,
47, 47, 47, 48, 48, 48, 48, 49, 49, 50,
50, 50, 50, 51, 51, 51, 51, 51, 51, 52,
52, 53, 53, 53, 53, 53, 53, 53, 53, 53,
53, 54, 54, 54, 54, 54, 54, 55, 55, 55,
55, 55, 55, 56, 56, 56, 56, 56, 56, 57,
57, 58, 58, 58, 58, 58, 58, 59, 59, 59,
59, 60, 60, 61, 61, 61, 61, 61, 61, 61,
61, 61, 61, 62, 62, 62, 62, 62, 62, 62,
62, 62, 62, 62, 62, 62, 62, 63, 63, 63,
63, 64
};
PrimeGenerator::PrimeGenerator(uint64_t start, uint64_t stop) :
Erat(start, stop),
preSieve_(start, stop)
{ }
void PrimeGenerator::init()
{
// sieving is used > max(SmallPrime)
uint64_t sieving = smallPrimes.back() + 1;
uint64_t sieveSize = get_sieve_size();
start_ = max(start_, sieving);
Erat::init(start_, stop_, sieveSize, preSieve_);
sievingPrimes_.init(this, preSieve_);
isInit_ = true;
}
size_t PrimeGenerator::getStartIdx() const
{
size_t startIdx = 0;
if (start_ > 1)
startIdx = primePi[start_ - 1];
return startIdx;
}
size_t PrimeGenerator::getStopIdx() const
{
size_t stopIdx = 0;
if (stop_ < smallPrimes.back())
stopIdx = primePi[stop_];
else
stopIdx = smallPrimes.size();
return stopIdx;
}
void PrimeGenerator::init(vector<uint64_t>& primes)
{
size_t size = primeCountApprox(start_, stop_);
primes.reserve(size);
if (start_ <= smallPrimes.back())
{
size_t a = getStartIdx();
size_t b = getStopIdx();
primes.insert(primes.end(),
smallPrimes.begin() + a,
smallPrimes.begin() + b);
}
init();
}
void PrimeGenerator::init(vector<uint64_t>& primes, size_t* size)
{
if (start_ <= smallPrimes.back())
{
size_t a = getStartIdx();
size_t b = getStopIdx();
*size = b - a;
copy(smallPrimes.begin() + a,
smallPrimes.begin() + b,
primes.begin());
}
init();
}
bool PrimeGenerator::sieveSegment(vector<uint64_t>& primes)
{
if (!isInit_)
init(primes);
if (!hasNextSegment())
return false;
sieveSegment();
return true;
}
bool PrimeGenerator::sieveSegment(vector<uint64_t>& primes, size_t* size)
{
if (!isInit_)
{
init(primes, size);
if (*size > 0)
return false;
}
if (!hasNextSegment())
{
*size = 1;
primes[0] = ~0ull;
finished_ = (primes[0] > stop_);
return false;
}
sieveSegment();
return true;
}
void PrimeGenerator::sieveSegment()
{
uint64_t sqrtHigh = isqrt(segmentHigh_);
sieveIdx_ = 0;
low_ = segmentLow_;
if (!prime_)
prime_ = sievingPrimes_.next();
while (prime_ <= sqrtHigh)
{
addSievingPrime(prime_);
prime_ = sievingPrimes_.next();
}
Erat::sieveSegment();
}
void PrimeGenerator::fill(vector<uint64_t>& primes)
{
while (sieveSegment(primes))
{
for (; sieveIdx_ < sieveSize_; sieveIdx_ += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve_[sieveIdx_]);
while (bits)
primes.push_back(nextPrime(&bits, low_));
low_ += 8 * 30;
}
}
}
} // namespace
|
Update to latest libprimesieve
|
Update to latest libprimesieve
|
C++
|
bsd-2-clause
|
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
|
8e73e1165cef2ae8986b566eac6a679c9062864e
|
Tensile/Source/lib/include/Tensile/TensorDescriptor.hpp
|
Tensile/Source/lib/include/Tensile/TensorDescriptor.hpp
|
/*******************************************************************************
*
* MIT License
*
* Copyright 2019-2020 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include <cassert>
#include <algorithm>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
#include <Tensile/DataTypes.hpp>
#include <Tensile/Debug.hpp>
#include <Tensile/Macros.hpp>
#include <Tensile/Utils.hpp>
namespace Tensile
{
template <typename SizeIter>
inline size_t CoordCount(SizeIter sizeBegin, SizeIter sizeEnd)
{
size_t rv = 1;
while(sizeBegin != sizeEnd)
{
rv *= *sizeBegin;
sizeBegin++;
}
return rv;
}
template <typename CoordIter, typename SizeIter>
inline void CoordNumbered(
size_t num, CoordIter coordBegin, CoordIter coordEnd, SizeIter sizeBegin, SizeIter sizeEnd)
{
auto coord = coordBegin;
auto size = sizeBegin;
while(coord != coordEnd && size != sizeEnd)
{
*coord = num % *size;
num /= *size;
coord++;
size++;
}
if(coord != coordEnd || size != sizeEnd)
throw std::runtime_error("Inconsistent size of coordinates.");
}
template <typename CoordIter, typename SizeIter>
inline bool IncrementCoord(CoordIter coordBegin,
CoordIter coordEnd,
SizeIter sizeBegin,
SizeIter sizeEnd)
{
auto coord = coordBegin;
auto size = sizeBegin;
while(coord != coordEnd)
{
(*coord)++;
if(*coord < *size)
return true;
*coord = 0;
coord++;
size++;
}
return false;
}
/**
* Describes a tensor including dimensions, memory layout, and data type.
* Decoupled from any particular pointer value or memory location.
*
* Provides functions for indexing and otherwise iterating through a tensor.
*/
class TENSILE_API TensorDescriptor
{
public:
static const size_t UseDefaultStride;
TensorDescriptor()
{
this->calculate();
}
template <typename IterA, typename IterB>
TensorDescriptor(
DataType t, IterA sizesBegin, IterA sizesEnd, IterB stridesBegin, IterB stridesEnd)
: m_sizes(sizesBegin, sizesEnd)
, m_strides(stridesBegin, stridesEnd)
, m_dataType(t)
{
this->calculate();
}
template <typename Iter>
TensorDescriptor(DataType t, Iter sizesBegin, Iter sizesEnd)
: m_sizes(sizesBegin, sizesEnd)
, m_dataType(t)
{
this->calculate();
}
TensorDescriptor(DataType t, std::initializer_list<size_t> sizes)
: m_sizes(sizes)
, m_dataType(t)
{
this->calculate();
}
TensorDescriptor(DataType t,
std::initializer_list<size_t> sizes,
std::initializer_list<size_t> strides)
: m_sizes(sizes)
, m_strides(strides)
, m_dataType(t)
{
this->calculate();
}
inline void calculate()
{
if(m_sizes.empty())
{
m_strides = m_sizes;
m_totalLogicalElements = 0;
m_totalAllocatedElements = 0;
return;
}
for(int i = 0; i < m_sizes.size(); i++)
{
TENSILE_ASSERT_EXC(m_sizes[i] > 0);
}
m_strides.resize(m_sizes.size(), UseDefaultStride);
if(m_strides[0] == UseDefaultStride)
{
m_strides[0] = 1;
}
m_totalLogicalElements = m_sizes[0];
for(int i = 1; i < m_sizes.size(); i++)
{
m_totalLogicalElements *= m_sizes[i];
if(m_strides[i] == UseDefaultStride)
{
m_strides[i] = m_strides[i - 1] * m_sizes[i - 1];
}
}
m_totalAllocatedElements = 1;
for(int i = 0; i < m_sizes.size(); i++)
m_totalAllocatedElements += m_strides[i] * (m_sizes[i] - 1);
if(Debug::Instance().printTensorInfo())
{
std::cout << "TensorDescriptor:calculate " << *this
<< "totalLogicalElements=" << m_totalLogicalElements
<< " totalAllocatedElem=" << m_totalAllocatedElements << "\n";
}
}
const std::vector<size_t>& sizes() const
{
return m_sizes;
}
const std::vector<size_t>& strides() const
{
return m_strides;
}
bool empty() const
{
return m_sizes.empty();
}
void appendDim(size_t logicalCount);
void appendDim(size_t logicalCount, size_t allocatedCount);
/**
* Returns the number of elements of padding in the given dimension (0 if
* unpadded). May be negative if stride is less than size
*/
int64_t dimensionPadding(size_t dim) const;
/**
* Collapses dimensions in the interval [begin, end).
*
* preconditions:
* - end >= begin
* - begin < dimensions()
* - end <= dimensions()
* - dimensions in the interval [begin, end-1) are not padded.
*
* postconditions:
* - dimensions() is diminished by end-begin
* - total elements (allocated and logical) remain the same
* - dimension 'begin' is the product of all the dimensions in the interval
* [begin, end).
*/
void collapseDims(size_t begin, size_t end);
size_t dimensions() const
{
return m_sizes.size();
}
size_t totalLogicalElements() const
{
return m_totalLogicalElements;
}
size_t totalAllocatedElements() const
{
return m_totalAllocatedElements;
}
size_t totalAllocatedBytes() const
{
return totalAllocatedElements() * elementBytes();
}
size_t elementBytes() const
{
return DataTypeInfo::Get(m_dataType).elementSize;
}
DataType dataType() const
{
return m_dataType;
}
template <typename Container>
inline size_t index(Container const& indices) const
{
if(indices.size() != dimensions())
throw std::runtime_error("Incorrect number of indices.");
for(int i = 0; i < indices.size(); i++)
if(indices[i] >= m_sizes[i])
throw std::runtime_error("Index out of bounds.");
return std::inner_product(indices.begin(), indices.end(), m_strides.begin(), size_t(0));
}
template <typename T>
inline size_t index(std::initializer_list<T> indices) const
{
if(indices.size() != dimensions())
throw std::runtime_error("Incorrect number of indices.");
for(auto i = std::make_pair(indices.begin(), m_sizes.begin()); i.first != indices.end();
i.first++, i.second++)
if(*i.first >= *i.second)
throw std::runtime_error("Index out of bounds.");
return std::inner_product(indices.begin(), indices.end(), m_strides.begin(), size_t(0));
}
template <class... Ts,
typename = typename std::enable_if<
std::is_integral<typename std::common_type<Ts...>::type>::value>::type>
inline size_t index(Ts... is) const
{
return this->index({is...});
}
inline bool incrementCoord(std::vector<size_t>& coord, size_t firstDimension = 0) const
{
if(coord.size() != dimensions())
throw std::runtime_error(concatenate(
"Invalid coordinate size ", coord.size(), " for ", dimensions(), "-tensor"));
if(firstDimension >= dimensions())
return false;
return IncrementCoord(
coord.begin() + firstDimension, coord.end(), m_sizes.begin(), m_sizes.end());
}
bool operator==(const TensorDescriptor& rhs) const;
bool operator!=(const TensorDescriptor& rhs) const;
std::string ToString() const;
friend std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t);
private:
std::vector<size_t> m_sizes;
std::vector<size_t> m_strides;
size_t m_totalLogicalElements = 0;
size_t m_totalAllocatedElements = 0;
DataType m_dataType = DataType::Float;
};
std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t);
template <typename T>
void WriteTensor1D(std::ostream& stream,
T* data,
TensorDescriptor const& desc,
bool decorated = true)
{
if(desc.dimensions() != 1)
throw std::runtime_error(
"WriteTensor1D is only compatible with 1-dimensional tensors.");
if(decorated)
stream << "[";
if(desc.sizes()[0] > 0)
stream << data[0];
for(size_t i = 1; i < desc.sizes()[0]; i++)
stream << " " << data[i];
if(decorated)
stream << "]" << std::endl;
}
/**
* @brief Writes a tensor to an output stream.
*
* \param stream The stream to write to
* \param data Pointer to the tensor data
* \param desc Tensor descriptor
* \param ptrValue Pointer value to print to describe the location of the data.
* \param decorated Print brackets [] to indicate start/end of tensor dims
*/
template <typename T>
void WriteTensor(std::ostream& stream,
T const* data,
TensorDescriptor const& desc,
T const* ptrValue = nullptr,
bool decorated = true)
{
stream << "Tensor(";
streamJoin(stream, desc.sizes(), ", ");
stream << ", data_ptr: " << data << ")" << std::endl;
if(desc.dimensions() == 0)
return;
if(desc.dimensions() == 1)
{
WriteTensor1D(stream, data, desc, decorated);
return;
}
auto const& sizes = desc.sizes();
std::vector<size_t> coord(desc.dimensions(), 0);
const auto stride0 = desc.strides()[0];
auto upperDimCount = CoordCount(sizes.begin() + 2, sizes.end());
for(size_t idx = 0; idx < upperDimCount; idx++)
{
CoordNumbered(idx, coord.begin() + 2, coord.end(), sizes.begin() + 2, sizes.end());
coord[0] = 0;
coord[1] = 0;
if(decorated)
{
stream << "(";
streamJoin(stream, coord, ", ");
stream << ")" << std::endl << "[" << std::endl;
}
for(coord[1] = 0; coord[1] < sizes[1]; coord[1]++)
{
coord[0] = 0;
auto const* localPtr = data + desc.index(coord);
if(sizes[0] > 0)
stream << localPtr[0];
for(coord[0] = 1; coord[0] < sizes[0]; coord[0]++)
{
stream << " " << localPtr[coord[0] * stride0];
}
stream << std::endl;
}
if(decorated)
{
stream << std::endl << "]" << std::endl;
}
}
}
} // namespace Tensile
|
/*******************************************************************************
*
* MIT License
*
* Copyright 2019-2020 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include <cassert>
#include <algorithm>
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
#include <Tensile/DataTypes.hpp>
#include <Tensile/Debug.hpp>
#include <Tensile/Macros.hpp>
#include <Tensile/Utils.hpp>
namespace Tensile
{
template <typename SizeIter>
inline size_t CoordCount(SizeIter sizeBegin, SizeIter sizeEnd)
{
size_t rv = 1;
while(sizeBegin != sizeEnd)
{
rv *= *sizeBegin;
sizeBegin++;
}
return rv;
}
template <typename CoordIter, typename SizeIter>
inline void CoordNumbered(
size_t num, CoordIter coordBegin, CoordIter coordEnd, SizeIter sizeBegin, SizeIter sizeEnd)
{
auto coord = coordBegin;
auto size = sizeBegin;
while(coord != coordEnd && size != sizeEnd)
{
*coord = num % *size;
num /= *size;
coord++;
size++;
}
if(coord != coordEnd || size != sizeEnd)
throw std::runtime_error("Inconsistent size of coordinates.");
}
template <typename CoordIter, typename SizeIter>
inline bool IncrementCoord(CoordIter coordBegin,
CoordIter coordEnd,
SizeIter sizeBegin,
SizeIter sizeEnd)
{
auto coord = coordBegin;
auto size = sizeBegin;
while(coord != coordEnd)
{
(*coord)++;
if(*coord < *size)
return true;
*coord = 0;
coord++;
size++;
}
return false;
}
/**
* Describes a tensor including dimensions, memory layout, and data type.
* Decoupled from any particular pointer value or memory location.
*
* Provides functions for indexing and otherwise iterating through a tensor.
*/
class TENSILE_API TensorDescriptor
{
public:
static const size_t UseDefaultStride;
TensorDescriptor()
{
this->calculate();
}
template <typename IterA, typename IterB>
TensorDescriptor(
DataType t, IterA sizesBegin, IterA sizesEnd, IterB stridesBegin, IterB stridesEnd)
: m_sizes(sizesBegin, sizesEnd)
, m_strides(stridesBegin, stridesEnd)
, m_dataType(t)
{
this->calculate();
}
template <typename Iter>
TensorDescriptor(DataType t, Iter sizesBegin, Iter sizesEnd)
: m_sizes(sizesBegin, sizesEnd)
, m_dataType(t)
{
this->calculate();
}
TensorDescriptor(DataType t, std::initializer_list<size_t> sizes)
: m_sizes(sizes)
, m_dataType(t)
{
this->calculate();
}
TensorDescriptor(DataType t,
std::initializer_list<size_t> sizes,
std::initializer_list<size_t> strides)
: m_sizes(sizes)
, m_strides(strides)
, m_dataType(t)
{
this->calculate();
}
inline void calculate()
{
if(m_sizes.empty())
{
m_strides = m_sizes;
m_totalLogicalElements = 0;
m_totalAllocatedElements = 0;
return;
}
// for(int i = 0; i < m_sizes.size(); i++)
// {
// TENSILE_ASSERT_EXC(m_sizes[i] > 0);
// }
m_strides.resize(m_sizes.size(), UseDefaultStride);
if(m_strides[0] == UseDefaultStride)
{
m_strides[0] = 1;
}
m_totalLogicalElements = m_sizes[0];
for(int i = 1; i < m_sizes.size(); i++)
{
m_totalLogicalElements *= m_sizes[i];
if(m_strides[i] == UseDefaultStride)
{
m_strides[i] = m_strides[i - 1] * m_sizes[i - 1];
}
}
m_totalAllocatedElements = 1;
for(int i = 0; i < m_sizes.size(); i++)
m_totalAllocatedElements += m_strides[i] * (m_sizes[i] - 1);
if(Debug::Instance().printTensorInfo())
{
std::cout << "TensorDescriptor:calculate " << *this
<< "totalLogicalElements=" << m_totalLogicalElements
<< " totalAllocatedElem=" << m_totalAllocatedElements << "\n";
}
}
const std::vector<size_t>& sizes() const
{
return m_sizes;
}
const std::vector<size_t>& strides() const
{
return m_strides;
}
bool empty() const
{
return m_sizes.empty();
}
void appendDim(size_t logicalCount);
void appendDim(size_t logicalCount, size_t allocatedCount);
/**
* Returns the number of elements of padding in the given dimension (0 if
* unpadded). May be negative if stride is less than size
*/
int64_t dimensionPadding(size_t dim) const;
/**
* Collapses dimensions in the interval [begin, end).
*
* preconditions:
* - end >= begin
* - begin < dimensions()
* - end <= dimensions()
* - dimensions in the interval [begin, end-1) are not padded.
*
* postconditions:
* - dimensions() is diminished by end-begin
* - total elements (allocated and logical) remain the same
* - dimension 'begin' is the product of all the dimensions in the interval
* [begin, end).
*/
void collapseDims(size_t begin, size_t end);
size_t dimensions() const
{
return m_sizes.size();
}
size_t totalLogicalElements() const
{
return m_totalLogicalElements;
}
size_t totalAllocatedElements() const
{
return m_totalAllocatedElements;
}
size_t totalAllocatedBytes() const
{
return totalAllocatedElements() * elementBytes();
}
size_t elementBytes() const
{
return DataTypeInfo::Get(m_dataType).elementSize;
}
DataType dataType() const
{
return m_dataType;
}
template <typename Container>
inline size_t index(Container const& indices) const
{
if(indices.size() != dimensions())
throw std::runtime_error("Incorrect number of indices.");
for(int i = 0; i < indices.size(); i++)
if(indices[i] >= m_sizes[i])
throw std::runtime_error("Index out of bounds.");
return std::inner_product(indices.begin(), indices.end(), m_strides.begin(), size_t(0));
}
template <typename T>
inline size_t index(std::initializer_list<T> indices) const
{
if(indices.size() != dimensions())
throw std::runtime_error("Incorrect number of indices.");
for(auto i = std::make_pair(indices.begin(), m_sizes.begin()); i.first != indices.end();
i.first++, i.second++)
if(*i.first >= *i.second)
throw std::runtime_error("Index out of bounds.");
return std::inner_product(indices.begin(), indices.end(), m_strides.begin(), size_t(0));
}
template <class... Ts,
typename = typename std::enable_if<
std::is_integral<typename std::common_type<Ts...>::type>::value>::type>
inline size_t index(Ts... is) const
{
return this->index({is...});
}
inline bool incrementCoord(std::vector<size_t>& coord, size_t firstDimension = 0) const
{
if(coord.size() != dimensions())
throw std::runtime_error(concatenate(
"Invalid coordinate size ", coord.size(), " for ", dimensions(), "-tensor"));
if(firstDimension >= dimensions())
return false;
return IncrementCoord(
coord.begin() + firstDimension, coord.end(), m_sizes.begin(), m_sizes.end());
}
bool operator==(const TensorDescriptor& rhs) const;
bool operator!=(const TensorDescriptor& rhs) const;
std::string ToString() const;
friend std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t);
private:
std::vector<size_t> m_sizes;
std::vector<size_t> m_strides;
size_t m_totalLogicalElements = 0;
size_t m_totalAllocatedElements = 0;
DataType m_dataType = DataType::Float;
};
std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t);
template <typename T>
void WriteTensor1D(std::ostream& stream,
T* data,
TensorDescriptor const& desc,
bool decorated = true)
{
if(desc.dimensions() != 1)
throw std::runtime_error(
"WriteTensor1D is only compatible with 1-dimensional tensors.");
if(decorated)
stream << "[";
if(desc.sizes()[0] > 0)
stream << data[0];
for(size_t i = 1; i < desc.sizes()[0]; i++)
stream << " " << data[i];
if(decorated)
stream << "]" << std::endl;
}
/**
* @brief Writes a tensor to an output stream.
*
* \param stream The stream to write to
* \param data Pointer to the tensor data
* \param desc Tensor descriptor
* \param ptrValue Pointer value to print to describe the location of the data.
* \param decorated Print brackets [] to indicate start/end of tensor dims
*/
template <typename T>
void WriteTensor(std::ostream& stream,
T const* data,
TensorDescriptor const& desc,
T const* ptrValue = nullptr,
bool decorated = true)
{
stream << "Tensor(";
streamJoin(stream, desc.sizes(), ", ");
stream << ", data_ptr: " << data << ")" << std::endl;
if(desc.dimensions() == 0)
return;
if(desc.dimensions() == 1)
{
WriteTensor1D(stream, data, desc, decorated);
return;
}
auto const& sizes = desc.sizes();
std::vector<size_t> coord(desc.dimensions(), 0);
const auto stride0 = desc.strides()[0];
auto upperDimCount = CoordCount(sizes.begin() + 2, sizes.end());
for(size_t idx = 0; idx < upperDimCount; idx++)
{
CoordNumbered(idx, coord.begin() + 2, coord.end(), sizes.begin() + 2, sizes.end());
coord[0] = 0;
coord[1] = 0;
if(decorated)
{
stream << "(";
streamJoin(stream, coord, ", ");
stream << ")" << std::endl << "[" << std::endl;
}
for(coord[1] = 0; coord[1] < sizes[1]; coord[1]++)
{
coord[0] = 0;
auto const* localPtr = data + desc.index(coord);
if(sizes[0] > 0)
stream << localPtr[0];
for(coord[0] = 1; coord[0] < sizes[0]; coord[0]++)
{
stream << " " << localPtr[coord[0] * stride0];
}
stream << std::endl;
}
if(decorated)
{
stream << std::endl << "]" << std::endl;
}
}
}
} // namespace Tensile
|
Test removal of assertion for sizes > 0
|
Test removal of assertion for sizes > 0
|
C++
|
mit
|
ROCmSoftwarePlatform/Tensile,ROCmSoftwarePlatform/Tensile,ROCmSoftwarePlatform/Tensile
|
484c1cd8c4d64057679e2c8fd75ece98f085d4b9
|
console/loop.cpp
|
console/loop.cpp
|
/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* 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 "loop.h"
#include "config.h"
#include "output.h"
#include "mode.h"
#include "configmonitor.h"
#include "edid.h"
#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
using namespace KScreen;
Loop::Loop(QObject* parent): QObject(parent)
{
start();
}
Loop::~Loop()
{
}
void Loop::start()
{
qDebug() << "START";
QDateTime date = QDateTime::currentDateTime();
m_config = Config::current();
qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
ConfigMonitor::instance()->addConfig(m_config);
connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
//config->outputs()[65]->setCurrentMode(70);
//Config::setConfig(config);
}
void Loop::printConfig()
{
// KScreen *screen = KScreen::self();
// qDebug() << "Backend: " << screen->backend();
qDebug() << "\n============================================================\n"
"============================================================\n"
"============================================================\n";
qDebug() << "Screen:";
qDebug() << "maxSize:" << m_config->screen()->maxSize();
qDebug() << "minSize:" << m_config->screen()->minSize();
qDebug() << "currentSize:" << m_config->screen()->currentSize();
OutputList outputs = m_config->outputs();
OutputList outputEnabled;
Q_FOREACH(Output *output, outputs) {
qDebug() << "\n-----------------------------------------------------\n";
qDebug() << "Id: " << output->id();
qDebug() << "Name: " << output->name();
qDebug() << "Type: " << output->type();
qDebug() << "Connected: " << output->isConnected();
qDebug() << "Enabled: " << output->isEnabled();
qDebug() << "Primary: " << output->isPrimary();
qDebug() << "Rotation: " << output->rotation();
qDebug() << "Pos: " << output->pos();
if (output->currentMode()) {
qDebug() << "Size: " << output->mode(output->currentMode())->size();
}
qDebug() << "Clones: " << output->clones().isEmpty();
qDebug() << "Mode: " << output->currentMode();
qDebug() << "Preferred mode: " << output->preferredMode();
qDebug() << "Modes: ";
ModeList modes = output->modes();
Q_FOREACH(Mode* mode, modes) {
qDebug() << "\t" << mode->id() << " " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
}
Edid* edid = output->edid();
qDebug() << "EDID Info: ";
if (edid != 0) {
qDebug() << "\tDevice ID: " << edid->deviceId();
qDebug() << "\tName: " << edid->name();
qDebug() << "\tVendor: " << edid->vendor();
qDebug() << "\tSerial: " << edid->serial();
qDebug() << "\tEISA ID: " << edid->eisaId();
qDebug() << "\tHash: " << edid->hash();
qDebug() << "\tWidth: " << edid->width();
qDebug() << "\tHeight: " << edid->height();
qDebug() << "\tGamma: " << edid->gamma();
qDebug() << "\tRed: " << edid->red();
qDebug() << "\tGreen: " << edid->green();
qDebug() << "\tBlue: " << edid->blue();
qDebug() << "\tWhite: " << edid->white();
} else {
qDebug() << "\tUnavailable";
}
if (output->isEnabled()) {
outputEnabled.insert(output->id(), output);
}
}
}
#include <loop.moc>
|
/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* 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 "loop.h"
#include "config.h"
#include "output.h"
#include "mode.h"
#include "configmonitor.h"
#include "edid.h"
#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
using namespace KScreen;
Loop::Loop(QObject* parent): QObject(parent)
{
start();
}
Loop::~Loop()
{
}
void Loop::start()
{
qDebug() << "START";
QDateTime date = QDateTime::currentDateTime();
m_config = Config::current();
qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
ConfigMonitor::instance()->addConfig(m_config);
connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
//config->outputs()[65]->setCurrentMode(70);
//Config::setConfig(config);
}
void Loop::printConfig()
{
// KScreen *screen = KScreen::self();
// qDebug() << "Backend: " << screen->backend();
qDebug() << "\n============================================================\n"
"============================================================\n"
"============================================================\n";
qDebug() << "Screen:";
qDebug() << "maxSize:" << m_config->screen()->maxSize();
qDebug() << "minSize:" << m_config->screen()->minSize();
qDebug() << "currentSize:" << m_config->screen()->currentSize();
OutputList outputs = m_config->outputs();
OutputList outputEnabled;
Q_FOREACH(Output *output, outputs) {
qDebug() << "\n-----------------------------------------------------\n";
qDebug() << "Id: " << output->id();
qDebug() << "Name: " << output->name();
qDebug() << "Type: " << output->type();
qDebug() << "Connected: " << output->isConnected();
qDebug() << "Enabled: " << output->isEnabled();
qDebug() << "Primary: " << output->isPrimary();
qDebug() << "Rotation: " << output->rotation();
qDebug() << "Pos: " << output->pos();
if (output->currentMode()) {
qDebug() << "Size: " << output->mode(output->currentMode())->size();
}
qDebug() << "Clones: " << output->clones().isEmpty();
qDebug() << "Mode: " << output->currentMode();
qDebug() << "Preferred modes: " << output->preferredModes();
qDebug() << "Modes: ";
ModeList modes = output->modes();
Q_FOREACH(Mode* mode, modes) {
qDebug() << "\t" << mode->id() << " " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
}
Edid* edid = output->edid();
qDebug() << "EDID Info: ";
if (edid != 0) {
qDebug() << "\tDevice ID: " << edid->deviceId();
qDebug() << "\tName: " << edid->name();
qDebug() << "\tVendor: " << edid->vendor();
qDebug() << "\tSerial: " << edid->serial();
qDebug() << "\tEISA ID: " << edid->eisaId();
qDebug() << "\tHash: " << edid->hash();
qDebug() << "\tWidth: " << edid->width();
qDebug() << "\tHeight: " << edid->height();
qDebug() << "\tGamma: " << edid->gamma();
qDebug() << "\tRed: " << edid->red();
qDebug() << "\tGreen: " << edid->green();
qDebug() << "\tBlue: " << edid->blue();
qDebug() << "\tWhite: " << edid->white();
} else {
qDebug() << "\tUnavailable";
}
if (output->isEnabled()) {
outputEnabled.insert(output->id(), output);
}
}
}
#include <loop.moc>
|
Improve preferred modes
|
Improve preferred modes
- add missing implementation of KScreen::Output::preferredModes()
- improve kscreen-console to show IDs of all preferred modes
- fix XRandR backend to clear m_preferredModes before re-loading them
all again
|
C++
|
lgpl-2.1
|
davidedmundson/test,davidedmundson/test,davidedmundson/test
|
5a5794b68cb9e0201802b29d06e33b632e4a200b
|
workbench_sarajevo.cpp
|
workbench_sarajevo.cpp
|
// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'
R__LOAD_LIBRARY(libRooFit)
#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h> // usleep
#include <sys/types.h> // for kill
#include <signal.h> // for kill
#include <ctime>
using namespace RooFit;
////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
// { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////
void workbench_sarajevo(std::string workspace_filepath,
bool just_migrad=true,
int num_cpu=1,
std::string workspace_name="HWWRun2GGF",
std::string model_config_name="ModelConfig",
std::string data_name="obsData",
int optConst=2,
int parallel_interleave=0,
bool cpu_affinity=true,
int seed=1,
int timing_flag=1,
bool time_num_ints=false,
bool fork_timer = false,
int fork_timer_sleep_us = 100000,
int print_level=0,
bool debug=false,
bool total_cpu_timing=true,
bool fix_binned_pdfs=false,
bool zero_initial_POI=false,
std::string POI_name=""
// bool callNLLfirst=false
) {
if (debug) {
RooMsgService::instance().addStream(DEBUG);
// extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
}
// int N_parameters(8); // must be even, means and sigmas have diff ranges
if (timing_flag > 0) {
RooJsonListFile outfile;
outfile.open("timing_meta.json");
std::list<std::string> names = {"timestamp",
"workspace_filepath", "workspace_name",
"model_config_name", "data_name",
"num_cpu", "parallel_interleave", "cpu_affinity",
"seed", "pid", "time_num_ints",
"optConst", "print_level", "timing_flag"};
outfile.set_member_names(names.begin(), names.end());
// int timestamp = std::time(nullptr);
outfile << std::time(nullptr)
<< workspace_filepath << workspace_name
<< model_config_name << data_name
<< num_cpu << parallel_interleave << cpu_affinity
<< seed << getpid() << time_num_ints
<< optConst << print_level << timing_flag;
}
RooTrace::timing_flag = timing_flag;
if (time_num_ints) {
RooTrace::set_time_numInts(kTRUE);
}
// other stuff
int printlevel(print_level);
int optimizeConst(optConst);
// int N_timing_loops(3); // not used
if (printlevel == 0) {
RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
}
RooRandom::randomGenerator()->SetSeed(seed);
// Load the workspace data and pdf
TFile *_file0 = TFile::Open(workspace_filepath.c_str());
RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));
// Activate binned likelihood calculation for binned models
if (fix_binned_pdfs) {
RooFIter iter = w->components().fwdIterator();
RooAbsArg* component_arg;
while((component_arg = iter.next())) {
if (component_arg->IsA() == RooRealSumPdf::Class()) {
component_arg->setAttribute("BinnedLikelihood");
std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
}
}
}
RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));
// RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
RooAbsPdf* pdf = mc->GetPdf();
RooAbsData * data = w->data(data_name.c_str());
// Manually set initial values of parameter of interest
if (zero_initial_POI) {
if (POI_name.length() > 0) {
RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
POI->setVal(0);
} else {
std::cout << "POI_name is empty!" << std::endl;
exit(1);
}
}
// --- Perform extended ML fit of composite PDF to data ---
RooJsonListFile outfile;
RooWallTimer timer;
if (timing_flag == 1) {
outfile.open("timing_full_minimize.json");
outfile.add_member_name("walltime_s")
.add_member_name("segment")
.add_member_name("pid");
}
RooJsonListFile outfile_cpu;
RooCPUTimer ctimer;
if (total_cpu_timing) {
outfile_cpu.open("timing_full_minimize_cpu.json");
outfile_cpu.add_member_name("cputime_s")
.add_member_name("segment")
.add_member_name("pid");
}
Bool_t cpuAffinity;
if (cpu_affinity) {
cpuAffinity = kTRUE;
} else {
cpuAffinity = kFALSE;
}
// for (int it = 0; it < N_timing_loops; ++it)
{
RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
CPUAffinity(cpuAffinity)));//, "Extended");
// std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll)); // shared_ptr gives odd error in ROOT cling!
// RooAbsTestStatistic * nll = dynamic_cast<RooAbsTestStatistic*>(RARnll);
// if (time_evaluate_partition) {
// nll->setTimeEvaluatePartition(kTRUE);
// }
// if (callNLLfirst) {
// RARnll->getVal();
// }
RooMinimizer m(*RARnll);
// m.setVerbose(1);
m.setStrategy(0);
m.setProfile(1);
m.setPrintLevel(printlevel);
m.optimizeConst(optimizeConst);
int pid = -1;
if (fork_timer) {
pid = fork();
}
if (pid == 0) {
/* child */
timer.start();
while (true) {
timer.stop();
std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
usleep(fork_timer_sleep_us);
}
}
else {
/* parent */
double time_migrad, time_hesse, time_minos;
double ctime_migrad, ctime_hesse, ctime_minos;
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
// m.hesse();
m.migrad();
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "migrad" << getpid();
time_migrad = timer.timing_s();
}
if (total_cpu_timing) {
std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
ctime_migrad = ctimer.timing_s();
}
if (!just_migrad) {
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
m.hesse();
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "hesse" << getpid();
time_hesse = timer.timing_s();
}
if (total_cpu_timing) {
std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
ctime_hesse = ctimer.timing_s();
}
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
m.minos(*mc->GetParametersOfInterest());
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "minos" << getpid();
time_minos = timer.timing_s();
outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
}
if (total_cpu_timing) {
std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "minos" << getpid();
ctime_minos = ctimer.timing_s();
outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
}
}
if (pid > 0) {
// a child exists
kill(pid, SIGKILL);
}
}
delete RARnll;
}
}
|
// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'
R__LOAD_LIBRARY(libRooFit)
#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h> // usleep
#include <sys/types.h> // for kill
#include <signal.h> // for kill
#include <ctime>
using namespace RooFit;
////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
// { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////
void workbench_sarajevo(std::string workspace_filepath,
bool just_migrad=true,
int num_cpu=1,
std::string workspace_name="HWWRun2GGF",
std::string model_config_name="ModelConfig",
std::string data_name="obsData",
int optConst=2,
int parallel_interleave=0,
bool cpu_affinity=true,
int seed=1,
int timing_flag=1,
bool time_num_ints=false,
bool fork_timer = false,
int fork_timer_sleep_us = 100000,
int print_level=0,
bool debug=false,
bool total_cpu_timing=true,
bool fix_binned_pdfs=false,
bool zero_initial_POI=false,
std::string POI_name=""
// bool callNLLfirst=false
) {
if (debug) {
RooMsgService::instance().addStream(DEBUG);
// extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
}
// int N_parameters(8); // must be even, means and sigmas have diff ranges
if (timing_flag > 0) {
RooJsonListFile outfile;
outfile.open("timing_meta.json");
std::list<std::string> names = {"timestamp",
"workspace_filepath", "workspace_name",
"model_config_name", "data_name",
"num_cpu", "parallel_interleave", "cpu_affinity",
"seed", "pid", "time_num_ints",
"optConst", "print_level", "timing_flag"};
outfile.set_member_names(names.begin(), names.end());
// int timestamp = std::time(nullptr);
outfile << std::time(nullptr)
<< workspace_filepath << workspace_name
<< model_config_name << data_name
<< num_cpu << parallel_interleave << cpu_affinity
<< seed << getpid() << time_num_ints
<< optConst << print_level << timing_flag;
}
RooTrace::timing_flag = timing_flag;
if (time_num_ints) {
RooTrace::set_time_numInts(kTRUE);
}
// other stuff
int printlevel(print_level);
int optimizeConst(optConst);
// int N_timing_loops(3); // not used
if (printlevel == 0) {
RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
}
RooRandom::randomGenerator()->SetSeed(seed);
// Load the workspace data and pdf
TFile *_file0 = TFile::Open(workspace_filepath.c_str());
RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));
// Activate binned likelihood calculation for binned models
if (fix_binned_pdfs) {
RooFIter iter = w->components().fwdIterator();
RooAbsArg* component_arg;
while((component_arg = iter.next())) {
if (component_arg->IsA() == RooRealSumPdf::Class()) {
component_arg->setAttribute("BinnedLikelihood");
std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
}
}
}
RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));
// RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
RooAbsPdf* pdf = mc->GetPdf();
RooAbsData * data = w->data(data_name.c_str());
// Manually set initial values of parameter of interest
if (zero_initial_POI) {
if (POI_name.length() > 0) {
RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
POI->setVal(0);
} else {
std::cout << "POI_name is empty!" << std::endl;
exit(1);
}
}
// --- Perform extended ML fit of composite PDF to data ---
RooJsonListFile outfile;
RooWallTimer timer;
if (timing_flag == 1) {
outfile.open("timing_full_minimize.json");
outfile.add_member_name("walltime_s")
.add_member_name("segment")
.add_member_name("pid");
}
RooJsonListFile outfile_cpu;
RooCPUTimer ctimer;
if (total_cpu_timing) {
outfile_cpu.open("timing_full_minimize_cpu.json");
outfile_cpu.add_member_name("cputime_s")
.add_member_name("segment")
.add_member_name("pid");
}
Bool_t cpuAffinity;
if (cpu_affinity) {
cpuAffinity = kTRUE;
} else {
cpuAffinity = kFALSE;
}
// for (int it = 0; it < N_timing_loops; ++it)
{
RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
CPUAffinity(cpuAffinity)));//, "Extended");
// std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll)); // shared_ptr gives odd error in ROOT cling!
// RooAbsTestStatistic * nll = dynamic_cast<RooAbsTestStatistic*>(RARnll);
// if (time_evaluate_partition) {
// nll->setTimeEvaluatePartition(kTRUE);
// }
// if (callNLLfirst) {
// RARnll->getVal();
// }
RooMinimizer m(*RARnll);
// m.setVerbose(1);
m.setStrategy(0);
m.setProfile(1);
m.setPrintLevel(printlevel);
m.optimizeConst(optimizeConst);
m.setMinimizerType("Minuit2");
int pid = -1;
if (fork_timer) {
pid = fork();
}
if (pid == 0) {
/* child */
timer.start();
while (true) {
timer.stop();
std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
usleep(fork_timer_sleep_us);
}
}
else {
/* parent */
double time_migrad, time_hesse, time_minos;
double ctime_migrad, ctime_hesse, ctime_minos;
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
// m.hesse();
m.migrad();
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "migrad" << getpid();
time_migrad = timer.timing_s();
}
if (total_cpu_timing) {
std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
ctime_migrad = ctimer.timing_s();
}
if (!just_migrad) {
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
m.hesse();
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "hesse" << getpid();
time_hesse = timer.timing_s();
}
if (total_cpu_timing) {
std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
ctime_hesse = ctimer.timing_s();
}
if (timing_flag == 1) {
timer.start();
}
if (total_cpu_timing) {
ctimer.start();
}
m.minos(*mc->GetParametersOfInterest());
if (timing_flag == 1) {
timer.stop();
}
if (total_cpu_timing) {
ctimer.stop();
}
if (timing_flag == 1) {
std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
outfile << timer.timing_s() << "minos" << getpid();
time_minos = timer.timing_s();
outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
}
if (total_cpu_timing) {
std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
outfile_cpu << ctimer.timing_s() << "minos" << getpid();
ctime_minos = ctimer.timing_s();
outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
}
}
if (pid > 0) {
// a child exists
kill(pid, SIGKILL);
}
}
delete RARnll;
}
}
|
Set minimizer type to Minuit2 for workbench
|
Set minimizer type to Minuit2 for workbench
|
C++
|
apache-2.0
|
roofit-dev/parallel-roofit-scripts,roofit-dev/parallel-roofit-scripts,roofit-dev/parallel-roofit-scripts,roofit-dev/parallel-roofit-scripts,roofit-dev/parallel-roofit-scripts
|
cd274b3e0682d6ffb554bd83fe90f041cb053e34
|
src/usrp_source.cc
|
src/usrp_source.cc
|
/*
* Copyright (c) 2010, Joshua Lackey
* Copyright (c) 2010-2011, Thomas Tsou
* 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.
*
* 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <complex>
#include "usrp_source.h"
extern int g_verbosity;
usrp_source::usrp_source(float sample_rate,
long int fpga_master_clock_freq,
bool external_ref) {
m_desired_sample_rate = sample_rate;
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_external_ref = external_ref;
m_sample_rate = 0.0;
m_dev.reset();
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
}
usrp_source::~usrp_source() {
stop();
delete m_cb;
pthread_mutex_destroy(&m_u_mutex);
}
void usrp_source::stop() {
pthread_mutex_lock(&m_u_mutex);
if(m_dev) {
uhd::stream_cmd_t cmd = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
m_dev->issue_stream_cmd(cmd);
}
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::start() {
pthread_mutex_lock(&m_u_mutex);
if(m_dev) {
uhd::stream_cmd_t cmd = uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;
m_dev->issue_stream_cmd(cmd);
}
pthread_mutex_unlock(&m_u_mutex);
}
float usrp_source::sample_rate() {
return m_sample_rate;
}
int usrp_source::tune(double freq) {
double actual_freq;
pthread_mutex_lock(&m_u_mutex);
m_dev->set_rx_freq(freq);
actual_freq = m_dev->get_rx_freq();
pthread_mutex_unlock(&m_u_mutex);
return actual_freq;
}
void usrp_source::set_antenna(const std::string antenna) {
m_dev->set_rx_antenna(antenna);
}
void usrp_source::set_antenna(int antenna) {
std::vector<std::string> antennas = get_antennas();
if (antenna < antennas.size())
set_antenna(antennas[antenna]);
else
fprintf(stderr, "error: requested invalid antenna\n");
}
std::vector<std::string> usrp_source::get_antennas() {
return m_dev->get_rx_antennas();
}
bool usrp_source::set_gain(float gain) {
uhd::gain_range_t gain_range = m_dev->get_rx_gain_range();
float min = gain_range.start(), max = gain_range.stop();
if((gain < 0.0) || (1.0 < gain))
return false;
m_dev->set_rx_gain(min + gain * (max - min));
return true;
}
/*
* open() should be called before multiple threads access usrp_source.
*/
int usrp_source::open(unsigned int subdev) {
if(!m_dev) {
uhd::device_addr_t dev_addr("type=usrp2");
if (!(m_dev = uhd::usrp::single_usrp::make(dev_addr))) {
fprintf(stderr, "error: single_usrp::make: failed!\n");
return -1;
}
m_dev->set_rx_rate(m_desired_sample_rate);
m_sample_rate = m_dev->get_rx_rate();
uhd::clock_config_t clock_config;
clock_config.pps_source = uhd::clock_config_t::PPS_SMA;
clock_config.pps_polarity = uhd::clock_config_t::PPS_NEG;
if (m_external_ref)
clock_config.ref_source = uhd::clock_config_t::REF_SMA;
else
clock_config.ref_source = uhd::clock_config_t::REF_INT;
m_dev->set_clock_config(clock_config);
if(g_verbosity > 1) {
fprintf(stderr, "Sample rate: %f\n", m_sample_rate);
}
}
set_gain(0.45);
set_antenna(1);
m_recv_samples_per_packet =
m_dev->get_device()->get_max_recv_samps_per_packet();
return 0;
}
int usrp_source::fill(unsigned int num_samples, unsigned int *overrun_i) {
unsigned char ubuf[m_recv_samples_per_packet * 2 * sizeof(short)];
short *s = (short *)ubuf;
unsigned int i, j, space, overruns = 0;
complex *c;
while ((m_cb->data_available() < num_samples)
&& m_cb->space_available() > 0) {
uhd::rx_metadata_t metadata;
pthread_mutex_lock(&m_u_mutex);
size_t samples_read = m_dev->get_device()->recv((void*)ubuf,
m_recv_samples_per_packet,
metadata,
uhd::io_type_t::COMPLEX_INT16,
uhd::device::RECV_MODE_ONE_PACKET);
pthread_mutex_unlock(&m_u_mutex);
if (samples_read < m_recv_samples_per_packet) {
fprintf(stderr, "error: device::recv\n");
return -1;
}
// write complex<short> input to complex<float> output
c = (complex *)m_cb->poke(&space);
// set space to number of complex items to copy
if(space > m_recv_samples_per_packet)
space = m_recv_samples_per_packet;
// write data
for(i = 0, j = 0; i < space; i += 1, j += 2)
c[i] = complex(s[j], s[j + 1]);
// update cb
m_cb->wrote(i);
}
// if the cb is full, we left behind data from the usb packet
if(m_cb->space_available() == 0) {
fprintf(stderr, "warning: local overrun\n");
overruns++;
}
return 0;
}
int usrp_source::read(complex *buf, unsigned int num_samples, unsigned int *samples_read) {
unsigned int n;
if(fill(num_samples, 0))
return -1;
n = m_cb->read(buf, num_samples);
if(samples_read)
*samples_read = n;
return 0;
}
/*
* Don't hold a lock on this and use the usrp at the same time.
*/
circular_buffer *usrp_source::get_buffer() {
return m_cb;
}
int usrp_source::flush(unsigned int flush_count) {
m_cb->flush();
fill(flush_count * m_recv_samples_per_packet * 2 * sizeof(short), 0);
m_cb->flush();
return 0;
}
|
/*
* Copyright (c) 2010, Joshua Lackey
* Copyright (c) 2010-2011, Thomas Tsou
* 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.
*
* 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <complex>
#include <iostream>
#include "usrp_source.h"
extern int g_verbosity;
usrp_source::usrp_source(float sample_rate,
long int fpga_master_clock_freq,
bool external_ref) {
m_desired_sample_rate = sample_rate;
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_external_ref = external_ref;
m_sample_rate = 0.0;
m_dev.reset();
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
}
usrp_source::~usrp_source() {
stop();
delete m_cb;
pthread_mutex_destroy(&m_u_mutex);
}
void usrp_source::stop() {
pthread_mutex_lock(&m_u_mutex);
if(m_dev) {
uhd::stream_cmd_t cmd(uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS);
m_dev->issue_stream_cmd(cmd);
}
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::start() {
pthread_mutex_lock(&m_u_mutex);
if(m_dev) {
uhd::stream_cmd_t cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
m_dev->issue_stream_cmd(cmd);
}
pthread_mutex_unlock(&m_u_mutex);
}
float usrp_source::sample_rate() {
return m_sample_rate;
}
int usrp_source::tune(double freq) {
double actual_freq;
pthread_mutex_lock(&m_u_mutex);
m_dev->set_rx_freq(freq);
actual_freq = m_dev->get_rx_freq();
pthread_mutex_unlock(&m_u_mutex);
return actual_freq;
}
void usrp_source::set_antenna(const std::string antenna) {
m_dev->set_rx_antenna(antenna);
}
void usrp_source::set_antenna(int antenna) {
std::vector<std::string> antennas = get_antennas();
if (antenna < antennas.size())
set_antenna(antennas[antenna]);
else
fprintf(stderr, "error: requested invalid antenna\n");
}
std::vector<std::string> usrp_source::get_antennas() {
return m_dev->get_rx_antennas();
}
bool usrp_source::set_gain(float gain) {
uhd::gain_range_t gain_range = m_dev->get_rx_gain_range();
float min = gain_range.start(), max = gain_range.stop();
if((gain < 0.0) || (1.0 < gain))
return false;
m_dev->set_rx_gain(min + gain * (max - min));
return true;
}
/*
* open() should be called before multiple threads access usrp_source.
*/
int usrp_source::open(unsigned int subdev) {
if(!m_dev) {
uhd::device_addr_t dev_addr("type=usrp2");
if (!(m_dev = uhd::usrp::single_usrp::make(dev_addr))) {
fprintf(stderr, "error: single_usrp::make: failed!\n");
return -1;
}
m_dev->set_rx_rate(m_desired_sample_rate);
m_sample_rate = m_dev->get_rx_rate();
uhd::clock_config_t clock_config;
clock_config.pps_source = uhd::clock_config_t::PPS_SMA;
clock_config.pps_polarity = uhd::clock_config_t::PPS_NEG;
if (m_external_ref)
clock_config.ref_source = uhd::clock_config_t::REF_SMA;
else
clock_config.ref_source = uhd::clock_config_t::REF_INT;
m_dev->set_clock_config(clock_config);
if(g_verbosity > 1) {
fprintf(stderr, "Sample rate: %f\n", m_sample_rate);
}
}
set_gain(0.45);
set_antenna(1);
m_recv_samples_per_packet =
m_dev->get_device()->get_max_recv_samps_per_packet();
return 0;
}
std::string handle_rx_err(uhd::rx_metadata_t metadata, unsigned int *overrun) {
*overrun = false;
std::ostringstream ost("error: ");
switch (metadata.error_code) {
case uhd::rx_metadata_t::ERROR_CODE_NONE:
ost << "no error";
break;
case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
ost << "no packet received, implementation timed-out";
break;
case uhd::rx_metadata_t::ERROR_CODE_LATE_COMMAND:
ost << "a stream command was issued in the past";
break;
case uhd::rx_metadata_t::ERROR_CODE_BROKEN_CHAIN:
ost << "expected another stream command";
break;
case uhd::rx_metadata_t::ERROR_CODE_OVERFLOW:
*overrun = true;
ost << "an internal receive buffer has filled";
break;
case uhd::rx_metadata_t::ERROR_CODE_BAD_PACKET:
ost << "the packet could not be parsed";
break;
default:
ost << "unknown error " << metadata.error_code;
}
return ost.str();
}
int usrp_source::fill(unsigned int num_samples, unsigned int *overrun) {
unsigned char ubuf[m_recv_samples_per_packet * 2 * sizeof(short)];
short *s = (short *)ubuf;
unsigned int i, j, space, overruns = 0;
complex *c;
while ((m_cb->data_available() < num_samples)
&& m_cb->space_available() > 0) {
uhd::rx_metadata_t metadata;
pthread_mutex_lock(&m_u_mutex);
size_t samples_read = m_dev->get_device()->recv((void*)ubuf,
m_recv_samples_per_packet,
metadata,
uhd::io_type_t::COMPLEX_INT16,
uhd::device::RECV_MODE_ONE_PACKET);
pthread_mutex_unlock(&m_u_mutex);
if (samples_read < m_recv_samples_per_packet) {
std::string err_str = handle_rx_err(metadata, overrun);
if (!*overrun) {
fprintf(stderr, err_str.c_str());
return -1;
}
}
// write complex<short> input to complex<float> output
c = (complex *)m_cb->poke(&space);
// set space to number of complex items to copy
if(space > m_recv_samples_per_packet)
space = m_recv_samples_per_packet;
// write data
for(i = 0, j = 0; i < space; i += 1, j += 2)
c[i] = complex(s[j], s[j + 1]);
// update cb
m_cb->wrote(i);
}
// if the cb is full, we left behind data from the usb packet
if(m_cb->space_available() == 0) {
fprintf(stderr, "warning: local overrun\n");
overruns++;
}
return 0;
}
int usrp_source::read(complex *buf, unsigned int num_samples, unsigned int *samples_read) {
unsigned int n;
if(fill(num_samples, 0))
return -1;
n = m_cb->read(buf, num_samples);
if(samples_read)
*samples_read = n;
return 0;
}
/*
* Don't hold a lock on this and use the usrp at the same time.
*/
circular_buffer *usrp_source::get_buffer() {
return m_cb;
}
int usrp_source::flush(unsigned int flush_count) {
m_cb->flush();
fill(flush_count * m_recv_samples_per_packet * 2 * sizeof(short), 0);
m_cb->flush();
return 0;
}
|
add underrun and other error msg handling
|
uhd: add underrun and other error msg handling
|
C++
|
bsd-2-clause
|
ttsou/kalibrate-uhd,ttsou/kalibrate-uhd
|
2b3dbfa5a63cb5a6625ec00294ebd933800f0255
|
src/util/asmap.cpp
|
src/util/asmap.cpp
|
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include <assert.h>
#include <crypto/common.h>
namespace {
uint32_t DecodeBits(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos, uint8_t minval, const std::vector<uint8_t> &bit_sizes)
{
uint32_t val = minval;
bool bit;
for (std::vector<uint8_t>::const_iterator bit_sizes_it = bit_sizes.begin();
bit_sizes_it != bit_sizes.end(); ++bit_sizes_it) {
if (bit_sizes_it + 1 != bit_sizes.end()) {
if (bitpos == endpos) break;
bit = *bitpos;
bitpos++;
} else {
bit = 0;
}
if (bit) {
val += (1 << *bit_sizes_it);
} else {
for (int b = 0; b < *bit_sizes_it; b++) {
if (bitpos == endpos) break;
bit = *bitpos;
bitpos++;
val += bit << (*bit_sizes_it - 1 - b);
}
return val;
}
}
return -1;
}
enum class Instruction : uint32_t
{
RETURN = 0,
JUMP = 1,
MATCH = 2,
DEFAULT = 3,
};
const std::vector<uint8_t> TYPE_BIT_SIZES{0, 0, 1};
Instruction DecodeType(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return Instruction(DecodeBits(bitpos, endpos, 0, TYPE_BIT_SIZES));
}
const std::vector<uint8_t> ASN_BIT_SIZES{15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
uint32_t DecodeASN(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 1, ASN_BIT_SIZES);
}
const std::vector<uint8_t> MATCH_BIT_SIZES{1, 2, 3, 4, 5, 6, 7, 8};
uint32_t DecodeMatch(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 2, MATCH_BIT_SIZES);
}
const std::vector<uint8_t> JUMP_BIT_SIZES{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
uint32_t DecodeJump(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 17, JUMP_BIT_SIZES);
}
}
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip)
{
std::vector<bool>::const_iterator pos = asmap.begin();
const std::vector<bool>::const_iterator endpos = asmap.end();
uint8_t bits = ip.size();
uint32_t default_asn = 0;
uint32_t jump, match, matchlen;
Instruction opcode;
while (pos != endpos) {
opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
return DecodeASN(pos, endpos);
} else if (opcode == Instruction::JUMP) {
jump = DecodeJump(pos, endpos);
if (bits == 0) break;
if (ip[ip.size() - bits]) {
if (jump >= endpos - pos) break;
pos += jump;
}
bits--;
} else if (opcode == Instruction::MATCH) {
match = DecodeMatch(pos, endpos);
matchlen = CountBits(match) - 1;
for (uint32_t bit = 0; bit < matchlen; bit++) {
if (bits == 0) break;
if ((ip[ip.size() - bits]) != ((match >> (matchlen - 1 - bit)) & 1)) {
return default_asn;
}
bits--;
}
} else if (opcode == Instruction::DEFAULT) {
default_asn = DecodeASN(pos, endpos);
} else {
break;
}
}
return 0; // 0 is not a valid ASN
}
|
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include <assert.h>
#include <crypto/common.h>
namespace {
constexpr uint32_t INVALID = 0xFFFFFFFF;
uint32_t DecodeBits(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos, uint8_t minval, const std::vector<uint8_t> &bit_sizes)
{
uint32_t val = minval;
bool bit;
for (std::vector<uint8_t>::const_iterator bit_sizes_it = bit_sizes.begin();
bit_sizes_it != bit_sizes.end(); ++bit_sizes_it) {
if (bit_sizes_it + 1 != bit_sizes.end()) {
if (bitpos == endpos) break;
bit = *bitpos;
bitpos++;
} else {
bit = 0;
}
if (bit) {
val += (1 << *bit_sizes_it);
} else {
for (int b = 0; b < *bit_sizes_it; b++) {
if (bitpos == endpos) return INVALID; // Reached EOF in mantissa
bit = *bitpos;
bitpos++;
val += bit << (*bit_sizes_it - 1 - b);
}
return val;
}
}
return INVALID; // Reached EOF in exponent
}
enum class Instruction : uint32_t
{
RETURN = 0,
JUMP = 1,
MATCH = 2,
DEFAULT = 3,
};
const std::vector<uint8_t> TYPE_BIT_SIZES{0, 0, 1};
Instruction DecodeType(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return Instruction(DecodeBits(bitpos, endpos, 0, TYPE_BIT_SIZES));
}
const std::vector<uint8_t> ASN_BIT_SIZES{15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
uint32_t DecodeASN(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 1, ASN_BIT_SIZES);
}
const std::vector<uint8_t> MATCH_BIT_SIZES{1, 2, 3, 4, 5, 6, 7, 8};
uint32_t DecodeMatch(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 2, MATCH_BIT_SIZES);
}
const std::vector<uint8_t> JUMP_BIT_SIZES{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30};
uint32_t DecodeJump(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos)
{
return DecodeBits(bitpos, endpos, 17, JUMP_BIT_SIZES);
}
}
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip)
{
std::vector<bool>::const_iterator pos = asmap.begin();
const std::vector<bool>::const_iterator endpos = asmap.end();
uint8_t bits = ip.size();
uint32_t default_asn = 0;
uint32_t jump, match, matchlen;
Instruction opcode;
while (pos != endpos) {
opcode = DecodeType(pos, endpos);
if (opcode == Instruction::RETURN) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
return default_asn;
} else if (opcode == Instruction::JUMP) {
jump = DecodeJump(pos, endpos);
if (jump == INVALID) break; // Jump offset straddles EOF
if (bits == 0) break;
if (ip[ip.size() - bits]) {
if (jump >= endpos - pos) break;
pos += jump;
}
bits--;
} else if (opcode == Instruction::MATCH) {
match = DecodeMatch(pos, endpos);
if (match == INVALID) break; // Match bits straddle EOF
matchlen = CountBits(match) - 1;
for (uint32_t bit = 0; bit < matchlen; bit++) {
if (bits == 0) break;
if ((ip[ip.size() - bits]) != ((match >> (matchlen - 1 - bit)) & 1)) {
return default_asn;
}
bits--;
}
} else if (opcode == Instruction::DEFAULT) {
default_asn = DecodeASN(pos, endpos);
if (default_asn == INVALID) break; // ASN straddles EOF
} else {
break; // Instruction straddles EOF
}
}
return 0; // 0 is not a valid ASN
}
|
Deal with decoding failures explicitly in asmap Interpret
|
Deal with decoding failures explicitly in asmap Interpret
|
C++
|
mit
|
MeshCollider/bitcoin,pstratem/bitcoin,MeshCollider/bitcoin,prusnak/bitcoin,MarcoFalke/bitcoin,alecalve/bitcoin,namecoin/namecoin-core,anditto/bitcoin,GroestlCoin/GroestlCoin,ElementsProject/elements,fujicoin/fujicoin,dscotese/bitcoin,jamesob/bitcoin,MeshCollider/bitcoin,domob1812/namecore,prusnak/bitcoin,litecoin-project/litecoin,qtumproject/qtum,mruddy/bitcoin,midnightmagic/bitcoin,Xekyo/bitcoin,AkioNak/bitcoin,andreaskern/bitcoin,practicalswift/bitcoin,EthanHeilman/bitcoin,pataquets/namecoin-core,JeremyRubin/bitcoin,cdecker/bitcoin,domob1812/bitcoin,fujicoin/fujicoin,pataquets/namecoin-core,sstone/bitcoin,EthanHeilman/bitcoin,litecoin-project/litecoin,lateminer/bitcoin,n1bor/bitcoin,jambolo/bitcoin,mruddy/bitcoin,sstone/bitcoin,bitcoinknots/bitcoin,anditto/bitcoin,jnewbery/bitcoin,ajtowns/bitcoin,lateminer/bitcoin,GroestlCoin/bitcoin,pataquets/namecoin-core,domob1812/bitcoin,AkioNak/bitcoin,jlopp/statoshi,namecoin/namecore,jambolo/bitcoin,jlopp/statoshi,jambolo/bitcoin,qtumproject/qtum,domob1812/bitcoin,lateminer/bitcoin,prusnak/bitcoin,mruddy/bitcoin,n1bor/bitcoin,dscotese/bitcoin,particl/particl-core,prusnak/bitcoin,fanquake/bitcoin,dscotese/bitcoin,AkioNak/bitcoin,yenliangl/bitcoin,jlopp/statoshi,MarcoFalke/bitcoin,jonasschnelli/bitcoin,qtumproject/qtum,andreaskern/bitcoin,jamesob/bitcoin,mm-s/bitcoin,pataquets/namecoin-core,instagibbs/bitcoin,andreaskern/bitcoin,jlopp/statoshi,particl/particl-core,kallewoof/bitcoin,ElementsProject/elements,andreaskern/bitcoin,fanquake/bitcoin,litecoin-project/litecoin,MeshCollider/bitcoin,kallewoof/bitcoin,fanquake/bitcoin,lateminer/bitcoin,JeremyRubin/bitcoin,achow101/bitcoin,mm-s/bitcoin,bitcoinsSG/bitcoin,bitcoin/bitcoin,ElementsProject/elements,midnightmagic/bitcoin,MarcoFalke/bitcoin,yenliangl/bitcoin,rnicoll/bitcoin,namecoin/namecoin-core,pstratem/bitcoin,Xekyo/bitcoin,mm-s/bitcoin,bitcoinsSG/bitcoin,particl/particl-core,prusnak/bitcoin,JeremyRubin/bitcoin,fanquake/bitcoin,GroestlCoin/GroestlCoin,kallewoof/bitcoin,instagibbs/bitcoin,lateminer/bitcoin,sipsorcery/bitcoin,GroestlCoin/bitcoin,GroestlCoin/GroestlCoin,alecalve/bitcoin,alecalve/bitcoin,sipsorcery/bitcoin,bitcoinknots/bitcoin,ajtowns/bitcoin,alecalve/bitcoin,midnightmagic/bitcoin,ElementsProject/elements,sipsorcery/bitcoin,JeremyRubin/bitcoin,rnicoll/dogecoin,achow101/bitcoin,namecoin/namecoin-core,cdecker/bitcoin,jambolo/bitcoin,particl/particl-core,GroestlCoin/bitcoin,fujicoin/fujicoin,fanquake/bitcoin,anditto/bitcoin,dscotese/bitcoin,MarcoFalke/bitcoin,GroestlCoin/GroestlCoin,bitcoinknots/bitcoin,rnicoll/bitcoin,sstone/bitcoin,practicalswift/bitcoin,ajtowns/bitcoin,domob1812/namecore,cdecker/bitcoin,midnightmagic/bitcoin,apoelstra/bitcoin,namecoin/namecoin-core,apoelstra/bitcoin,jonasschnelli/bitcoin,jambolo/bitcoin,sipsorcery/bitcoin,rnicoll/dogecoin,Sjors/bitcoin,alecalve/bitcoin,domob1812/namecore,rnicoll/bitcoin,anditto/bitcoin,EthanHeilman/bitcoin,alecalve/bitcoin,bitcoinsSG/bitcoin,namecoin/namecore,GroestlCoin/GroestlCoin,jlopp/statoshi,MarcoFalke/bitcoin,apoelstra/bitcoin,sipsorcery/bitcoin,AkioNak/bitcoin,jlopp/statoshi,jamesob/bitcoin,midnightmagic/bitcoin,namecoin/namecore,tecnovert/particl-core,anditto/bitcoin,MarcoFalke/bitcoin,GroestlCoin/GroestlCoin,apoelstra/bitcoin,MeshCollider/bitcoin,tecnovert/particl-core,pstratem/bitcoin,pstratem/bitcoin,JeremyRubin/bitcoin,cdecker/bitcoin,kallewoof/bitcoin,GroestlCoin/bitcoin,litecoin-project/litecoin,mruddy/bitcoin,qtumproject/qtum,yenliangl/bitcoin,achow101/bitcoin,sipsorcery/bitcoin,namecoin/namecore,Xekyo/bitcoin,pstratem/bitcoin,ajtowns/bitcoin,instagibbs/bitcoin,apoelstra/bitcoin,bitcoin/bitcoin,n1bor/bitcoin,bitcoinknots/bitcoin,Sjors/bitcoin,JeremyRubin/bitcoin,kallewoof/bitcoin,jnewbery/bitcoin,particl/particl-core,mm-s/bitcoin,practicalswift/bitcoin,GroestlCoin/bitcoin,dscotese/bitcoin,AkioNak/bitcoin,jamesob/bitcoin,rnicoll/bitcoin,domob1812/bitcoin,jamesob/bitcoin,fujicoin/fujicoin,qtumproject/qtum,rnicoll/dogecoin,jonasschnelli/bitcoin,achow101/bitcoin,Sjors/bitcoin,pstratem/bitcoin,sstone/bitcoin,cdecker/bitcoin,instagibbs/bitcoin,namecoin/namecore,jonasschnelli/bitcoin,practicalswift/bitcoin,ElementsProject/elements,namecoin/namecore,ElementsProject/elements,bitcoinsSG/bitcoin,anditto/bitcoin,andreaskern/bitcoin,instagibbs/bitcoin,n1bor/bitcoin,bitcoinsSG/bitcoin,rnicoll/bitcoin,MeshCollider/bitcoin,jambolo/bitcoin,rnicoll/bitcoin,namecoin/namecoin-core,dscotese/bitcoin,yenliangl/bitcoin,achow101/bitcoin,jnewbery/bitcoin,domob1812/namecore,ajtowns/bitcoin,domob1812/bitcoin,Sjors/bitcoin,sstone/bitcoin,yenliangl/bitcoin,domob1812/namecore,mruddy/bitcoin,tecnovert/particl-core,Xekyo/bitcoin,Xekyo/bitcoin,tecnovert/particl-core,kallewoof/bitcoin,particl/particl-core,bitcoinknots/bitcoin,mm-s/bitcoin,fanquake/bitcoin,bitcoin/bitcoin,bitcoin/bitcoin,jamesob/bitcoin,ajtowns/bitcoin,achow101/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,fujicoin/fujicoin,litecoin-project/litecoin,litecoin-project/litecoin,jnewbery/bitcoin,practicalswift/bitcoin,andreaskern/bitcoin,AkioNak/bitcoin,EthanHeilman/bitcoin,fujicoin/fujicoin,mm-s/bitcoin,pataquets/namecoin-core,midnightmagic/bitcoin,lateminer/bitcoin,prusnak/bitcoin,EthanHeilman/bitcoin,bitcoin/bitcoin,n1bor/bitcoin,tecnovert/particl-core,practicalswift/bitcoin,pataquets/namecoin-core,apoelstra/bitcoin,sstone/bitcoin,Xekyo/bitcoin,domob1812/bitcoin,jnewbery/bitcoin,rnicoll/dogecoin,instagibbs/bitcoin,namecoin/namecoin-core,jonasschnelli/bitcoin,n1bor/bitcoin,bitcoin/bitcoin,qtumproject/qtum,qtumproject/qtum,domob1812/namecore,yenliangl/bitcoin,bitcoinsSG/bitcoin,EthanHeilman/bitcoin,cdecker/bitcoin,rnicoll/dogecoin,mruddy/bitcoin,Sjors/bitcoin
|
223b41490b96f991f911ea94190e741fea30c30e
|
src/Nazara/Audio/Formats/sndfileLoader.cpp
|
src/Nazara/Audio/Formats/sndfileLoader.cpp
|
// Copyright (C) 2020 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/Formats/sndfileLoader.hpp>
#include <Nazara/Audio/Algorithm.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundStream.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Stream.hpp>
#include <memory>
#include <set>
#include <vector>
#include <sndfile/sndfile.h>
#include <Nazara/Audio/Debug.hpp>
namespace Nz
{
namespace Detail
{
sf_count_t GetSize(void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return stream->GetSize();
}
sf_count_t Read(void* ptr, sf_count_t count, void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return static_cast<sf_count_t>(stream->Read(ptr, static_cast<std::size_t>(count)));
}
sf_count_t Seek(sf_count_t offset, int whence, void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
switch (whence)
{
case SEEK_CUR:
stream->Read(nullptr, static_cast<std::size_t>(offset));
break;
case SEEK_END:
stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici
break;
case SEEK_SET:
stream->SetCursorPos(offset);
break;
default:
NazaraInternalError("Seek mode not handled");
}
return stream->GetCursorPos();
}
sf_count_t Tell(void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return stream->GetCursorPos();
}
static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell};
class sndfileStream : public SoundStream
{
public:
sndfileStream() :
m_handle(nullptr)
{
}
~sndfileStream()
{
if (m_handle)
sf_close(m_handle);
}
UInt32 GetDuration() const override
{
return m_duration;
}
AudioFormat GetFormat() const override
{
// Nous avons besoin du nombre de canaux d'origine pour convertir en mono, nous trichons donc un peu...
if (m_mixToMono)
return AudioFormat_Mono;
else
return m_format;
}
std::mutex& GetMutex() override
{
return m_mutex;
}
UInt64 GetSampleCount() const override
{
return m_sampleCount;
}
UInt32 GetSampleRate() const override
{
return m_sampleRate;
}
bool Open(const std::filesystem::path& filePath, bool forceMono)
{
// Nous devons gérer nous-même le flux car il doit rester ouvert après le passage du loader
// (les flux automatiquement ouverts par le ResourceLoader étant fermés après celui-ci)
std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, OpenMode_ReadOnly))
{
NazaraError("Failed to open stream from file: " + Error::GetLastError());
return false;
}
m_ownedStream = std::move(file);
return Open(*m_ownedStream, forceMono);
}
bool Open(const void* data, std::size_t size, bool forceMono)
{
m_ownedStream = std::make_unique<MemoryView>(data, size);
return Open(*m_ownedStream, forceMono);
}
bool Open(Stream& stream, bool forceMono)
{
SF_INFO infos;
infos.format = 0; // Unknown format
m_handle = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream);
if (!m_handle)
{
NazaraError("Failed to open sound: " + std::string(sf_strerror(m_handle)));
return false;
}
// Un peu de RRID
CallOnExit onExit([this]
{
sf_close(m_handle);
m_handle = nullptr;
});
m_format = Audio::Instance()->GetAudioFormat(infos.channels);
if (m_format == AudioFormat_Unknown)
{
NazaraError("Channel count not handled");
return false;
}
m_sampleCount = infos.channels*infos.frames;
m_sampleRate = infos.samplerate;
// Durée de la musique (s) = samples / channels*rate
m_duration = static_cast<UInt32>(1000ULL*m_sampleCount / (m_format*m_sampleRate));
// https://github.com/LaurentGomila/SFML/issues/271
// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
///FIXME: Seulement le Vorbis ?
if (infos.format & SF_FORMAT_VORBIS)
sf_command(m_handle, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);
// On mixera en mono lors de la lecture
if (forceMono && m_format != AudioFormat_Mono)
{
m_mixToMono = true;
m_sampleCount = static_cast<UInt32>(infos.frames);
}
else
m_mixToMono = false;
onExit.Reset();
return true;
}
UInt64 Read(void* buffer, UInt64 sampleCount) override
{
// Si la musique a été demandée en mono, nous devons la convertir à la volée lors de la lecture
if (m_mixToMono)
{
// On garde un buffer sur le côté pour éviter la réallocation
m_mixBuffer.resize(m_format * sampleCount);
sf_count_t readSampleCount = sf_read_short(m_handle, m_mixBuffer.data(), m_format * sampleCount);
MixToMono(m_mixBuffer.data(), static_cast<Int16*>(buffer), m_format, sampleCount);
return readSampleCount / m_format;
}
else
return sf_read_short(m_handle, static_cast<Int16*>(buffer), sampleCount);
}
void Seek(UInt64 offset) override
{
sf_seek(m_handle, offset*m_sampleRate / 1000, SEEK_SET);
}
UInt64 Tell() override
{
return sf_seek(m_handle, 0, SEEK_CUR) * 1000 / m_sampleRate;
}
private:
std::vector<Int16> m_mixBuffer;
std::unique_ptr<Stream> m_ownedStream;
AudioFormat m_format;
SNDFILE* m_handle;
bool m_mixToMono;
std::mutex m_mutex;
UInt32 m_duration;
UInt32 m_sampleRate;
UInt64 m_sampleCount;
};
bool IsSupported(const std::string& extension)
{
static std::set<std::string> supportedExtensions = {
"aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k",
"nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve"
};
return supportedExtensions.find(extension) != supportedExtensions.end();
}
Ternary CheckSoundStream(Stream& stream, const SoundStreamParams& parameters)
{
NazaraUnused(parameters);
SF_INFO info;
info.format = 0; // Format inconnu
// Si on peut ouvrir le flux, c'est qu'il est dans un format compatible
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (file)
{
sf_close(file);
return Ternary_True;
}
else
return Ternary_False;
}
SoundStreamRef LoadSoundStreamFile(const std::filesystem::path& filePath, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream = std::make_unique<sndfileStream>();
if (!soundStream->Open(filePath, parameters.forceMono))
{
NazaraError("Failed to open sound stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
SoundStreamRef LoadSoundStreamMemory(const void* data, std::size_t size, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream(new sndfileStream);
if (!soundStream->Open(data, size, parameters.forceMono))
{
NazaraError("Failed to open music stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
SoundStreamRef LoadSoundStreamStream(Stream& stream, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream(new sndfileStream);
if (!soundStream->Open(stream, parameters.forceMono))
{
NazaraError("Failed to open music stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
Ternary CheckSoundBuffer(Stream& stream, const SoundBufferParams& parameters)
{
NazaraUnused(parameters);
SF_INFO info;
info.format = 0;
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (file)
{
sf_close(file);
return Ternary_True;
}
else
return Ternary_False;
}
SoundBufferRef LoadSoundBuffer(Stream& stream, const SoundBufferParams& parameters)
{
SF_INFO info;
info.format = 0;
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (!file)
{
NazaraError("Failed to load sound file: " + std::string(sf_strerror(file)));
return nullptr;
}
// Lynix utilise RAII...
// C'est très efficace !
// MemoryLeak est confus...
CallOnExit onExit([file]
{
sf_close(file);
});
AudioFormat format = Audio::Instance()->GetAudioFormat(info.channels);
if (format == AudioFormat_Unknown)
{
NazaraError("Channel count not handled");
return nullptr;
}
// https://github.com/LaurentGomila/SFML/issues/271
// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
///FIXME: Seulement le Vorbis ?
if (info.format & SF_FORMAT_VORBIS)
sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);
unsigned int sampleCount = static_cast<unsigned int>(info.frames * info.channels);
std::unique_ptr<Int16[]> samples(new Int16[sampleCount]);
if (sf_read_short(file, samples.get(), sampleCount) != sampleCount)
{
NazaraError("Failed to read samples");
return nullptr;
}
// Une conversion en mono est-elle nécessaire ?
if (parameters.forceMono && format != AudioFormat_Mono)
{
// Nous effectuons la conversion en mono dans le même buffer (il va de toute façon être copié)
MixToMono(samples.get(), samples.get(), static_cast<unsigned int>(info.channels), static_cast<unsigned int>(info.frames));
format = AudioFormat_Mono;
sampleCount = static_cast<unsigned int>(info.frames);
}
return SoundBuffer::New(format, sampleCount, info.samplerate, samples.get());
}
}
namespace Loaders
{
void Register_sndfile()
{
SoundBufferLoader::RegisterLoader(Detail::IsSupported, Detail::CheckSoundBuffer, Detail::LoadSoundBuffer);
SoundStreamLoader::RegisterLoader(Detail::IsSupported, Detail::CheckSoundStream, Detail::LoadSoundStreamStream, Detail::LoadSoundStreamFile, Detail::LoadSoundStreamMemory);
}
void Unregister_sndfile()
{
SoundBufferLoader::UnregisterLoader(Detail::IsSupported, Detail::CheckSoundBuffer, Detail::LoadSoundBuffer);
SoundStreamLoader::UnregisterLoader(Detail::IsSupported, Detail::CheckSoundStream, Detail::LoadSoundStreamStream, Detail::LoadSoundStreamFile, Detail::LoadSoundStreamMemory);
}
}
}
|
// Copyright (C) 2020 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/Formats/sndfileLoader.hpp>
#include <Nazara/Audio/Algorithm.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundStream.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Stream.hpp>
#include <memory>
#include <set>
#include <vector>
#include <sndfile.h>
#include <Nazara/Audio/Debug.hpp>
namespace Nz
{
namespace Detail
{
sf_count_t GetSize(void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return stream->GetSize();
}
sf_count_t Read(void* ptr, sf_count_t count, void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return static_cast<sf_count_t>(stream->Read(ptr, static_cast<std::size_t>(count)));
}
sf_count_t Seek(sf_count_t offset, int whence, void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
switch (whence)
{
case SEEK_CUR:
stream->Read(nullptr, static_cast<std::size_t>(offset));
break;
case SEEK_END:
stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici
break;
case SEEK_SET:
stream->SetCursorPos(offset);
break;
default:
NazaraInternalError("Seek mode not handled");
}
return stream->GetCursorPos();
}
sf_count_t Tell(void* user_data)
{
Stream* stream = static_cast<Stream*>(user_data);
return stream->GetCursorPos();
}
static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell};
class sndfileStream : public SoundStream
{
public:
sndfileStream() :
m_handle(nullptr)
{
}
~sndfileStream()
{
if (m_handle)
sf_close(m_handle);
}
UInt32 GetDuration() const override
{
return m_duration;
}
AudioFormat GetFormat() const override
{
// Nous avons besoin du nombre de canaux d'origine pour convertir en mono, nous trichons donc un peu...
if (m_mixToMono)
return AudioFormat_Mono;
else
return m_format;
}
std::mutex& GetMutex() override
{
return m_mutex;
}
UInt64 GetSampleCount() const override
{
return m_sampleCount;
}
UInt32 GetSampleRate() const override
{
return m_sampleRate;
}
bool Open(const std::filesystem::path& filePath, bool forceMono)
{
// Nous devons gérer nous-même le flux car il doit rester ouvert après le passage du loader
// (les flux automatiquement ouverts par le ResourceLoader étant fermés après celui-ci)
std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, OpenMode_ReadOnly))
{
NazaraError("Failed to open stream from file: " + Error::GetLastError());
return false;
}
m_ownedStream = std::move(file);
return Open(*m_ownedStream, forceMono);
}
bool Open(const void* data, std::size_t size, bool forceMono)
{
m_ownedStream = std::make_unique<MemoryView>(data, size);
return Open(*m_ownedStream, forceMono);
}
bool Open(Stream& stream, bool forceMono)
{
SF_INFO infos;
infos.format = 0; // Unknown format
m_handle = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream);
if (!m_handle)
{
NazaraError("Failed to open sound: " + std::string(sf_strerror(m_handle)));
return false;
}
// Un peu de RRID
CallOnExit onExit([this]
{
sf_close(m_handle);
m_handle = nullptr;
});
m_format = Audio::Instance()->GetAudioFormat(infos.channels);
if (m_format == AudioFormat_Unknown)
{
NazaraError("Channel count not handled");
return false;
}
m_sampleCount = infos.channels*infos.frames;
m_sampleRate = infos.samplerate;
// Durée de la musique (s) = samples / channels*rate
m_duration = static_cast<UInt32>(1000ULL*m_sampleCount / (m_format*m_sampleRate));
// https://github.com/LaurentGomila/SFML/issues/271
// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
///FIXME: Seulement le Vorbis ?
if (infos.format & SF_FORMAT_VORBIS)
sf_command(m_handle, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);
// On mixera en mono lors de la lecture
if (forceMono && m_format != AudioFormat_Mono)
{
m_mixToMono = true;
m_sampleCount = static_cast<UInt32>(infos.frames);
}
else
m_mixToMono = false;
onExit.Reset();
return true;
}
UInt64 Read(void* buffer, UInt64 sampleCount) override
{
// Si la musique a été demandée en mono, nous devons la convertir à la volée lors de la lecture
if (m_mixToMono)
{
// On garde un buffer sur le côté pour éviter la réallocation
m_mixBuffer.resize(m_format * sampleCount);
sf_count_t readSampleCount = sf_read_short(m_handle, m_mixBuffer.data(), m_format * sampleCount);
MixToMono(m_mixBuffer.data(), static_cast<Int16*>(buffer), m_format, sampleCount);
return readSampleCount / m_format;
}
else
return sf_read_short(m_handle, static_cast<Int16*>(buffer), sampleCount);
}
void Seek(UInt64 offset) override
{
sf_seek(m_handle, offset*m_sampleRate / 1000, SEEK_SET);
}
UInt64 Tell() override
{
return sf_seek(m_handle, 0, SEEK_CUR) * 1000 / m_sampleRate;
}
private:
std::vector<Int16> m_mixBuffer;
std::unique_ptr<Stream> m_ownedStream;
AudioFormat m_format;
SNDFILE* m_handle;
bool m_mixToMono;
std::mutex m_mutex;
UInt32 m_duration;
UInt32 m_sampleRate;
UInt64 m_sampleCount;
};
bool IsSupported(const std::string& extension)
{
static std::set<std::string> supportedExtensions = {
"aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k",
"nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve"
};
return supportedExtensions.find(extension) != supportedExtensions.end();
}
Ternary CheckSoundStream(Stream& stream, const SoundStreamParams& parameters)
{
NazaraUnused(parameters);
SF_INFO info;
info.format = 0; // Format inconnu
// Si on peut ouvrir le flux, c'est qu'il est dans un format compatible
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (file)
{
sf_close(file);
return Ternary_True;
}
else
return Ternary_False;
}
SoundStreamRef LoadSoundStreamFile(const std::filesystem::path& filePath, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream = std::make_unique<sndfileStream>();
if (!soundStream->Open(filePath, parameters.forceMono))
{
NazaraError("Failed to open sound stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
SoundStreamRef LoadSoundStreamMemory(const void* data, std::size_t size, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream(new sndfileStream);
if (!soundStream->Open(data, size, parameters.forceMono))
{
NazaraError("Failed to open music stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
SoundStreamRef LoadSoundStreamStream(Stream& stream, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream(new sndfileStream);
if (!soundStream->Open(stream, parameters.forceMono))
{
NazaraError("Failed to open music stream");
return nullptr;
}
soundStream->SetPersistent(false);
return soundStream.release();
}
Ternary CheckSoundBuffer(Stream& stream, const SoundBufferParams& parameters)
{
NazaraUnused(parameters);
SF_INFO info;
info.format = 0;
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (file)
{
sf_close(file);
return Ternary_True;
}
else
return Ternary_False;
}
SoundBufferRef LoadSoundBuffer(Stream& stream, const SoundBufferParams& parameters)
{
SF_INFO info;
info.format = 0;
SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
if (!file)
{
NazaraError("Failed to load sound file: " + std::string(sf_strerror(file)));
return nullptr;
}
// Lynix utilise RAII...
// C'est très efficace !
// MemoryLeak est confus...
CallOnExit onExit([file]
{
sf_close(file);
});
AudioFormat format = Audio::Instance()->GetAudioFormat(info.channels);
if (format == AudioFormat_Unknown)
{
NazaraError("Channel count not handled");
return nullptr;
}
// https://github.com/LaurentGomila/SFML/issues/271
// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
///FIXME: Seulement le Vorbis ?
if (info.format & SF_FORMAT_VORBIS)
sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);
unsigned int sampleCount = static_cast<unsigned int>(info.frames * info.channels);
std::unique_ptr<Int16[]> samples(new Int16[sampleCount]);
if (sf_read_short(file, samples.get(), sampleCount) != sampleCount)
{
NazaraError("Failed to read samples");
return nullptr;
}
// Une conversion en mono est-elle nécessaire ?
if (parameters.forceMono && format != AudioFormat_Mono)
{
// Nous effectuons la conversion en mono dans le même buffer (il va de toute façon être copié)
MixToMono(samples.get(), samples.get(), static_cast<unsigned int>(info.channels), static_cast<unsigned int>(info.frames));
format = AudioFormat_Mono;
sampleCount = static_cast<unsigned int>(info.frames);
}
return SoundBuffer::New(format, sampleCount, info.samplerate, samples.get());
}
}
namespace Loaders
{
void Register_sndfile()
{
SoundBufferLoader::RegisterLoader(Detail::IsSupported, Detail::CheckSoundBuffer, Detail::LoadSoundBuffer);
SoundStreamLoader::RegisterLoader(Detail::IsSupported, Detail::CheckSoundStream, Detail::LoadSoundStreamStream, Detail::LoadSoundStreamFile, Detail::LoadSoundStreamMemory);
}
void Unregister_sndfile()
{
SoundBufferLoader::UnregisterLoader(Detail::IsSupported, Detail::CheckSoundBuffer, Detail::LoadSoundBuffer);
SoundStreamLoader::UnregisterLoader(Detail::IsSupported, Detail::CheckSoundStream, Detail::LoadSoundStreamStream, Detail::LoadSoundStreamFile, Detail::LoadSoundStreamMemory);
}
}
}
|
Fix sndfile inclusion
|
Fix sndfile inclusion
|
C++
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
d46f4eac6871bdadbbe8d45f5665062f572e8aaf
|
Application/cmbNucImporter.cxx
|
Application/cmbNucImporter.cxx
|
#include "cmbNucImporter.h"
#include "cmbNucCore.h"
#include "inpFileIO.h"
#include "cmbNucMainWindow.h"
#include "cmbNucInputListWidget.h"
#include "cmbNucAssembly.h"
#include "cmbNucInputPropertiesWidget.h"
#include "xmlFileIO.h"
#include "cmbNucDefaults.h"
#include "cmbNucMaterialColors.h"
#include "cmbNucDuctLibrary.h"
#include <set>
#include <QSettings>
#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
extern int defaultAssemblyColors[][3];
extern int numAssemblyDefaultColors;
cmbNucImporter::cmbNucImporter(cmbNucMainWindow * mw)
:mainWindow(mw)
{
}
bool cmbNucImporter::importXMLPins()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
std::map<std::string, std::string> junk;
double tmpD = 10.0;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
mainWindow->NuclearCore->getPinLibrary()->setKeepGoingAsRename();
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<PinCell*> pincells;
if(!xmlFileReader::read(fileNames[i].toStdString(), pincells, materials)) return false;
for(unsigned int j = 0; j < pincells.size(); ++j)
{
this->addPin(pincells[j], tmpD, junk);
}
}
delete materials;
return true;
}
bool cmbNucImporter::importXMLDucts()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
std::map<std::string, std::string> junk;
double tmpD = 10;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
double ductThick[] = {10.0, 10.0};
mainWindow->NuclearCore->GetDefaults()->getDuctThickness(ductThick[0],ductThick[1]);
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<DuctCell*> ductcells;
if(!xmlFileReader::read(fileNames[i].toStdString(), ductcells, materials)) return false;
for(unsigned int j = 0; j < ductcells.size(); ++j)
{
this->addDuct(ductcells[j], tmpD, ductThick, junk);
}
}
delete materials;
return true;
}
bool cmbNucImporter::importInpFile()
{
// Use cached value for last used directory if there is one,
// or default to the user's home dir if not.
QSettings settings("CMBNuclear", "CMBNuclear");
QDir dir = settings.value("cache/lastDir", QDir::homePath()).toString();
QStringList fileNames =
QFileDialog::getOpenFileNames(mainWindow,
"Open File...",
dir.path(),
"INP Files (*.inp)");
if(fileNames.count()==0)
{
return false;
}
// Cache the directory for the next time the dialog is opened
QFileInfo info(fileNames[0]);
settings.setValue("cache/lastDir", info.dir().path());
int numExistingAssy = mainWindow->NuclearCore->GetNumberOfAssemblies();
bool need_to_use_assem = false;
mainWindow->NuclearCore->getPinLibrary()->resetConflictResolution();
for( int i = 0; i < fileNames.count(); ++i)
{
inpFileReader freader;
switch(freader.open(fileNames[i].toStdString()))
{
case inpFileReader::ASSEMBLY_TYPE:
{
if(!mainWindow->InputsWidget->isEnabled() || mainWindow->InputsWidget->onlyMeshLoaded())
{
mainWindow->doClearAll(true);
}
QFileInfo finfo(fileNames[i]);
std::string label = finfo.completeBaseName().toStdString();
cmbNucAssembly *assembly = new cmbNucAssembly();
assembly->setLabel(label);
if(!freader.read(*assembly, mainWindow->NuclearCore->getPinLibrary(),
mainWindow->NuclearCore->getDuctLibrary()))
{
QMessageBox msgBox;
msgBox.setText("Invalid INP file");
msgBox.setInformativeText(fileNames[i]+" could not be readed.");
msgBox.exec();
delete assembly;
return false;
}
if(mainWindow->InputsWidget->isEnabled() &&
assembly->IsHexType() != mainWindow->NuclearCore->IsHexType())
{
QMessageBox msgBox;
msgBox.setText("Not the same type");
msgBox.setInformativeText(fileNames[i]+" is not the same geometry type as current core.");
msgBox.exec();
delete assembly;
return false;
}
int acolorIndex = numExistingAssy +
mainWindow->NuclearCore->GetNumberOfAssemblies() % numAssemblyDefaultColors;
QColor acolor(defaultAssemblyColors[acolorIndex][0],
defaultAssemblyColors[acolorIndex][1],
defaultAssemblyColors[acolorIndex][2]);
assembly->SetLegendColor(acolor);
bool need_to_calc_defaults = mainWindow->NuclearCore->GetNumberOfAssemblies() == 0;
mainWindow->NuclearCore->AddAssembly(assembly);
if(need_to_calc_defaults)
{
mainWindow->NuclearCore->calculateDefaults();
switch(assembly->getLattice().GetGeometryType())
{
case RECTILINEAR:
mainWindow->NuclearCore->setGeometryLabel("Rectangular");
break;
case HEXAGONAL:
mainWindow->NuclearCore->setGeometryLabel("HexFlat");
break;
}
}
else
{
assembly->setFromDefaults( mainWindow->NuclearCore->GetDefaults() );
}
need_to_use_assem = true;
if( mainWindow->NuclearCore->getLattice().GetGeometrySubType() & ANGLE_60 &&
mainWindow->NuclearCore->getLattice().GetGeometrySubType() & VERTEX )
{
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
assembly->getLattice().setFullCellMode(Lattice::HEX_FULL);
}
else
{
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
assembly->getLattice().setFullCellMode(Lattice::HEX_FULL_30);
}
assembly->adjustRotation();
break;
}
case inpFileReader::CORE_TYPE:
// clear old assembly
if(!mainWindow->checkFilesBeforePreceeding()) return false;
mainWindow->doClearAll();
log.clear();
mainWindow->PropertyWidget->setObject(NULL, NULL);
mainWindow->PropertyWidget->setAssembly(NULL);
if(!freader.read(*(mainWindow->NuclearCore)))
{
QMessageBox msgBox;
msgBox.setText("Invalid INP file");
msgBox.setInformativeText(fileNames[i]+" could not be readed.");
msgBox.exec();
mainWindow->unsetCursor();
return false;
}
mainWindow->NuclearCore->setAndTestDiffFromFiles(false);
mainWindow->NuclearCore->SetLegendColorToAssemblies(numAssemblyDefaultColors,
defaultAssemblyColors);
mainWindow->PropertyWidget->resetCore(mainWindow->NuclearCore);
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
for(int j = 0; j < mainWindow->NuclearCore->GetNumberOfAssemblies(); ++j)
{
mainWindow->NuclearCore->GetAssembly(j)->adjustRotation();
if( mainWindow->NuclearCore->getLattice().GetGeometrySubType() & ANGLE_60 &&
mainWindow->NuclearCore->getLattice().GetGeometrySubType() & VERTEX )
{
mainWindow->NuclearCore->GetAssembly(j)->getLattice().setFullCellMode(Lattice::HEX_FULL);
}
else
{
mainWindow->NuclearCore->GetAssembly(j)->getLattice().setFullCellMode(Lattice::HEX_FULL_30);
}
}
break;
default:
qDebug() << "could not open" << fileNames[i];
}
std::vector<std::string> tlog = freader.getLog();
log.insert(log.end(), tlog.begin(), tlog.end());
}
int numNewAssy = mainWindow->NuclearCore->GetNumberOfAssemblies() - numExistingAssy;
if(numNewAssy)
{
mainWindow->PropertyWidget->resetCore(mainWindow->NuclearCore);
}
// update data colors
mainWindow->updateCoreMaterialColors();
// In case the loaded core adds new materials
mainWindow->InputsWidget->updateUI(numNewAssy);
return true;
}
bool cmbNucImporter::importXMLAssembly()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
cmbNucDuctLibrary * dl = new cmbNucDuctLibrary();
cmbNucPinLibrary * pl = new cmbNucPinLibrary();
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
double tmpD = 10;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
double ductThick[] = {10.0, 10.0};
mainWindow->NuclearCore->GetDefaults()->getDuctThickness(ductThick[0],ductThick[1]);
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<cmbNucAssembly *> assys;
std::map<PinCell*, PinCell*> addedPin;
std::map<DuctCell*, DuctCell*> addedDuct;
std::map<std::string, std::string> ductMap;
std::map<std::string, std::string> pinMap;
xmlFileReader::read(fileNames[i].toStdString(), assys, pl, dl, materials);
for(unsigned int j = 0; j < assys.size(); ++j)
{
cmbNucAssembly * assy = assys[j];
if(assy->IsHexType() != mainWindow->NuclearCore->IsHexType())
{
QMessageBox msgBox;
msgBox.setText("Not the same type");
msgBox.setInformativeText(fileNames[i]+" is not the same geometry type as current core.");
msgBox.exec();
for(unsigned int k = 0; k < assys.size(); ++k)
{
delete assys[k];
}
j = assys.size();
continue;
}
//update duct
DuctCell * aduct = &(assy->getAssyDuct());
if(addedDuct.find(aduct) != addedDuct.end())
{
assy->setDuctCell(addedDuct[aduct]);
}
else
{
DuctCell * dc = new DuctCell();
dc->fill(aduct);
addedDuct[aduct] = dc;
this->addDuct(dc, tmpD, ductThick, ductMap);
assy->setDuctCell(dc);
}
std::map<std::string, std::string> jnk;
//update pins
for(std::size_t k = 0; k < assy->GetNumberOfPinCells(); ++k)
{
PinCell* old = assy->GetPinCell(k);
PinCell* newpc = NULL;
if(addedPin.find(old) != addedPin.end())
{
newpc = addedPin[old];
}
else
{
newpc = new PinCell;
newpc->fill(old);
addedPin[old] = newpc;
this->addPin(newpc, tmpD, jnk);
}
assy->SetPinCell(k, newpc);
if(old->getLabel() != newpc->getLabel())
{
assy->getLattice().replaceLabel(old->getLabel(), newpc->getLabel());
}
}
//add assy
std::string n = assy->getLabel();
int count = 0;
while(!mainWindow->NuclearCore->label_unique(n))
{
n = (QString(assy->getLabel().c_str()) + QString::number(count++)).toStdString();
}
assy->setLabel(n);
mainWindow->NuclearCore->AddAssembly(assy);
}
}
delete materials;
delete dl;
delete pl;
return true;
}
void cmbNucImporter::addPin(PinCell * pc, double dh, std::map<std::string, std::string> & nc)
{
pc->setHeight(dh);
//adjust materials
if(pc->cellMaterialSet())
{
QPointer<cmbNucMaterial> cm = pc->getCellMaterial();
QPointer<cmbNucMaterial> tmpm = this->getMaterial(pc->getCellMaterial());
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
pc->setCellMaterial(tmpm);
}
int layers = pc->GetNumberOfLayers();
for(int k = 0; k < layers; ++k)
{
QPointer<cmbNucMaterial> tmpm = this->getMaterial(pc->Material(k));
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
pc->SetMaterial(k, tmpm);
}
mainWindow->NuclearCore->getPinLibrary()->addPin(&pc, true, nc);
}
void cmbNucImporter::addDuct(DuctCell * dc, double dh, double dt[2], std::map<std::string, std::string> & nc)
{
dc->setDuctThickness(dt[0], dt[1]);
dc->setLength(dh);
//adjust materials
for(unsigned int k = 0; k < dc->numberOfDucts(); ++k)
{
Duct * d = dc->getDuct(k);
int layers = d->NumberOfLayers();
for(int l = 0; l < layers; ++l)
{
QPointer<cmbNucMaterial> tmpm = this->getMaterial(d->getMaterial(l));
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
d->setMaterial(l, tmpm);
if(mainWindow->NuclearCore->IsHexType())
{
double * tmp = d->getNormThick(l);
tmp[1] = tmp[0];
}
}
}
mainWindow->NuclearCore->getDuctLibrary()->addDuct(dc, nc);
}
QPointer<cmbNucMaterial> cmbNucImporter::getMaterial(QPointer<cmbNucMaterial> cm)
{
cmbNucMaterialColors * matColorMap = cmbNucMaterialColors::instance();
if( matColorMap->nameUsed(cm->getName()))
{
return matColorMap->getMaterialByName(cm->getName());
}
else if(matColorMap->labelUsed(cm->getLabel()))
{
return matColorMap->getMaterialByLabel(cm->getLabel());
}
else
{
return matColorMap->AddMaterial(cm->getName(),
cm->getLabel(),
cm->getColor());
}
}
QStringList cmbNucImporter::getXMLFiles()
{
// Use cached value for last used directory if there is one,
// or default to the user's home dir if not.
QSettings settings("CMBNuclear", "CMBNuclear");
QDir dir = settings.value("cache/lastDir", QDir::homePath()).toString();
QStringList fileNames =
QFileDialog::getOpenFileNames(mainWindow,
"Open File...",
dir.path(),
"RGG XML File (*.RXF)");
if(fileNames.count()==0)
{
return fileNames;
}
// Cache the directory for the next time the dialog is opened
QFileInfo info(fileNames[0]);
settings.setValue("cache/lastDir", info.dir().path());
return fileNames;
}
|
#include "cmbNucImporter.h"
#include "cmbNucCore.h"
#include "inpFileIO.h"
#include "cmbNucMainWindow.h"
#include "cmbNucInputListWidget.h"
#include "cmbNucAssembly.h"
#include "cmbNucInputPropertiesWidget.h"
#include "xmlFileIO.h"
#include "cmbNucDefaults.h"
#include "cmbNucMaterialColors.h"
#include "cmbNucDuctLibrary.h"
#include <set>
#include <QSettings>
#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
extern int defaultAssemblyColors[][3];
extern int numAssemblyDefaultColors;
cmbNucImporter::cmbNucImporter(cmbNucMainWindow * mw)
:mainWindow(mw)
{
}
bool cmbNucImporter::importXMLPins()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
std::map<std::string, std::string> junk;
double tmpD = 10.0;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
mainWindow->NuclearCore->getPinLibrary()->setKeepGoingAsRename();
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<PinCell*> pincells;
if(!xmlFileReader::read(fileNames[i].toStdString(), pincells, materials)) return false;
for(unsigned int j = 0; j < pincells.size(); ++j)
{
this->addPin(pincells[j], tmpD, junk);
}
}
delete materials;
return true;
}
bool cmbNucImporter::importXMLDucts()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
std::map<std::string, std::string> junk;
double tmpD = 10;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
double ductThick[] = {10.0, 10.0};
mainWindow->NuclearCore->GetDefaults()->getDuctThickness(ductThick[0],ductThick[1]);
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<DuctCell*> ductcells;
if(!xmlFileReader::read(fileNames[i].toStdString(), ductcells, materials)) return false;
for(unsigned int j = 0; j < ductcells.size(); ++j)
{
this->addDuct(ductcells[j], tmpD, ductThick, junk);
}
}
delete materials;
return true;
}
bool cmbNucImporter::importInpFile()
{
// Use cached value for last used directory if there is one,
// or default to the user's home dir if not.
QSettings settings("CMBNuclear", "CMBNuclear");
QDir dir = settings.value("cache/lastDir", QDir::homePath()).toString();
QStringList fileNames =
QFileDialog::getOpenFileNames(mainWindow,
"Open File...",
dir.path(),
"INP Files (*.inp)");
if(fileNames.count()==0)
{
return false;
}
// Cache the directory for the next time the dialog is opened
QFileInfo info(fileNames[0]);
settings.setValue("cache/lastDir", info.dir().path());
int numExistingAssy = mainWindow->NuclearCore->GetNumberOfAssemblies();
bool need_to_use_assem = false;
mainWindow->NuclearCore->getPinLibrary()->resetConflictResolution();
for( int i = 0; i < fileNames.count(); ++i)
{
inpFileReader freader;
switch(freader.open(fileNames[i].toStdString()))
{
case inpFileReader::ASSEMBLY_TYPE:
{
if(!mainWindow->InputsWidget->isEnabled() || mainWindow->InputsWidget->onlyMeshLoaded())
{
mainWindow->doClearAll(true);
}
QFileInfo finfo(fileNames[i]);
std::string label = finfo.completeBaseName().toStdString();
cmbNucAssembly *assembly = new cmbNucAssembly();
assembly->setLabel(label);
if(!freader.read(*assembly, mainWindow->NuclearCore->getPinLibrary(),
mainWindow->NuclearCore->getDuctLibrary()))
{
QMessageBox msgBox;
msgBox.setText("Invalid INP file");
msgBox.setInformativeText(fileNames[i]+" could not be readed.");
msgBox.exec();
delete assembly;
return false;
}
if(mainWindow->InputsWidget->isEnabled() &&
assembly->IsHexType() != mainWindow->NuclearCore->IsHexType())
{
QMessageBox msgBox;
msgBox.setText("Not the same type");
msgBox.setInformativeText(fileNames[i]+" is not the same geometry type as current core.");
msgBox.exec();
delete assembly;
return false;
}
int acolorIndex = numExistingAssy +
mainWindow->NuclearCore->GetNumberOfAssemblies() % numAssemblyDefaultColors;
QColor acolor(defaultAssemblyColors[acolorIndex][0],
defaultAssemblyColors[acolorIndex][1],
defaultAssemblyColors[acolorIndex][2]);
assembly->SetLegendColor(acolor);
bool need_to_calc_defaults = mainWindow->NuclearCore->GetNumberOfAssemblies() == 0;
mainWindow->NuclearCore->AddAssembly(assembly);
if(need_to_calc_defaults)
{
mainWindow->NuclearCore->calculateDefaults();
switch(assembly->getLattice().GetGeometryType())
{
case RECTILINEAR:
mainWindow->NuclearCore->setGeometryLabel("Rectangular");
break;
case HEXAGONAL:
mainWindow->NuclearCore->setGeometryLabel("HexFlat");
break;
}
}
else
{
assembly->setFromDefaults( mainWindow->NuclearCore->GetDefaults() );
}
need_to_use_assem = true;
if( mainWindow->NuclearCore->getLattice().GetGeometrySubType() & ANGLE_60 &&
mainWindow->NuclearCore->getLattice().GetGeometrySubType() & VERTEX )
{
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
assembly->getLattice().setFullCellMode(Lattice::HEX_FULL);
}
else
{
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
assembly->getLattice().setFullCellMode(Lattice::HEX_FULL_30);
}
assembly->adjustRotation();
break;
}
case inpFileReader::CORE_TYPE:
// clear old assembly
if(!mainWindow->checkFilesBeforePreceeding()) return false;
mainWindow->doClearAll();
log.clear();
mainWindow->PropertyWidget->setObject(NULL, NULL);
mainWindow->PropertyWidget->setAssembly(NULL);
if(!freader.read(*(mainWindow->NuclearCore)))
{
QMessageBox msgBox;
msgBox.setText("Invalid INP file");
msgBox.setInformativeText(fileNames[i]+" could not be readed.");
msgBox.exec();
mainWindow->unsetCursor();
return false;
}
mainWindow->NuclearCore->setAndTestDiffFromFiles(false);
mainWindow->NuclearCore->SetLegendColorToAssemblies(numAssemblyDefaultColors,
defaultAssemblyColors);
mainWindow->PropertyWidget->resetCore(mainWindow->NuclearCore);
mainWindow->NuclearCore->getLattice().setFullCellMode(Lattice::HEX_FULL);
for(int j = 0; j < mainWindow->NuclearCore->GetNumberOfAssemblies(); ++j)
{
mainWindow->NuclearCore->GetAssembly(j)->adjustRotation();
if( mainWindow->NuclearCore->getLattice().GetGeometrySubType() & ANGLE_60 &&
mainWindow->NuclearCore->getLattice().GetGeometrySubType() & VERTEX )
{
mainWindow->NuclearCore->GetAssembly(j)->getLattice().setFullCellMode(Lattice::HEX_FULL);
}
else
{
mainWindow->NuclearCore->GetAssembly(j)->getLattice().setFullCellMode(Lattice::HEX_FULL_30);
}
}
break;
default:
qDebug() << "could not open" << fileNames[i];
QMessageBox msgBox;
msgBox.setText("Could Not Open File");
msgBox.setInformativeText(fileNames[i]+" is not a valid core or assembly file.");
msgBox.exec();
return false;
}
std::vector<std::string> tlog = freader.getLog();
log.insert(log.end(), tlog.begin(), tlog.end());
}
int numNewAssy = mainWindow->NuclearCore->GetNumberOfAssemblies() - numExistingAssy;
if(numNewAssy)
{
mainWindow->PropertyWidget->resetCore(mainWindow->NuclearCore);
}
// update data colors
mainWindow->updateCoreMaterialColors();
// In case the loaded core adds new materials
mainWindow->InputsWidget->updateUI(numNewAssy);
return true;
}
bool cmbNucImporter::importXMLAssembly()
{
QStringList fileNames = this->getXMLFiles();
if(fileNames.count()==0)
{
return false;
}
cmbNucDuctLibrary * dl = new cmbNucDuctLibrary();
cmbNucPinLibrary * pl = new cmbNucPinLibrary();
cmbNucMaterialColors * materials = new cmbNucMaterialColors;
double tmpD = 10;
assert(mainWindow->NuclearCore->HasDefaults());
mainWindow->NuclearCore->GetDefaults()->getHeight(tmpD);
double ductThick[] = {10.0, 10.0};
mainWindow->NuclearCore->GetDefaults()->getDuctThickness(ductThick[0],ductThick[1]);
for( int i = 0; i < fileNames.count(); ++i)
{
materials->clear();
std::vector<cmbNucAssembly *> assys;
std::map<PinCell*, PinCell*> addedPin;
std::map<DuctCell*, DuctCell*> addedDuct;
std::map<std::string, std::string> ductMap;
std::map<std::string, std::string> pinMap;
xmlFileReader::read(fileNames[i].toStdString(), assys, pl, dl, materials);
for(unsigned int j = 0; j < assys.size(); ++j)
{
cmbNucAssembly * assy = assys[j];
if(assy->IsHexType() != mainWindow->NuclearCore->IsHexType())
{
QMessageBox msgBox;
msgBox.setText("Not the same type");
msgBox.setInformativeText(fileNames[i]+" is not the same geometry type as current core.");
msgBox.exec();
for(unsigned int k = 0; k < assys.size(); ++k)
{
delete assys[k];
}
j = assys.size();
continue;
}
//update duct
DuctCell * aduct = &(assy->getAssyDuct());
if(addedDuct.find(aduct) != addedDuct.end())
{
assy->setDuctCell(addedDuct[aduct]);
}
else
{
DuctCell * dc = new DuctCell();
dc->fill(aduct);
addedDuct[aduct] = dc;
this->addDuct(dc, tmpD, ductThick, ductMap);
assy->setDuctCell(dc);
}
std::map<std::string, std::string> jnk;
//update pins
for(std::size_t k = 0; k < assy->GetNumberOfPinCells(); ++k)
{
PinCell* old = assy->GetPinCell(k);
PinCell* newpc = NULL;
if(addedPin.find(old) != addedPin.end())
{
newpc = addedPin[old];
}
else
{
newpc = new PinCell;
newpc->fill(old);
addedPin[old] = newpc;
this->addPin(newpc, tmpD, jnk);
}
assy->SetPinCell(k, newpc);
if(old->getLabel() != newpc->getLabel())
{
assy->getLattice().replaceLabel(old->getLabel(), newpc->getLabel());
}
}
//add assy
std::string n = assy->getLabel();
int count = 0;
while(!mainWindow->NuclearCore->label_unique(n))
{
n = (QString(assy->getLabel().c_str()) + QString::number(count++)).toStdString();
}
assy->setLabel(n);
mainWindow->NuclearCore->AddAssembly(assy);
}
}
delete materials;
delete dl;
delete pl;
return true;
}
void cmbNucImporter::addPin(PinCell * pc, double dh, std::map<std::string, std::string> & nc)
{
pc->setHeight(dh);
//adjust materials
if(pc->cellMaterialSet())
{
QPointer<cmbNucMaterial> cm = pc->getCellMaterial();
QPointer<cmbNucMaterial> tmpm = this->getMaterial(pc->getCellMaterial());
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
pc->setCellMaterial(tmpm);
}
int layers = pc->GetNumberOfLayers();
for(int k = 0; k < layers; ++k)
{
QPointer<cmbNucMaterial> tmpm = this->getMaterial(pc->Material(k));
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
pc->SetMaterial(k, tmpm);
}
mainWindow->NuclearCore->getPinLibrary()->addPin(&pc, true, nc);
}
void cmbNucImporter::addDuct(DuctCell * dc, double dh, double dt[2], std::map<std::string, std::string> & nc)
{
dc->setDuctThickness(dt[0], dt[1]);
dc->setLength(dh);
//adjust materials
for(unsigned int k = 0; k < dc->numberOfDucts(); ++k)
{
Duct * d = dc->getDuct(k);
int layers = d->NumberOfLayers();
for(int l = 0; l < layers; ++l)
{
QPointer<cmbNucMaterial> tmpm = this->getMaterial(d->getMaterial(l));
assert(tmpm != NULL);
assert(tmpm != cmbNucMaterialColors::instance()->getUnknownMaterial());
d->setMaterial(l, tmpm);
if(mainWindow->NuclearCore->IsHexType())
{
double * tmp = d->getNormThick(l);
tmp[1] = tmp[0];
}
}
}
mainWindow->NuclearCore->getDuctLibrary()->addDuct(dc, nc);
}
QPointer<cmbNucMaterial> cmbNucImporter::getMaterial(QPointer<cmbNucMaterial> cm)
{
cmbNucMaterialColors * matColorMap = cmbNucMaterialColors::instance();
if( matColorMap->nameUsed(cm->getName()))
{
return matColorMap->getMaterialByName(cm->getName());
}
else if(matColorMap->labelUsed(cm->getLabel()))
{
return matColorMap->getMaterialByLabel(cm->getLabel());
}
else
{
return matColorMap->AddMaterial(cm->getName(),
cm->getLabel(),
cm->getColor());
}
}
QStringList cmbNucImporter::getXMLFiles()
{
// Use cached value for last used directory if there is one,
// or default to the user's home dir if not.
QSettings settings("CMBNuclear", "CMBNuclear");
QDir dir = settings.value("cache/lastDir", QDir::homePath()).toString();
QStringList fileNames =
QFileDialog::getOpenFileNames(mainWindow,
"Open File...",
dir.path(),
"RGG XML File (*.RXF)");
if(fileNames.count()==0)
{
return fileNames;
}
// Cache the directory for the next time the dialog is opened
QFileInfo info(fileNames[0]);
settings.setValue("cache/lastDir", info.dir().path());
return fileNames;
}
|
fix chash
|
fix chash
|
C++
|
bsd-3-clause
|
Sprunth/RGG,Sprunth/RGG,Sprunth/RGG,Sprunth/RGG
|
1b419d18f8fa8e27b25c1d7cd62e54faaa9bd497
|
src/QtLocationPlugin/GoogleMapProvider.cpp
|
src/QtLocationPlugin/GoogleMapProvider.cpp
|
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "GoogleMapProvider.h"
#if defined(DEBUG_GOOGLE_MAPS)
#include <QFile>
#include <QStandardPaths>
#endif
#include <QtGlobal>
#include "QGCMapEngine.h"
GoogleMapProvider::GoogleMapProvider(const QString &imageFormat, const quint32 averageSize, const QGeoMapType::MapStyle mapType, QObject* parent)
: MapProvider(QStringLiteral("https://www.google.com/maps/preview"), imageFormat, averageSize, mapType, parent)
, _googleVersionRetrieved(false)
, _googleReply(nullptr)
{
// Google version strings
_versionGoogleMap = QStringLiteral("m@354000000");
_versionGoogleSatellite = QStringLiteral("692");
_versionGoogleLabels = QStringLiteral("h@336");
_versionGoogleTerrain = QStringLiteral("t@354,r@354000000");
_versionGoogleHybrid = QStringLiteral("y");
_secGoogleWord = QStringLiteral("Galileo");
}
GoogleMapProvider::~GoogleMapProvider() {
if (_googleReply)
_googleReply->deleteLater();
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_getSecGoogleWords(const int x, const int y, QString& sec1, QString& sec2) const {
sec1 = QStringLiteral(""); // after &x=...
sec2 = QStringLiteral(""); // after &zoom=...
int seclen = ((x * 3) + y) % 8;
sec2 = _secGoogleWord.left(seclen);
if (y >= 10000 && y < 100000) {
sec1 = QStringLiteral("&s=");
}
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_networkReplyError(QNetworkReply::NetworkError error) {
qWarning() << "Could not connect to google maps. Error:" << error;
if (_googleReply) {
_googleReply->deleteLater();
_googleReply = nullptr;
}
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_replyDestroyed() {
_googleReply = nullptr;
}
void GoogleMapProvider::_googleVersionCompleted() {
if (!_googleReply || (_googleReply->error() != QNetworkReply::NoError)) {
qDebug() << "Error collecting Google maps version info";
return;
}
const QString html = QString(_googleReply->readAll());
#if defined(DEBUG_GOOGLE_MAPS)
QString filename = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
filename += QStringLiteral("/google.output");
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << html << endl;
}
#endif
QRegExp reg(QStringLiteral("\"*https?://mt\\D?\\d..*/vt\\?lyrs=m@(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
_versionGoogleMap = QString(QStringLiteral("m@%1")).arg(reg.capturedTexts().value(1, QString()));
}
reg = QRegExp(QStringLiteral("\"*https?://khm\\D?\\d.googleapis.com/kh\\?v=(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
_versionGoogleSatellite = reg.capturedTexts().value(1);
}
reg = QRegExp(QStringLiteral("\"*https?://mt\\D?\\d..*/vt\\?lyrs=t@(\\d*),r@(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
const QStringList gc = reg.capturedTexts();
_versionGoogleTerrain = QString(QStringLiteral("t@%1,r@%2")).arg(gc.value(1), gc.value(2));
}
_googleReply->deleteLater();
_googleReply = nullptr;
}
void GoogleMapProvider::_tryCorrectGoogleVersions(QNetworkAccessManager* networkManager) {
QMutexLocker locker(&_googleVersionMutex);
if (_googleVersionRetrieved) {
return;
}
_googleVersionRetrieved = true;
if (networkManager) {
QNetworkRequest qheader;
QNetworkProxy proxy = networkManager->proxy();
QNetworkProxy tProxy;
tProxy.setType(QNetworkProxy::DefaultProxy);
networkManager->setProxy(tProxy);
QSslConfiguration conf = qheader.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
qheader.setSslConfiguration(conf);
const QString url = QStringLiteral("http://maps.google.com/maps/api/js?v=3.2&sensor=false");
qheader.setUrl(QUrl(url));
QByteArray ua;
ua.append(getQGCMapEngine()->userAgent());
qheader.setRawHeader("User-Agent", ua);
_googleReply = networkManager->get(qheader);
connect(_googleReply, &QNetworkReply::finished, this, &GoogleMapProvider::_googleVersionCompleted);
connect(_googleReply, &QNetworkReply::destroyed, this, &GoogleMapProvider::_replyDestroyed);
connect(_googleReply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &GoogleMapProvider::_networkReplyError);
networkManager->setProxy(proxy);
}
}
QString GoogleStreetMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
// http://mt1.google.com/vt/lyrs=m
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleMap)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleSatelliteMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
// http://mt1.google.com/vt/lyrs=s
QString server = QStringLiteral("khm");
QString request = QStringLiteral("kh");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleSatellite)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleLabelsMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = "mts";
QString request = "vt";
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleLabels)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleTerrainMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleTerrain)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleHybridMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleHybrid)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
|
/****************************************************************************
*
* (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "GoogleMapProvider.h"
#if defined(DEBUG_GOOGLE_MAPS)
#include <QFile>
#include <QStandardPaths>
#endif
#include <QtGlobal>
#include "QGCMapEngine.h"
GoogleMapProvider::GoogleMapProvider(const QString &imageFormat, const quint32 averageSize, const QGeoMapType::MapStyle mapType, QObject* parent)
: MapProvider(QStringLiteral("https://www.google.com/maps/preview"), imageFormat, averageSize, mapType, parent)
, _googleVersionRetrieved(false)
, _googleReply(nullptr)
{
// Google version strings
_versionGoogleMap = QStringLiteral("m@354000000");
_versionGoogleSatellite = QStringLiteral("692");
_versionGoogleLabels = QStringLiteral("h@336");
_versionGoogleTerrain = QStringLiteral("t@354,r@354000000");
_versionGoogleHybrid = QStringLiteral("y");
_secGoogleWord = QStringLiteral("Galileo");
}
GoogleMapProvider::~GoogleMapProvider() {
if (_googleReply)
_googleReply->deleteLater();
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_getSecGoogleWords(const int x, const int y, QString& sec1, QString& sec2) const {
sec1 = QStringLiteral(""); // after &x=...
sec2 = QStringLiteral(""); // after &zoom=...
int seclen = ((x * 3) + y) % 8;
sec2 = _secGoogleWord.left(seclen);
if (y >= 10000 && y < 100000) {
sec1 = QStringLiteral("&s=");
}
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_networkReplyError(QNetworkReply::NetworkError error) {
qWarning() << "Could not connect to google maps. Error:" << error;
if (_googleReply) {
_googleReply->deleteLater();
_googleReply = nullptr;
}
}
//-----------------------------------------------------------------------------
void GoogleMapProvider::_replyDestroyed() {
_googleReply = nullptr;
}
void GoogleMapProvider::_googleVersionCompleted() {
if (!_googleReply || (_googleReply->error() != QNetworkReply::NoError)) {
qDebug() << "Error collecting Google maps version info";
return;
}
const QString html = QString(_googleReply->readAll());
#if defined(DEBUG_GOOGLE_MAPS)
QString filename = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
filename += QStringLiteral("/google.output");
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << html << endl;
}
#endif
QRegExp reg(QStringLiteral("\"*https?://mt\\D?\\d..*/vt\\?lyrs=m@(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
_versionGoogleMap = QString(QStringLiteral("m@%1")).arg(reg.capturedTexts().value(1, QString()));
}
reg = QRegExp(QStringLiteral("\"*https?://khm\\D?\\d.googleapis.com/kh\\?v=(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
_versionGoogleSatellite = reg.capturedTexts().value(1);
}
reg = QRegExp(QStringLiteral("\"*https?://mt\\D?\\d..*/vt\\?lyrs=t@(\\d*),r@(\\d*)"), Qt::CaseInsensitive);
if (reg.indexIn(html) != -1) {
const QStringList gc = reg.capturedTexts();
_versionGoogleTerrain = QString(QStringLiteral("t@%1,r@%2")).arg(gc.value(1), gc.value(2));
}
_googleReply->deleteLater();
_googleReply = nullptr;
}
void GoogleMapProvider::_tryCorrectGoogleVersions(QNetworkAccessManager* networkManager) {
QMutexLocker locker(&_googleVersionMutex);
if (_googleVersionRetrieved) {
return;
}
_googleVersionRetrieved = true;
if (networkManager) {
QNetworkRequest qheader;
QNetworkProxy proxy = networkManager->proxy();
QNetworkProxy tProxy;
tProxy.setType(QNetworkProxy::DefaultProxy);
networkManager->setProxy(tProxy);
QSslConfiguration conf = qheader.sslConfiguration();
conf.setPeerVerifyMode(QSslSocket::VerifyNone);
qheader.setSslConfiguration(conf);
const QString url = QStringLiteral("http://maps.google.com/maps/api/js?v=3.2&sensor=false");
qheader.setUrl(QUrl(url));
QByteArray ua;
ua.append(getQGCMapEngine()->userAgent());
qheader.setRawHeader("User-Agent", ua);
_googleReply = networkManager->get(qheader);
connect(_googleReply, &QNetworkReply::finished, this, &GoogleMapProvider::_googleVersionCompleted);
connect(_googleReply, &QNetworkReply::destroyed, this, &GoogleMapProvider::_replyDestroyed);
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
connect(_googleReply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &GoogleMapProvider::_networkReplyError);
#else
connect(_googleReply, &QNetworkReply::errorOccurred, this, &GoogleMapProvider::_networkReplyError);
#endif
networkManager->setProxy(proxy);
}
}
QString GoogleStreetMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
// http://mt1.google.com/vt/lyrs=m
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleMap)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleSatelliteMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
// http://mt1.google.com/vt/lyrs=s
QString server = QStringLiteral("khm");
QString request = QStringLiteral("kh");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleSatellite)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleLabelsMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = "mts";
QString request = "vt";
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleLabels)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleTerrainMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/v=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleTerrain)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
QString GoogleHybridMapProvider::_getURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) {
QString server = QStringLiteral("mt");
QString request = QStringLiteral("vt");
QString sec1; // after &x=...
QString sec2; // after &zoom=...
_getSecGoogleWords(x, y, sec1, sec2);
_tryCorrectGoogleVersions(networkManager);
return QString(QStringLiteral("http://%1%2.google.com/%3/lyrs=%4&hl=%5&x=%6%7&y=%8&z=%9&s=%10"))
.arg(server)
.arg(_getServerNum(x, y, 4))
.arg(request)
.arg(_versionGoogleHybrid)
.arg(_language)
.arg(x)
.arg(sec1)
.arg(y)
.arg(zoom)
.arg(sec2);
}
|
Add new errorOccurred for Qt 5.15 builds
|
GoogleMapProvider: Add new errorOccurred for Qt 5.15 builds
Signed-off-by: Patrick José Pereira <[email protected]>
|
C++
|
agpl-3.0
|
Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol
|
f400932348661dd800e191a53b4eab13cea50da8
|
Plugins/org.mitk.gui.qt.photoacoustics.simulation/src/internal/PASimulator.cpp
|
Plugins/org.mitk.gui.qt.photoacoustics.simulation/src/internal/PASimulator.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "PASimulator.h"
// Qt
#include <QMessageBox>
#include <QCheckBox>
#include <QFileDialog>
// mitk
#include <mitkImage.h>
#include <mitkDataNode.h>
#include <mitkIOUtil.h>
#include <iostream>
#include <fstream>
const std::string PASimulator::VIEW_ID = "org.mitk.views.pasimulator";
void PASimulator::SetFocus()
{
m_Controls.pushButtonShowRandomTissue->setFocus();
}
void PASimulator::CreateQtPartControl(QWidget *parent)
{
m_Controls.setupUi(parent);
connect(m_Controls.pushButtonShowRandomTissue, SIGNAL(clicked()), this, SLOT(DoImageProcessing()));
connect(m_Controls.checkBoxGauss, SIGNAL(stateChanged(int)), this, SLOT(ClickedGaussBox()));
connect(m_Controls.pushButtonOpenPath, SIGNAL(clicked()), this, SLOT(OpenFolder()));
connect(m_Controls.pushButtonOpenBinary, SIGNAL(clicked()), this, SLOT(OpenBinary()));
connect(m_Controls.checkBoxGenerateBatch, SIGNAL(clicked()), this, SLOT(UpdateVisibilityOfBatchCreation()));
connect(m_Controls.pushButtonAjustWavelength, SIGNAL(clicked()), this, SLOT(UpdateParametersAccordingToWavelength()));
connect(m_Controls.checkBoxRngSeed, SIGNAL(clicked()), this, SLOT(ClickedCheckboxFixedSeed()));
connect(m_Controls.checkBoxRandomizeParameters, SIGNAL(clicked()), this, SLOT(ClickedRandomizePhysicalParameters()));
m_Controls.spinboxSigma->setEnabled(false);
m_Controls.labelSigma->setEnabled(false);
char* home_env = std::getenv("HOME");
if (home_env == nullptr)
{
home_env = std::getenv("HOMEPATH");
}
if (home_env == nullptr)
{
home_env = "";
}
m_Controls.label_NrrdFilePath->setText(home_env);
m_PhotoacousticPropertyCalculator = mitk::pa::PropertyCalculator::New();
UpdateVisibilityOfBatchCreation();
ClickedRandomizePhysicalParameters();
ClickedCheckboxFixedSeed();
ClickedGaussBox();
}
void PASimulator::ClickedRandomizePhysicalParameters()
{
m_Controls.spinboxRandomizeParameters->setEnabled(m_Controls.checkBoxRandomizeParameters->isChecked());
}
void PASimulator::ClickedCheckboxFixedSeed()
{
m_Controls.spinBoxRngSeed->setEnabled(m_Controls.checkBoxRngSeed->isChecked());
}
void PASimulator::UpdateParametersAccordingToWavelength()
{
int wavelength = m_Controls.spinboxWavelength->value();
double bloodOxygenation = m_Controls.spinboxBloodOxygenSaturation->value() / 100;
auto result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::BLOOD, wavelength, bloodOxygenation);
m_Controls.spinboxMaxAbsorption->setValue(result.mua);
m_Controls.spinboxMinAbsorption->setValue(result.mua);
m_Controls.spinboxBloodVesselScatteringMinimum->setValue(result.mus);
m_Controls.spinboxBloodVesselScatteringMaximum->setValue(result.mus);
m_Controls.spinboxBloodVesselAnisotropyMinimum->setValue(result.g);
m_Controls.spinboxBloodVesselAnisotropyMaximum->setValue(result.g);
result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::EPIDERMIS, wavelength, bloodOxygenation);
m_Controls.spinboxSkinAbsorption->setValue(result.mua);
m_Controls.spinboxSkinScattering->setValue(result.mus);
m_Controls.spinboxSkinAnisotropy->setValue(result.g);
result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::STANDARD_TISSUE, wavelength, bloodOxygenation);
m_Controls.spinboxBackgroundAbsorption->setValue(result.mua);
m_Controls.spinboxBackgroundScattering->setValue(result.mus);
m_Controls.spinboxBackgroundAnisotropy->setValue(result.g);
}
void PASimulator::UpdateVisibilityOfBatchCreation()
{
m_Controls.widgetBatchFile->setVisible(m_Controls.checkBoxGenerateBatch->isChecked());
}
mitk::pa::TissueGeneratorParameters::Pointer PASimulator::GetParametersFromUIInput()
{
auto parameters = mitk::pa::TissueGeneratorParameters::New();
// Getting settings from UI
// General settings
parameters->SetXDim(m_Controls.spinboxXDim->value());
parameters->SetYDim(m_Controls.spinboxYDim->value());
parameters->SetZDim(m_Controls.spinboxZDim->value());
parameters->SetDoVolumeSmoothing(m_Controls.checkBoxGauss->isChecked());
if (parameters->GetDoVolumeSmoothing())
parameters->SetVolumeSmoothingSigma(m_Controls.spinboxSigma->value());
parameters->SetRandomizePhysicalProperties(m_Controls.checkBoxRandomizeParameters->isChecked());
parameters->SetRandomizePhysicalPropertiesPercentage(m_Controls.spinboxRandomizeParameters->value());
parameters->SetVoxelSpacingInCentimeters(m_Controls.spinboxSpacing->value());
parameters->SetUseRngSeed(m_Controls.checkBoxRngSeed->isChecked());
parameters->SetRngSeed(m_Controls.spinBoxRngSeed->value());
// Monte Carlo simulation parameters
parameters->SetMCflag(m_Controls.spinboxMcFlag->value());
parameters->SetMCLaunchflag(m_Controls.spinboxLaunchFlag->value());
parameters->SetMCBoundaryflag(m_Controls.spinboxboundaryFlag->value());
parameters->SetMCLaunchPointX(m_Controls.spinboxLaunchpointX->value());
parameters->SetMCLaunchPointY(m_Controls.spinboxLaunchpointY->value());
parameters->SetMCLaunchPointZ(m_Controls.spinboxLaunchpointZ->value());
parameters->SetMCFocusPointX(m_Controls.spinboxFocuspointX->value());
parameters->SetMCFocusPointY(m_Controls.spinboxFocuspointY->value());
parameters->SetMCFocusPointZ(m_Controls.spinboxFocuspointZ->value());
parameters->SetMCTrajectoryVectorX(m_Controls.spinboxTrajectoryVectorX->value());
parameters->SetMCTrajectoryVectorY(m_Controls.spinboxTrajectoryVectorY->value());
parameters->SetMCTrajectoryVectorZ(m_Controls.spinboxTrajectoryVectorZ->value());
parameters->SetMCRadius(m_Controls.spinboxRadius->value());
parameters->SetMCWaist(m_Controls.spinboxWaist->value());
// Vessel settings
parameters->SetMaxVesselAbsorption(m_Controls.spinboxMaxAbsorption->value());
parameters->SetMinVesselAbsorption(m_Controls.spinboxMinAbsorption->value());
parameters->SetMaxVesselBending(m_Controls.spinboxMaxBending->value());
parameters->SetMinVesselBending(m_Controls.spinboxMinBending->value());
parameters->SetMaxVesselRadiusInMillimeters(m_Controls.spinboxMaxDiameter->value());
parameters->SetMinVesselRadiusInMillimeters(m_Controls.spinboxMinDiameter->value());
parameters->SetMaxNumberOfVessels(m_Controls.spinboxMaxVessels->value());
parameters->SetMinNumberOfVessels(m_Controls.spinboxMinVessels->value());
parameters->SetMinVesselScattering(m_Controls.spinboxBloodVesselScatteringMinimum->value());
parameters->SetMaxVesselScattering(m_Controls.spinboxBloodVesselScatteringMaximum->value());
parameters->SetMinVesselAnisotropy(m_Controls.spinboxBloodVesselAnisotropyMinimum->value());
parameters->SetMaxVesselAnisotropy(m_Controls.spinboxBloodVesselAnisotropyMaximum->value());
parameters->SetVesselBifurcationFrequency(m_Controls.spinboxBifurcationFrequency->value());
parameters->SetMinVesselZOrigin(m_Controls.spinboxMinSpawnDepth->value());
parameters->SetMaxVesselZOrigin(m_Controls.spinboxMaxSpawnDepth->value());
// Background tissue settings
parameters->SetBackgroundAbsorption(m_Controls.spinboxBackgroundAbsorption->value());
parameters->SetBackgroundScattering(m_Controls.spinboxBackgroundScattering->value());
parameters->SetBackgroundAnisotropy(m_Controls.spinboxBackgroundAnisotropy->value());
// Air settings
parameters->SetAirThicknessInMillimeters(m_Controls.spinboxAirThickness->value());
//Skin tissue settings
parameters->SetSkinThicknessInMillimeters(m_Controls.spinboxSkinThickness->value());
parameters->SetSkinAbsorption(m_Controls.spinboxSkinAbsorption->value());
parameters->SetSkinScattering(m_Controls.spinboxSkinScattering->value());
parameters->SetSkinAnisotropy(m_Controls.spinboxSkinAnisotropy->value());
parameters->SetCalculateNewVesselPositionCallback(&mitk::pa::VesselMeanderStrategy::CalculateRandomlyDivergingPosition);
return parameters;
}
void PASimulator::DoImageProcessing()
{
int numberOfVolumes = 1;
if (m_Controls.checkBoxGenerateBatch->isChecked())
{
if (m_Controls.labelBinarypath->text().isNull() || m_Controls.labelBinarypath->text().isEmpty())
{
QMessageBox::warning(nullptr, QString("Warning"), QString("You need to specify the binary first!"));
return;
}
numberOfVolumes = m_Controls.spinboxNumberVolumes->value();
if (numberOfVolumes < 1)
{
QMessageBox::warning(nullptr, QString("Warning"), QString("You need to create at least one volume!"));
return;
}
}
auto tissueParameters = GetParametersFromUIInput();
for (int volumeIndex = 0; volumeIndex < numberOfVolumes; volumeIndex++)
{
mitk::pa::InSilicoTissueVolume::Pointer volume =
mitk::pa::InSilicoTissueGenerator::GenerateInSilicoData(tissueParameters);
mitk::Image::Pointer tissueVolume = volume->ConvertToMitkImage();
if (m_Controls.checkBoxGenerateBatch->isChecked())
{
std::string nrrdFilePath = m_Controls.label_NrrdFilePath->text().toStdString();
std::string tissueName = m_Controls.lineEditTissueName->text().toStdString();
std::string binaryPath = m_Controls.labelBinarypath->text().toStdString();
long numberOfPhotons = m_Controls.spinboxNumberPhotons->value() * 1000L;
auto batchParameters = mitk::pa::SimulationBatchGeneratorParameters::New();
batchParameters->SetBinaryPath(binaryPath);
batchParameters->SetNrrdFilePath(nrrdFilePath);
batchParameters->SetNumberOfPhotons(numberOfPhotons);
batchParameters->SetTissueName(tissueName);
batchParameters->SetVolumeIndex(volumeIndex);
batchParameters->SetYOffsetLowerThresholdInCentimeters(m_Controls.spinboxFromValue->value());
batchParameters->SetYOffsetUpperThresholdInCentimeters(m_Controls.spinboxToValue->value());
batchParameters->SetYOffsetStepInCentimeters(m_Controls.spinboxStepValue->value());
mitk::pa::SimulationBatchGenerator::WriteBatchFileAndSaveTissueVolume(batchParameters, tissueVolume);
}
else
{
mitk::DataNode::Pointer dataNode = mitk::DataNode::New();
dataNode->SetData(tissueVolume);
dataNode->SetName(m_Controls.lineEditTissueName->text().toStdString());
this->GetDataStorage()->Add(dataNode);
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());
}
}
}
void PASimulator::ClickedGaussBox()
{
if (m_Controls.checkBoxGauss->isChecked())
{
m_Controls.spinboxSigma->setEnabled(true);
m_Controls.labelSigma->setEnabled(true);
}
else
{
m_Controls.spinboxSigma->setEnabled(false);
m_Controls.labelSigma->setEnabled(false);
}
}
void PASimulator::OpenFolder()
{
m_Controls.label_NrrdFilePath->setText(QFileDialog::getExistingDirectory().append("/"));
}
void PASimulator::OpenBinary()
{
m_Controls.labelBinarypath->setText(QFileDialog::getOpenFileName());
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "PASimulator.h"
// Qt
#include <QMessageBox>
#include <QCheckBox>
#include <QFileDialog>
// mitk
#include <mitkImage.h>
#include <mitkDataNode.h>
#include <mitkIOUtil.h>
#include <iostream>
#include <fstream>
const std::string PASimulator::VIEW_ID = "org.mitk.views.pasimulator";
void PASimulator::SetFocus()
{
m_Controls.pushButtonShowRandomTissue->setFocus();
}
void PASimulator::CreateQtPartControl(QWidget *parent)
{
m_Controls.setupUi(parent);
connect(m_Controls.pushButtonShowRandomTissue, SIGNAL(clicked()), this, SLOT(DoImageProcessing()));
connect(m_Controls.checkBoxGauss, SIGNAL(stateChanged(int)), this, SLOT(ClickedGaussBox()));
connect(m_Controls.pushButtonOpenPath, SIGNAL(clicked()), this, SLOT(OpenFolder()));
connect(m_Controls.pushButtonOpenBinary, SIGNAL(clicked()), this, SLOT(OpenBinary()));
connect(m_Controls.checkBoxGenerateBatch, SIGNAL(clicked()), this, SLOT(UpdateVisibilityOfBatchCreation()));
connect(m_Controls.pushButtonAjustWavelength, SIGNAL(clicked()), this, SLOT(UpdateParametersAccordingToWavelength()));
connect(m_Controls.checkBoxRngSeed, SIGNAL(clicked()), this, SLOT(ClickedCheckboxFixedSeed()));
connect(m_Controls.checkBoxRandomizeParameters, SIGNAL(clicked()), this, SLOT(ClickedRandomizePhysicalParameters()));
m_Controls.spinboxSigma->setEnabled(false);
m_Controls.labelSigma->setEnabled(false);
std::string home_env = std::string(std::getenv("HOME"));
if (home_env.empty())
{
home_env = std::string(std::getenv("HOMEPATH"));
}
if (home_env.empty())
{
home_env = "";
}
m_Controls.label_NrrdFilePath->setText(home_env.c_str());
m_PhotoacousticPropertyCalculator = mitk::pa::PropertyCalculator::New();
UpdateVisibilityOfBatchCreation();
ClickedRandomizePhysicalParameters();
ClickedCheckboxFixedSeed();
ClickedGaussBox();
}
void PASimulator::ClickedRandomizePhysicalParameters()
{
m_Controls.spinboxRandomizeParameters->setEnabled(m_Controls.checkBoxRandomizeParameters->isChecked());
}
void PASimulator::ClickedCheckboxFixedSeed()
{
m_Controls.spinBoxRngSeed->setEnabled(m_Controls.checkBoxRngSeed->isChecked());
}
void PASimulator::UpdateParametersAccordingToWavelength()
{
int wavelength = m_Controls.spinboxWavelength->value();
double bloodOxygenation = m_Controls.spinboxBloodOxygenSaturation->value() / 100;
auto result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::BLOOD, wavelength, bloodOxygenation);
m_Controls.spinboxMaxAbsorption->setValue(result.mua);
m_Controls.spinboxMinAbsorption->setValue(result.mua);
m_Controls.spinboxBloodVesselScatteringMinimum->setValue(result.mus);
m_Controls.spinboxBloodVesselScatteringMaximum->setValue(result.mus);
m_Controls.spinboxBloodVesselAnisotropyMinimum->setValue(result.g);
m_Controls.spinboxBloodVesselAnisotropyMaximum->setValue(result.g);
result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::EPIDERMIS, wavelength, bloodOxygenation);
m_Controls.spinboxSkinAbsorption->setValue(result.mua);
m_Controls.spinboxSkinScattering->setValue(result.mus);
m_Controls.spinboxSkinAnisotropy->setValue(result.g);
result = m_PhotoacousticPropertyCalculator->CalculatePropertyForSpecificWavelength(
mitk::pa::PropertyCalculator::TissueType::STANDARD_TISSUE, wavelength, bloodOxygenation);
m_Controls.spinboxBackgroundAbsorption->setValue(result.mua);
m_Controls.spinboxBackgroundScattering->setValue(result.mus);
m_Controls.spinboxBackgroundAnisotropy->setValue(result.g);
}
void PASimulator::UpdateVisibilityOfBatchCreation()
{
m_Controls.widgetBatchFile->setVisible(m_Controls.checkBoxGenerateBatch->isChecked());
}
mitk::pa::TissueGeneratorParameters::Pointer PASimulator::GetParametersFromUIInput()
{
auto parameters = mitk::pa::TissueGeneratorParameters::New();
// Getting settings from UI
// General settings
parameters->SetXDim(m_Controls.spinboxXDim->value());
parameters->SetYDim(m_Controls.spinboxYDim->value());
parameters->SetZDim(m_Controls.spinboxZDim->value());
parameters->SetDoVolumeSmoothing(m_Controls.checkBoxGauss->isChecked());
if (parameters->GetDoVolumeSmoothing())
parameters->SetVolumeSmoothingSigma(m_Controls.spinboxSigma->value());
parameters->SetRandomizePhysicalProperties(m_Controls.checkBoxRandomizeParameters->isChecked());
parameters->SetRandomizePhysicalPropertiesPercentage(m_Controls.spinboxRandomizeParameters->value());
parameters->SetVoxelSpacingInCentimeters(m_Controls.spinboxSpacing->value());
parameters->SetUseRngSeed(m_Controls.checkBoxRngSeed->isChecked());
parameters->SetRngSeed(m_Controls.spinBoxRngSeed->value());
// Monte Carlo simulation parameters
parameters->SetMCflag(m_Controls.spinboxMcFlag->value());
parameters->SetMCLaunchflag(m_Controls.spinboxLaunchFlag->value());
parameters->SetMCBoundaryflag(m_Controls.spinboxboundaryFlag->value());
parameters->SetMCLaunchPointX(m_Controls.spinboxLaunchpointX->value());
parameters->SetMCLaunchPointY(m_Controls.spinboxLaunchpointY->value());
parameters->SetMCLaunchPointZ(m_Controls.spinboxLaunchpointZ->value());
parameters->SetMCFocusPointX(m_Controls.spinboxFocuspointX->value());
parameters->SetMCFocusPointY(m_Controls.spinboxFocuspointY->value());
parameters->SetMCFocusPointZ(m_Controls.spinboxFocuspointZ->value());
parameters->SetMCTrajectoryVectorX(m_Controls.spinboxTrajectoryVectorX->value());
parameters->SetMCTrajectoryVectorY(m_Controls.spinboxTrajectoryVectorY->value());
parameters->SetMCTrajectoryVectorZ(m_Controls.spinboxTrajectoryVectorZ->value());
parameters->SetMCRadius(m_Controls.spinboxRadius->value());
parameters->SetMCWaist(m_Controls.spinboxWaist->value());
// Vessel settings
parameters->SetMaxVesselAbsorption(m_Controls.spinboxMaxAbsorption->value());
parameters->SetMinVesselAbsorption(m_Controls.spinboxMinAbsorption->value());
parameters->SetMaxVesselBending(m_Controls.spinboxMaxBending->value());
parameters->SetMinVesselBending(m_Controls.spinboxMinBending->value());
parameters->SetMaxVesselRadiusInMillimeters(m_Controls.spinboxMaxDiameter->value());
parameters->SetMinVesselRadiusInMillimeters(m_Controls.spinboxMinDiameter->value());
parameters->SetMaxNumberOfVessels(m_Controls.spinboxMaxVessels->value());
parameters->SetMinNumberOfVessels(m_Controls.spinboxMinVessels->value());
parameters->SetMinVesselScattering(m_Controls.spinboxBloodVesselScatteringMinimum->value());
parameters->SetMaxVesselScattering(m_Controls.spinboxBloodVesselScatteringMaximum->value());
parameters->SetMinVesselAnisotropy(m_Controls.spinboxBloodVesselAnisotropyMinimum->value());
parameters->SetMaxVesselAnisotropy(m_Controls.spinboxBloodVesselAnisotropyMaximum->value());
parameters->SetVesselBifurcationFrequency(m_Controls.spinboxBifurcationFrequency->value());
parameters->SetMinVesselZOrigin(m_Controls.spinboxMinSpawnDepth->value());
parameters->SetMaxVesselZOrigin(m_Controls.spinboxMaxSpawnDepth->value());
// Background tissue settings
parameters->SetBackgroundAbsorption(m_Controls.spinboxBackgroundAbsorption->value());
parameters->SetBackgroundScattering(m_Controls.spinboxBackgroundScattering->value());
parameters->SetBackgroundAnisotropy(m_Controls.spinboxBackgroundAnisotropy->value());
// Air settings
parameters->SetAirThicknessInMillimeters(m_Controls.spinboxAirThickness->value());
//Skin tissue settings
parameters->SetSkinThicknessInMillimeters(m_Controls.spinboxSkinThickness->value());
parameters->SetSkinAbsorption(m_Controls.spinboxSkinAbsorption->value());
parameters->SetSkinScattering(m_Controls.spinboxSkinScattering->value());
parameters->SetSkinAnisotropy(m_Controls.spinboxSkinAnisotropy->value());
parameters->SetCalculateNewVesselPositionCallback(&mitk::pa::VesselMeanderStrategy::CalculateRandomlyDivergingPosition);
return parameters;
}
void PASimulator::DoImageProcessing()
{
int numberOfVolumes = 1;
if (m_Controls.checkBoxGenerateBatch->isChecked())
{
if (m_Controls.labelBinarypath->text().isNull() || m_Controls.labelBinarypath->text().isEmpty())
{
QMessageBox::warning(nullptr, QString("Warning"), QString("You need to specify the binary first!"));
return;
}
numberOfVolumes = m_Controls.spinboxNumberVolumes->value();
if (numberOfVolumes < 1)
{
QMessageBox::warning(nullptr, QString("Warning"), QString("You need to create at least one volume!"));
return;
}
}
auto tissueParameters = GetParametersFromUIInput();
for (int volumeIndex = 0; volumeIndex < numberOfVolumes; volumeIndex++)
{
mitk::pa::InSilicoTissueVolume::Pointer volume =
mitk::pa::InSilicoTissueGenerator::GenerateInSilicoData(tissueParameters);
mitk::Image::Pointer tissueVolume = volume->ConvertToMitkImage();
if (m_Controls.checkBoxGenerateBatch->isChecked())
{
std::string nrrdFilePath = m_Controls.label_NrrdFilePath->text().toStdString();
std::string tissueName = m_Controls.lineEditTissueName->text().toStdString();
std::string binaryPath = m_Controls.labelBinarypath->text().toStdString();
long numberOfPhotons = m_Controls.spinboxNumberPhotons->value() * 1000L;
auto batchParameters = mitk::pa::SimulationBatchGeneratorParameters::New();
batchParameters->SetBinaryPath(binaryPath);
batchParameters->SetNrrdFilePath(nrrdFilePath);
batchParameters->SetNumberOfPhotons(numberOfPhotons);
batchParameters->SetTissueName(tissueName);
batchParameters->SetVolumeIndex(volumeIndex);
batchParameters->SetYOffsetLowerThresholdInCentimeters(m_Controls.spinboxFromValue->value());
batchParameters->SetYOffsetUpperThresholdInCentimeters(m_Controls.spinboxToValue->value());
batchParameters->SetYOffsetStepInCentimeters(m_Controls.spinboxStepValue->value());
mitk::pa::SimulationBatchGenerator::WriteBatchFileAndSaveTissueVolume(batchParameters, tissueVolume);
}
else
{
mitk::DataNode::Pointer dataNode = mitk::DataNode::New();
dataNode->SetData(tissueVolume);
dataNode->SetName(m_Controls.lineEditTissueName->text().toStdString());
this->GetDataStorage()->Add(dataNode);
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());
}
}
}
void PASimulator::ClickedGaussBox()
{
if (m_Controls.checkBoxGauss->isChecked())
{
m_Controls.spinboxSigma->setEnabled(true);
m_Controls.labelSigma->setEnabled(true);
}
else
{
m_Controls.spinboxSigma->setEnabled(false);
m_Controls.labelSigma->setEnabled(false);
}
}
void PASimulator::OpenFolder()
{
m_Controls.label_NrrdFilePath->setText(QFileDialog::getExistingDirectory().append("/"));
}
void PASimulator::OpenBinary()
{
m_Controls.labelBinarypath->setText(QFileDialog::getOpenFileName());
}
|
replace char array with std string
|
replace char array with std string
|
C++
|
bsd-3-clause
|
MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,MITK/MITK,fmilano/mitk
|
268a29a7eaaa52c09223e3417c67592667139f1b
|
src/wmcontainer.cc
|
src/wmcontainer.cc
|
/*
* IceWM
*
* Copyright (C) 1997-2001 Marko Macek
*/
#include "config.h"
#include "ylib.h"
#include <X11/keysym.h>
#include "wmcontainer.h"
#include "wmframe.h"
#include "yxapp.h"
#include "prefs.h"
#include <stdio.h>
YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame)
:YWindow(parent)
{
fFrame = frame;
fHaveGrab = false;
fHaveActionGrab = false;
setStyle(wsManager);
setDoubleBuffer(false);
setPointer(YXApplication::leftPointer);
}
YClientContainer::~YClientContainer() {
releaseButtons();
}
void YClientContainer::handleButton(const XButtonEvent &button) {
bool doRaise = false;
bool doActivate = false;
bool firstClick = false;
if (!(button.state & ControlMask) &&
(buttonRaiseMask & (1 << (button.button - 1))) &&
(!useMouseWheel || (button.button != 4 && button.button != 5)))
{
if (focusOnClickClient) {
if (!getFrame()->isTypeDock()) {
doActivate = true;
if (getFrame()->canFocusByMouse() && !getFrame()->focused())
firstClick = true;
}
}
if (raiseOnClickClient) {
doRaise = true;
if (getFrame()->canRaise())
firstClick = true;
}
}
#if 1
if (clientMouseActions) {
unsigned int k = button.button + XK_Pointer_Button1 - 1;
unsigned int m = KEY_MODMASK(button.state);
unsigned int vm = VMod(m);
if (IS_WMKEY(k, vm, gMouseWinSize)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
int px = button.x + x();
int py = button.y + y();
int gx = (px * 3 / (int)width() - 1);
int gy = (py * 3 / (int)height() - 1);
if (gx < 0) gx = -1;
if (gx > 0) gx = 1;
if (gy < 0) gy = -1;
if (gy > 0) gy = 1;
bool doMove = (gx == 0 && gy == 0) ? true : false;
int mx, my;
if (doMove) {
mx = px;
my = py;
} else {
mx = button.x_root;
my = button.y_root;
}
if ((doMove && getFrame()->canMove()) ||
(!doMove && getFrame()->canSize()))
{
getFrame()->startMoveSize(doMove, 1,
gx, gy,
mx, my);
}
return ;
} else if (IS_WMKEY(k, vm, gMouseWinMove)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
if (getFrame()->canMove()) {
int px = button.x + x();
int py = button.y + y();
getFrame()->startMoveSize(1, 1,
0, 0,
px, py);
}
return ;
} else if (IS_WMKEY(k, vm, gMouseWinRaise)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
getFrame()->wmRaise();
return ;
}
}
#endif
///!!! do this first?
if (doActivate) {
bool input = getFrame() ? getFrame()->getInputFocusHint() : true;
if (input)
getFrame()->activate();
}
if (doRaise)
getFrame()->wmRaise();
///!!! it might be nice if this was per-window option (app-request)
if (!firstClick || passFirstClickToClient)
XAllowEvents(xapp->display(), ReplayPointer, CurrentTime);
else
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
XSync(xapp->display(), False);
}
// manage button grab on frame window to capture clicks to client window
// we want to keep the grab when:
// focusOnClickClient && not focused
// || raiseOnClickClient && not can be raised
// ('not on top' != 'can be raised')
// the difference is when we have transients and explicitFocus
// also there is the difference with layers and multiple workspaces
void YClientContainer::grabButtons() {
grabActions();
if (!fHaveGrab && (clickFocus ||
focusOnClickClient ||
raiseOnClickClient))
{
fHaveGrab = true;
XGrabButton(xapp->display(),
AnyButton, AnyModifier,
handle(), True,
ButtonPressMask,
GrabModeSync, GrabModeAsync, None, None);
}
}
void YClientContainer::releaseButtons() {
if (fHaveGrab) {
fHaveGrab = false;
XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle());
fHaveActionGrab = false;
}
grabActions();
}
void YClientContainer::regrabMouse() {
XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle());
if (fHaveActionGrab) {
fHaveActionGrab = false;
grabActions();
}
if (fHaveGrab ) {
fHaveGrab = false;
grabButtons();
}
}
void YClientContainer::grabActions() {
if (clientMouseActions) {
if (!fHaveActionGrab) {
fHaveActionGrab = true;
#ifndef NO_KEYBIND
if (gMouseWinMove.key != 0)
grabVButton(gMouseWinMove.key - XK_Pointer_Button1 + 1, gMouseWinMove.mod);
if (gMouseWinSize.key != 0)
grabVButton(gMouseWinSize.key - XK_Pointer_Button1 + 1, gMouseWinSize.mod);
if (gMouseWinRaise.key != 0)
grabVButton(gMouseWinRaise.key - XK_Pointer_Button1 + 1, gMouseWinRaise.mod);
#endif
}
}
}
void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) {
MSG(("configure request in frame"));
if (getFrame() &&
configureRequest.window == getFrame()->client()->handle())
{
XConfigureRequestEvent cre = configureRequest;
getFrame()->configureClient(cre);
}
}
void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) {
if (mapRequest.window == getFrame()->client()->handle()) {
manager->lockFocus();
getFrame()->setState(WinStateMinimized |
WinStateHidden |
WinStateRollup,
0);
manager->unlockFocus();
bool doActivate = true;
getFrame()->updateFocusOnMap(doActivate);
if (doActivate) {
getFrame()->activateWindow(true);
}
}
}
void YClientContainer::handleCrossing(const XCrossingEvent &crossing) {
if (getFrame() && pointerColormap) {
if (crossing.type == EnterNotify)
manager->setColormapWindow(getFrame());
else if (crossing.type == LeaveNotify &&
crossing.detail != NotifyInferior &&
crossing.mode == NotifyNormal &&
manager->colormapWindow() == getFrame())
{
manager->setColormapWindow(0);
}
}
}
// vim: set sw=4 ts=4 et:
|
/*
* IceWM
*
* Copyright (C) 1997-2001 Marko Macek
*/
#include "config.h"
#include "ylib.h"
#include <X11/keysym.h>
#include "wmcontainer.h"
#include "wmframe.h"
#include "yxapp.h"
#include "prefs.h"
#include <stdio.h>
YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame)
:YWindow(parent)
{
fFrame = frame;
fHaveGrab = false;
fHaveActionGrab = false;
setStyle(wsManager);
setDoubleBuffer(false);
setPointer(YXApplication::leftPointer);
}
YClientContainer::~YClientContainer() {
releaseButtons();
}
void YClientContainer::handleButton(const XButtonEvent &button) {
bool doRaise = false;
bool doActivate = false;
bool firstClick = false;
if (!(button.state & ControlMask) &&
(buttonRaiseMask & (1 << (button.button - 1))) &&
(!useMouseWheel || (button.button != 4 && button.button != 5)))
{
if (focusOnClickClient) {
if (!getFrame()->isTypeDock()) {
doActivate = true;
if (getFrame()->canFocusByMouse() && !getFrame()->focused())
firstClick = true;
}
}
if (raiseOnClickClient) {
doRaise = true;
if (getFrame()->canRaise())
firstClick = true;
}
}
#if 1
if (clientMouseActions) {
unsigned int k = button.button + XK_Pointer_Button1 - 1;
unsigned int m = KEY_MODMASK(button.state);
unsigned int vm = VMod(m);
if (IS_WMKEY(k, vm, gMouseWinSize)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
int px = button.x + x();
int py = button.y + y();
int gx = (px * 3 / (int)width() - 1);
int gy = (py * 3 / (int)height() - 1);
if (gx < 0) gx = -1;
if (gx > 0) gx = 1;
if (gy < 0) gy = -1;
if (gy > 0) gy = 1;
bool doMove = (gx == 0 && gy == 0) ? true : false;
int mx, my;
if (doMove) {
mx = px;
my = py;
} else {
mx = button.x_root;
my = button.y_root;
}
if ((doMove && getFrame()->canMove()) ||
(!doMove && getFrame()->canSize()))
{
getFrame()->startMoveSize(doMove, 1,
gx, gy,
mx, my);
}
return ;
} else if (IS_WMKEY(k, vm, gMouseWinMove)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
if (getFrame()->canMove()) {
int px = button.x + x();
int py = button.y + y();
getFrame()->startMoveSize(1, 1,
0, 0,
px, py);
}
return ;
} else if (IS_WMKEY(k, vm, gMouseWinRaise)) {
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
getFrame()->wmRaise();
return ;
}
}
#endif
///!!! do this first?
if (doActivate && getFrame()->getInputFocusHint())
getFrame()->activate();
if (doRaise)
getFrame()->wmRaise();
///!!! it might be nice if this was per-window option (app-request)
if (!firstClick || passFirstClickToClient)
XAllowEvents(xapp->display(), ReplayPointer, CurrentTime);
else
XAllowEvents(xapp->display(), AsyncPointer, CurrentTime);
XSync(xapp->display(), False);
}
// manage button grab on frame window to capture clicks to client window
// we want to keep the grab when:
// focusOnClickClient && not focused
// || raiseOnClickClient && not can be raised
// ('not on top' != 'can be raised')
// the difference is when we have transients and explicitFocus
// also there is the difference with layers and multiple workspaces
void YClientContainer::grabButtons() {
grabActions();
if (!fHaveGrab && (clickFocus ||
focusOnClickClient ||
raiseOnClickClient))
{
fHaveGrab = true;
XGrabButton(xapp->display(),
AnyButton, AnyModifier,
handle(), True,
ButtonPressMask,
GrabModeSync, GrabModeAsync, None, None);
}
}
void YClientContainer::releaseButtons() {
if (fHaveGrab) {
fHaveGrab = false;
XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle());
fHaveActionGrab = false;
}
grabActions();
}
void YClientContainer::regrabMouse() {
XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle());
if (fHaveActionGrab) {
fHaveActionGrab = false;
grabActions();
}
if (fHaveGrab ) {
fHaveGrab = false;
grabButtons();
}
}
void YClientContainer::grabActions() {
if (clientMouseActions) {
if (!fHaveActionGrab) {
fHaveActionGrab = true;
#ifndef NO_KEYBIND
if (gMouseWinMove.key != 0)
grabVButton(gMouseWinMove.key - XK_Pointer_Button1 + 1, gMouseWinMove.mod);
if (gMouseWinSize.key != 0)
grabVButton(gMouseWinSize.key - XK_Pointer_Button1 + 1, gMouseWinSize.mod);
if (gMouseWinRaise.key != 0)
grabVButton(gMouseWinRaise.key - XK_Pointer_Button1 + 1, gMouseWinRaise.mod);
#endif
}
}
}
void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) {
MSG(("configure request in frame"));
if (getFrame() &&
configureRequest.window == getFrame()->client()->handle())
{
XConfigureRequestEvent cre = configureRequest;
getFrame()->configureClient(cre);
}
}
void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) {
if (mapRequest.window == getFrame()->client()->handle()) {
manager->lockFocus();
getFrame()->setState(WinStateMinimized |
WinStateHidden |
WinStateRollup,
0);
manager->unlockFocus();
bool doActivate = true;
getFrame()->updateFocusOnMap(doActivate);
if (doActivate) {
getFrame()->activateWindow(true);
}
}
}
void YClientContainer::handleCrossing(const XCrossingEvent &crossing) {
if (getFrame() && pointerColormap) {
if (crossing.type == EnterNotify)
manager->setColormapWindow(getFrame());
else if (crossing.type == LeaveNotify &&
crossing.detail != NotifyInferior &&
crossing.mode == NotifyNormal &&
manager->colormapWindow() == getFrame())
{
manager->setColormapWindow(0);
}
}
}
// vim: set sw=4 ts=4 et:
|
remove unnecessary check for frame
|
remove unnecessary check for frame
|
C++
|
lgpl-2.1
|
dicej/icewm,dicej/icewm,dicej/icewm,dicej/icewm
|
f61bd63d59eaa0c769e037ed39858429b46db0a7
|
recognition/include/pcl/recognition/impl/hv/hv_papazov.hpp
|
recognition/include/pcl/recognition/impl/hv/hv_papazov.hpp
|
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <pcl/recognition/hv/hv_papazov.h>
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::initialize ()
{
// initialize mask...
mask_.resize (complete_models_.size ());
for (size_t i = 0; i < complete_models_.size (); i++)
mask_[i] = true;
// initalize model
for (size_t m = 0; m < complete_models_.size (); m++)
{
boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel);
// voxelize model cloud
recog_model->cloud_.reset (new pcl::PointCloud<ModelT>);
recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>);
recog_model->id_ = static_cast<int> (m);
pcl::VoxelGrid<ModelT> voxel_grid;
voxel_grid.setInputCloud (visible_models_[m]);
voxel_grid.setLeafSize (resolution_, resolution_, resolution_);
voxel_grid.filter (*(recog_model->cloud_));
pcl::VoxelGrid<ModelT> voxel_grid_complete;
voxel_grid_complete.setInputCloud (complete_models_[m]);
voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_);
voxel_grid_complete.filter (*(recog_model->complete_cloud_));
std::vector<int> explained_indices;
std::vector<int> outliers;
std::vector<int> nn_indices;
std::vector<float> nn_distances;
for (size_t i = 0; i < recog_model->cloud_->points.size (); i++)
{
if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances,
std::numeric_limits<int>::max ()))
{
outliers.push_back (static_cast<int> (i));
}
else
{
for (size_t k = 0; k < nn_distances.size (); k++)
{
explained_indices.push_back (nn_indices[k]); //nn_indices[k] points to the scene
}
}
}
std::sort (explained_indices.begin (), explained_indices.end ());
explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ());
recog_model->bad_information_ = static_cast<int> (outliers.size ());
if ((static_cast<float> (recog_model->bad_information_) / static_cast<float> (recog_model->complete_cloud_->points.size ()))
<= penalty_threshold_ && (static_cast<float> (explained_indices.size ())
/ static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_)
{
recog_model->explained_ = explained_indices;
recognition_models_.push_back (recog_model);
// update explained_by_RM_, add 1
for (size_t i = 0; i < explained_indices.size (); i++)
{
explained_by_RM_[explained_indices[i]]++;
points_explained_by_rm_[explained_indices[i]].push_back (recog_model);
}
}
else
{
mask_[m] = false; // the model didnt survive the sequential check...
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion ()
{
// iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex
typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator;
VertexIterator vi, vi_end, next;
boost::tie (vi, vi_end) = boost::vertices (conflict_graph_);
for (next = vi; next != vi_end; next++)
{
const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_);
typename boost::graph_traits<Graph>::adjacency_iterator ai;
typename boost::graph_traits<Graph>::adjacency_iterator ai_end;
boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]);
bool a_better_one = false;
for (tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai)
{
boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]);
if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_])
{
a_better_one = true;
}
}
if (a_better_one)
{
mask_[current->id_] = false;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::buildConflictGraph ()
{
// create vertices for the graph
for (size_t i = 0; i < (recognition_models_.size ()); i++)
{
const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_);
graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]);
}
// iterate over the remaining models and check for each one if there is a conflict with another one
for (size_t i = 0; i < recognition_models_.size (); i++)
{
for (size_t j = i; j < recognition_models_.size (); j++)
{
if (i != j)
{
float n_conflicts = 0.f;
// count scene points explained by both models
for (size_t k = 0; k < explained_by_RM_.size (); k++)
{
if (explained_by_RM_[k] > 1)
{
// this point could be a conflict
bool i_found = false;
bool j_found = false;
bool both_found = false;
for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++)
{
if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_)
i_found = true;
if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_)
j_found = true;
if (i_found && j_found)
both_found = true;
}
if (both_found)
n_conflicts += 1.f;
}
}
// check if number of points is big enough to create a conflict
bool add_conflict = false;
add_conflict = ((n_conflicts / static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_)
|| ((n_conflicts / static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_);
if (add_conflict)
{
boost::add_edge (i, j, conflict_graph_);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::verify ()
{
initialize();
buildConflictGraph ();
nonMaximaSuppresion ();
}
|
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <pcl/recognition/hv/hv_papazov.h>
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::initialize ()
{
// initialize mask...
mask_.resize (complete_models_.size ());
for (size_t i = 0; i < complete_models_.size (); i++)
mask_[i] = true;
// initalize model
for (size_t m = 0; m < complete_models_.size (); m++)
{
boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel);
// voxelize model cloud
recog_model->cloud_.reset (new pcl::PointCloud<ModelT>);
recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>);
recog_model->id_ = static_cast<int> (m);
pcl::VoxelGrid<ModelT> voxel_grid;
voxel_grid.setInputCloud (visible_models_[m]);
voxel_grid.setLeafSize (resolution_, resolution_, resolution_);
voxel_grid.filter (*(recog_model->cloud_));
pcl::VoxelGrid<ModelT> voxel_grid_complete;
voxel_grid_complete.setInputCloud (complete_models_[m]);
voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_);
voxel_grid_complete.filter (*(recog_model->complete_cloud_));
std::vector<int> explained_indices;
std::vector<int> outliers;
std::vector<int> nn_indices;
std::vector<float> nn_distances;
for (size_t i = 0; i < recog_model->cloud_->points.size (); i++)
{
if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances,
std::numeric_limits<int>::max ()))
{
outliers.push_back (static_cast<int> (i));
}
else
{
for (size_t k = 0; k < nn_distances.size (); k++)
{
explained_indices.push_back (nn_indices[k]); //nn_indices[k] points to the scene
}
}
}
std::sort (explained_indices.begin (), explained_indices.end ());
explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ());
recog_model->bad_information_ = static_cast<int> (outliers.size ());
if ((static_cast<float> (recog_model->bad_information_) / static_cast<float> (recog_model->complete_cloud_->points.size ()))
<= penalty_threshold_ && (static_cast<float> (explained_indices.size ())
/ static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_)
{
recog_model->explained_ = explained_indices;
recognition_models_.push_back (recog_model);
// update explained_by_RM_, add 1
for (size_t i = 0; i < explained_indices.size (); i++)
{
explained_by_RM_[explained_indices[i]]++;
points_explained_by_rm_[explained_indices[i]].push_back (recog_model);
}
}
else
{
mask_[m] = false; // the model didnt survive the sequential check...
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion ()
{
// iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex
typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator;
VertexIterator vi, vi_end, next;
boost::tie (vi, vi_end) = boost::vertices (conflict_graph_);
for (next = vi; next != vi_end; next++)
{
const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_);
typename boost::graph_traits<Graph>::adjacency_iterator ai;
typename boost::graph_traits<Graph>::adjacency_iterator ai_end;
boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]);
bool a_better_one = false;
for (boost::tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai)
{
boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]);
if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_])
{
a_better_one = true;
}
}
if (a_better_one)
{
mask_[current->id_] = false;
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::buildConflictGraph ()
{
// create vertices for the graph
for (size_t i = 0; i < (recognition_models_.size ()); i++)
{
const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_);
graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]);
}
// iterate over the remaining models and check for each one if there is a conflict with another one
for (size_t i = 0; i < recognition_models_.size (); i++)
{
for (size_t j = i; j < recognition_models_.size (); j++)
{
if (i != j)
{
float n_conflicts = 0.f;
// count scene points explained by both models
for (size_t k = 0; k < explained_by_RM_.size (); k++)
{
if (explained_by_RM_[k] > 1)
{
// this point could be a conflict
bool i_found = false;
bool j_found = false;
bool both_found = false;
for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++)
{
if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_)
i_found = true;
if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_)
j_found = true;
if (i_found && j_found)
both_found = true;
}
if (both_found)
n_conflicts += 1.f;
}
}
// check if number of points is big enough to create a conflict
bool add_conflict = false;
add_conflict = ((n_conflicts / static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_)
|| ((n_conflicts / static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_);
if (add_conflict)
{
boost::add_edge (i, j, conflict_graph_);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
template<typename ModelT, typename SceneT> void
pcl::PapazovHV<ModelT, SceneT>::verify ()
{
initialize();
buildConflictGraph ();
nonMaximaSuppresion ();
}
|
Use fully qualified boost::tie issue reported for boost 1.49 and Windows
|
Use fully qualified boost::tie issue reported for boost 1.49 and Windows
git-svn-id: 1af002208e930b4d920e7c2b948d1e98a012c795@5279 a9d63959-f2ad-4865-b262-bf0e56cfafb6
|
C++
|
bsd-3-clause
|
psoetens/pcl-svn,psoetens/pcl-svn,psoetens/pcl-svn,psoetens/pcl-svn,psoetens/pcl-svn
|
b1c6a47a0d6b816a9bc2d269b5c2e8a657441a37
|
trunk/libmesh/src/numerics/petsc_nonlinear_solver.C
|
trunk/libmesh/src/numerics/petsc_nonlinear_solver.C
|
// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
#include "libmesh_common.h"
#ifdef LIBMESH_HAVE_PETSC
// C++ includes
// Local Includes
#include "nonlinear_implicit_system.h"
#include "petsc_nonlinear_solver.h"
#include "petsc_vector.h"
#include "petsc_matrix.h"
#include "system.h"
//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc. PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
// Older versions of PETSc do not have the different int typedefs.
// On 64-bit machines, PetscInt may actually be a long long int.
// This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
typedef int PetscErrorCode;
typedef int PetscInt;
#endif
//-------------------------------------------------------------------
// this function is called by PETSc at the end of each nonlinear step
PetscErrorCode
__libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)
{
//int ierr=0;
//if (its > 0)
std::cout << " NL step " << its
<< std::scientific
<< ", |residual|_2 = " << fnorm
<< std::endl;
//return ierr;
return 0;
}
//---------------------------------------------------------------
// this function is called by PETSc to evaluate the residual at X
PetscErrorCode
__libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)
{
int ierr=0;
libmesh_assert (x != NULL);
libmesh_assert (r != NULL);
libmesh_assert (ctx != NULL);
PetscNonlinearSolver<Number>* solver =
static_cast<PetscNonlinearSolver<Number>*> (ctx);
NonlinearImplicitSystem &sys = solver->system();
PetscVector<Number> X_global(x), R(r);
PetscVector<Number>& X_sys = *dynamic_cast<PetscVector<Number>*>(sys.solution.get());
// Use the systems update() to get a good local version of the parallel solution
X_global.swap(X_sys);
sys.update();
X_global.swap(X_sys);
R.zero();
if (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);
else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), &R, NULL);
R.close();
return ierr;
}
//---------------------------------------------------------------
// this function is called by PETSc to evaluate the Jacobian at X
PetscErrorCode
__libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)
{
int ierr=0;
libmesh_assert (ctx != NULL);
PetscNonlinearSolver<Number>* solver =
static_cast<PetscNonlinearSolver<Number>*> (ctx);
NonlinearImplicitSystem &sys = solver->system();
PetscMatrix<Number> PC(*pc);
PetscMatrix<Number> Jac(*jac);
PetscVector<Number> X_global(x);
PetscVector<Number>& X_sys = *dynamic_cast<PetscVector<Number>*>(sys.solution.get());
// Use the systems update() to get a good local version of the parallel solution
X_global.swap(X_sys);
sys.update();
X_global.swap(X_sys);
PC.zero();
if (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);
else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), NULL, &PC);
PC.close();
Jac.close();
*msflag = SAME_NONZERO_PATTERN;
return ierr;
}
} // end extern "C"
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// PetscNonlinearSolver<> methods
template <typename T>
void PetscNonlinearSolver<T>::clear ()
{
if (this->initialized())
{
this->_is_initialized = false;
int ierr=0;
ierr = SNESDestroy(_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
}
template <typename T>
void PetscNonlinearSolver<T>::init ()
{
// Initialize the data structures if not done so already.
if (!this->initialized())
{
this->_is_initialized = true;
int ierr=0;
#if PETSC_VERSION_LESS_THAN(2,1,2)
// At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.
// The second argument was of type SNESProblemType, and could have a value of
// either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.
ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
#if PETSC_VERSION_LESS_THAN(2,3,3)
ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,
this, PETSC_NULL);
#else
// API name change in PETSc 2.3.3
ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,
this, PETSC_NULL);
#endif
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetFromOptions(_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
}
template <typename T>
std::pair<unsigned int, Real>
PetscNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, // System Jacobian Matrix
NumericVector<T>& x_in, // Solution vector
NumericVector<T>& r_in, // Residual vector
const double, // Stopping tolerance
const unsigned int)
{
this->init ();
PetscMatrix<T>* jac = dynamic_cast<PetscMatrix<T>*>(&jac_in);
PetscVector<T>* x = dynamic_cast<PetscVector<T>*>(&x_in);
PetscVector<T>* r = dynamic_cast<PetscVector<T>*>(&r_in);
// We cast to pointers so we can be sure that they succeeded
// by comparing the result against NULL.
libmesh_assert(jac != NULL); libmesh_assert(jac->mat() != NULL);
libmesh_assert(x != NULL); libmesh_assert(x->vec() != NULL);
libmesh_assert(r != NULL); libmesh_assert(r->vec() != NULL);
int ierr=0;
int n_iterations =0;
ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Have the Krylov subspace method use our good initial guess rather than 0
KSP ksp;
ierr = SNESGetKSP (_snes, &ksp);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Set the tolerances for the iterative solver. Use the user-supplied
// tolerance for the relative residual & leave the others at default values
ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,
PETSC_DEFAULT, this->max_linear_iterations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Set the tolerances for the non-linear solver.
ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,
this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
//Pull in command-line options
KSPSetFromOptions(ksp);
SNESSetFromOptions(_snes);
// ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);
// CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,
// the last one being a pointer to an int to hold the number of iterations required.
# if PETSC_VERSION_LESS_THAN(2,2,0)
ierr = SNESSolve (_snes, x->vec(), &n_iterations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)
ierr = SNESSolve (_snes, x->vec());
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// 2.3.x & newer style
#else
ierr = SNESSolve (_snes, PETSC_NULL, x->vec());
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
this->clear();
// return the # of its. and the final residual norm. Note that
// n_iterations may be zero for PETSc versions 2.2.x and greater.
return std::make_pair(n_iterations, 0.);
}
//------------------------------------------------------------------
// Explicit instantiations
template class PetscNonlinearSolver<Number>;
#endif // #ifdef LIBMESH_HAVE_PETSC
|
// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
#include "libmesh_common.h"
#ifdef LIBMESH_HAVE_PETSC
// C++ includes
// Local Includes
#include "nonlinear_implicit_system.h"
#include "petsc_nonlinear_solver.h"
#include "petsc_vector.h"
#include "petsc_matrix.h"
#include "system.h"
#include "dof_map.h"
//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc. PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
// Older versions of PETSc do not have the different int typedefs.
// On 64-bit machines, PetscInt may actually be a long long int.
// This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
typedef int PetscErrorCode;
typedef int PetscInt;
#endif
//-------------------------------------------------------------------
// this function is called by PETSc at the end of each nonlinear step
PetscErrorCode
__libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)
{
//int ierr=0;
//if (its > 0)
std::cout << " NL step " << its
<< std::scientific
<< ", |residual|_2 = " << fnorm
<< std::endl;
//return ierr;
return 0;
}
//---------------------------------------------------------------
// this function is called by PETSc to evaluate the residual at X
PetscErrorCode
__libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)
{
int ierr=0;
libmesh_assert (x != NULL);
libmesh_assert (r != NULL);
libmesh_assert (ctx != NULL);
PetscNonlinearSolver<Number>* solver =
static_cast<PetscNonlinearSolver<Number>*> (ctx);
NonlinearImplicitSystem &sys = solver->system();
PetscVector<Number> X_global(x), R(r);
PetscVector<Number>& X_sys = *dynamic_cast<PetscVector<Number>*>(sys.solution.get());
PetscVector<Number>& R_sys = *dynamic_cast<PetscVector<Number>*>(sys.rhs);
// Use the systems update() to get a good local version of the parallel solution
X_global.swap(X_sys);
R.swap(R_sys);
sys.get_dof_map().enforce_constraints_exactly(sys);
sys.update();
//Swap back
X_global.swap(X_sys);
R.swap(R_sys);
R.zero();
if (solver->residual != NULL) solver->residual (*sys.current_local_solution.get(), R);
else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), &R, NULL);
R.close();
X_global.close();
return ierr;
}
//---------------------------------------------------------------
// this function is called by PETSc to evaluate the Jacobian at X
PetscErrorCode
__libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)
{
int ierr=0;
libmesh_assert (ctx != NULL);
PetscNonlinearSolver<Number>* solver =
static_cast<PetscNonlinearSolver<Number>*> (ctx);
NonlinearImplicitSystem &sys = solver->system();
PetscMatrix<Number> PC(*pc);
PetscMatrix<Number> Jac(*jac);
PetscVector<Number> X_global(x);
PetscVector<Number>& X_sys = *dynamic_cast<PetscVector<Number>*>(sys.solution.get());
PetscMatrix<Number>& Jac_sys = *dynamic_cast<PetscMatrix<Number>*>(sys.matrix);
// Use the systems update() to get a good local version of the parallel solution
X_global.swap(X_sys);
Jac.swap(Jac_sys);
sys.get_dof_map().enforce_constraints_exactly(sys);
sys.update();
X_global.swap(X_sys);
Jac.swap(Jac_sys);
PC.zero();
if (solver->jacobian != NULL) solver->jacobian (*sys.current_local_solution.get(), PC);
else if (solver->matvec != NULL) solver->matvec (*sys.current_local_solution.get(), NULL, &PC);
PC.close();
Jac.close();
X_global.close();
*msflag = SAME_NONZERO_PATTERN;
return ierr;
}
} // end extern "C"
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// PetscNonlinearSolver<> methods
template <typename T>
void PetscNonlinearSolver<T>::clear ()
{
if (this->initialized())
{
this->_is_initialized = false;
int ierr=0;
ierr = SNESDestroy(_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
}
template <typename T>
void PetscNonlinearSolver<T>::init ()
{
// Initialize the data structures if not done so already.
if (!this->initialized())
{
this->_is_initialized = true;
int ierr=0;
#if PETSC_VERSION_LESS_THAN(2,1,2)
// At least until Petsc 2.1.1, the SNESCreate had a different calling syntax.
// The second argument was of type SNESProblemType, and could have a value of
// either SNES_NONLINEAR_EQUATIONS or SNES_UNCONSTRAINED_MINIMIZATION.
ierr = SNESCreate(libMesh::COMM_WORLD, SNES_NONLINEAR_EQUATIONS, &_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#else
ierr = SNESCreate(libMesh::COMM_WORLD,&_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
#if PETSC_VERSION_LESS_THAN(2,3,3)
ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,
this, PETSC_NULL);
#else
// API name change in PETSc 2.3.3
ierr = SNESMonitorSet (_snes, __libmesh_petsc_snes_monitor,
this, PETSC_NULL);
#endif
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetFromOptions(_snes);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
}
}
template <typename T>
std::pair<unsigned int, Real>
PetscNonlinearSolver<T>::solve (SparseMatrix<T>& jac_in, // System Jacobian Matrix
NumericVector<T>& x_in, // Solution vector
NumericVector<T>& r_in, // Residual vector
const double, // Stopping tolerance
const unsigned int)
{
this->init ();
PetscMatrix<T>* jac = dynamic_cast<PetscMatrix<T>*>(&jac_in);
PetscVector<T>* x = dynamic_cast<PetscVector<T>*>(&x_in);
PetscVector<T>* r = dynamic_cast<PetscVector<T>*>(&r_in);
// We cast to pointers so we can be sure that they succeeded
// by comparing the result against NULL.
libmesh_assert(jac != NULL); libmesh_assert(jac->mat() != NULL);
libmesh_assert(x != NULL); libmesh_assert(x->vec() != NULL);
libmesh_assert(r != NULL); libmesh_assert(r->vec() != NULL);
int ierr=0;
int n_iterations =0;
ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Have the Krylov subspace method use our good initial guess rather than 0
KSP ksp;
ierr = SNESGetKSP (_snes, &ksp);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Set the tolerances for the iterative solver. Use the user-supplied
// tolerance for the relative residual & leave the others at default values
ierr = KSPSetTolerances (ksp, this->initial_linear_tolerance, PETSC_DEFAULT,
PETSC_DEFAULT, this->max_linear_iterations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Set the tolerances for the non-linear solver.
ierr = SNESSetTolerances(_snes, this->absolute_residual_tolerance, this->relative_residual_tolerance,
this->absolute_step_tolerance, this->max_nonlinear_iterations, this->max_function_evaluations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
//Pull in command-line options
KSPSetFromOptions(ksp);
SNESSetFromOptions(_snes);
// ierr = KSPSetInitialGuessNonzero (ksp, PETSC_TRUE);
// CHKERRABORT(libMesh::COMM_WORLD,ierr);
// Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,
// the last one being a pointer to an int to hold the number of iterations required.
# if PETSC_VERSION_LESS_THAN(2,2,0)
ierr = SNESSolve (_snes, x->vec(), &n_iterations);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)
ierr = SNESSolve (_snes, x->vec());
CHKERRABORT(libMesh::COMM_WORLD,ierr);
// 2.3.x & newer style
#else
ierr = SNESSolve (_snes, PETSC_NULL, x->vec());
CHKERRABORT(libMesh::COMM_WORLD,ierr);
#endif
this->clear();
// return the # of its. and the final residual norm. Note that
// n_iterations may be zero for PETSc versions 2.2.x and greater.
return std::make_pair(n_iterations, 0.);
}
//------------------------------------------------------------------
// Explicit instantiations
template class PetscNonlinearSolver<Number>;
#endif // #ifdef LIBMESH_HAVE_PETSC
|
make petsc nonlinear solver work with adaptivity
|
make petsc nonlinear solver work with adaptivity
git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@3073 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
|
C++
|
lgpl-2.1
|
BalticPinguin/libmesh,pbauman/libmesh,roystgnr/libmesh,balborian/libmesh,svallaghe/libmesh,libMesh/libmesh,dschwen/libmesh,hrittich/libmesh,balborian/libmesh,svallaghe/libmesh,hrittich/libmesh,aeslaughter/libmesh,pbauman/libmesh,capitalaslash/libmesh,friedmud/libmesh,libMesh/libmesh,coreymbryant/libmesh,balborian/libmesh,libMesh/libmesh,vikramvgarg/libmesh,friedmud/libmesh,pbauman/libmesh,balborian/libmesh,dknez/libmesh,benkirk/libmesh,friedmud/libmesh,dknez/libmesh,benkirk/libmesh,vikramvgarg/libmesh,benkirk/libmesh,90jrong/libmesh,dknez/libmesh,90jrong/libmesh,cahaynes/libmesh,pbauman/libmesh,roystgnr/libmesh,dschwen/libmesh,dschwen/libmesh,jwpeterson/libmesh,cahaynes/libmesh,libMesh/libmesh,svallaghe/libmesh,giorgiobornia/libmesh,dmcdougall/libmesh,giorgiobornia/libmesh,dschwen/libmesh,vikramvgarg/libmesh,coreymbryant/libmesh,dknez/libmesh,capitalaslash/libmesh,dschwen/libmesh,hrittich/libmesh,jwpeterson/libmesh,balborian/libmesh,dmcdougall/libmesh,hrittich/libmesh,libMesh/libmesh,benkirk/libmesh,friedmud/libmesh,dmcdougall/libmesh,90jrong/libmesh,dmcdougall/libmesh,BalticPinguin/libmesh,90jrong/libmesh,libMesh/libmesh,dknez/libmesh,BalticPinguin/libmesh,90jrong/libmesh,coreymbryant/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,balborian/libmesh,aeslaughter/libmesh,90jrong/libmesh,dknez/libmesh,giorgiobornia/libmesh,vikramvgarg/libmesh,balborian/libmesh,jwpeterson/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,roystgnr/libmesh,coreymbryant/libmesh,balborian/libmesh,friedmud/libmesh,svallaghe/libmesh,90jrong/libmesh,dknez/libmesh,hrittich/libmesh,dmcdougall/libmesh,dschwen/libmesh,dschwen/libmesh,dmcdougall/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,hrittich/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,cahaynes/libmesh,roystgnr/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,90jrong/libmesh,aeslaughter/libmesh,svallaghe/libmesh,svallaghe/libmesh,svallaghe/libmesh,cahaynes/libmesh,pbauman/libmesh,balborian/libmesh,cahaynes/libmesh,friedmud/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,friedmud/libmesh,hrittich/libmesh,capitalaslash/libmesh,roystgnr/libmesh,capitalaslash/libmesh,libMesh/libmesh,svallaghe/libmesh,jwpeterson/libmesh,libMesh/libmesh,roystgnr/libmesh,aeslaughter/libmesh,roystgnr/libmesh,hrittich/libmesh,friedmud/libmesh,pbauman/libmesh,benkirk/libmesh,aeslaughter/libmesh,hrittich/libmesh,pbauman/libmesh,svallaghe/libmesh,pbauman/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,benkirk/libmesh,jwpeterson/libmesh,roystgnr/libmesh,benkirk/libmesh,dmcdougall/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,friedmud/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,90jrong/libmesh,coreymbryant/libmesh,aeslaughter/libmesh,aeslaughter/libmesh,benkirk/libmesh,cahaynes/libmesh,dschwen/libmesh,balborian/libmesh,benkirk/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,pbauman/libmesh,giorgiobornia/libmesh,cahaynes/libmesh,vikramvgarg/libmesh,dmcdougall/libmesh,dknez/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,cahaynes/libmesh
|
8e5eacc1364632e870bffd3aff1a601dbf2f67dd
|
decoder/vaapidecoder_vp9.cpp
|
decoder/vaapidecoder_vp9.cpp
|
/*
* Copyright (C) 2013-2014 Intel Corporation. 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#ifdef ANDROID
#include <functional>
#else
#include <tr1/functional>
#endif
#include "common/log.h"
#include "vaapidecoder_vp9.h"
#include "vaapidecoder_factory.h"
namespace YamiMediaCodec{
typedef VaapiDecoderVP9::PicturePtr PicturePtr;
VaapiDecoderVP9::VaapiDecoderVP9()
{
m_parser.reset(vp9_parser_new(), vp9_parser_free);
m_reference.resize(VP9_REF_FRAMES);
}
VaapiDecoderVP9::~VaapiDecoderVP9()
{
stop();
}
Decode_Status VaapiDecoderVP9::start(VideoConfigBuffer * buffer)
{
DEBUG("VP9: start() buffer size: %d x %d", buffer->width,
buffer->height);
buffer->profile = VAProfileVP9Profile0;
//8 reference frame + extra number
buffer->surfaceNumber = 8 + VP9_EXTRA_SURFACE_NUMBER;
DEBUG("disable native graphics buffer");
buffer->flag &= ~USE_NATIVE_GRAPHIC_BUFFER;
m_configBuffer = *buffer;
m_configBuffer.data = NULL;
m_configBuffer.size = 0;
if (m_configBuffer.width && m_configBuffer.height) {
m_configBuffer.surfaceWidth = ALIGN8(m_configBuffer.width);
m_configBuffer.surfaceHeight = ALIGN32(m_configBuffer.height);
Decode_Status status = VaapiDecoderBase::start(&m_configBuffer);
if (status != DECODE_SUCCESS)
return status;
}
return DECODE_SUCCESS;
}
Decode_Status VaapiDecoderVP9::reset(VideoConfigBuffer * buffer)
{
DEBUG("VP9: reset()");
return VaapiDecoderBase::reset(buffer);
}
void VaapiDecoderVP9::stop(void)
{
DEBUG("VP9: stop()");
flush();
VaapiDecoderBase::stop();
}
void VaapiDecoderVP9::flush(void)
{
m_parser.reset(vp9_parser_new(), vp9_parser_free);
m_reference.clear();
m_reference.resize(VP9_REF_FRAMES);
VaapiDecoderBase::flush();
}
Decode_Status VaapiDecoderVP9::ensureContext(const Vp9FrameHdr* hdr)
{
// only reset va context when there is a larger frame
if (m_configBuffer.width < hdr->width
|| m_configBuffer.height < hdr->height) {
INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d",
m_configBuffer.width, m_configBuffer.height, hdr->width, hdr->height);
Decode_Status status = VaapiDecoderBase::terminateVA();
if (status != DECODE_SUCCESS)
return status;
m_configBuffer.width = hdr->width;
m_configBuffer.height = hdr->height;
m_configBuffer.surfaceWidth = ALIGN8(hdr->width);
m_configBuffer.surfaceHeight = ALIGN32(hdr->height);
status = VaapiDecoderBase::start(&m_configBuffer);
if (status != DECODE_SUCCESS)
return status;
return DECODE_FORMAT_CHANGE;
} else if ((m_videoFormatInfo.width != hdr->width
|| m_videoFormatInfo.height != hdr->height) &&
(!hdr->show_existing_frame)) {
// notify client of resolution change, no need to reset hw context
INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d\n", m_videoFormatInfo.width, m_videoFormatInfo.height, hdr->width, hdr->height);
m_videoFormatInfo.width = hdr->width;
m_videoFormatInfo.height = hdr->height;
return DECODE_FORMAT_CHANGE;
}
return DECODE_SUCCESS;
}
bool VaapiDecoderVP9::fillReference(VADecPictureParameterBufferVP9* param, const Vp9FrameHdr* hdr)
{
#define FILL_REFERENCE(vafield, ref) \
do { \
int idx = ref - VP9_LAST_FRAME; \
if (!m_reference[idx]) { \
ERROR("reference to %d is invalid", idx); \
return false; \
} \
param->pic_fields.bits.vafield = hdr->ref_frame_indices[idx]; \
param->pic_fields.bits.vafield##_sign_bias = hdr->ref_frame_sign_bias[idx]; \
} while (0)
if (hdr->frame_type == VP9_KEY_FRAME) {
m_reference.clear();
m_reference.resize(VP9_REF_FRAMES);
} else {
FILL_REFERENCE(last_ref_frame, VP9_LAST_FRAME);
FILL_REFERENCE(golden_ref_frame, VP9_GOLDEN_FRAME);
FILL_REFERENCE(alt_ref_frame, VP9_ALTREF_FRAME);
}
for (size_t i = 0; i < m_reference.size(); i++) {
SurfacePtr& surface = m_reference[i];
param->reference_frames[i] = surface.get() ? surface->getID():VA_INVALID_SURFACE;
}
return true;
#undef FILL_REFERENCE
}
void VaapiDecoderVP9::updateReference(const PicturePtr& picture, const Vp9FrameHdr* hdr)
{
uint8_t flag = 1;
uint8_t refresh_frame_flags;
if (hdr->frame_type == VP9_KEY_FRAME) {
refresh_frame_flags = 0xff;
} else {
refresh_frame_flags = hdr->refresh_frame_flags;
}
for (int i = 0; i < VP9_REF_FRAMES; i++) {
if (refresh_frame_flags & flag) {
m_reference[i] = picture->getSurface();
}
flag <<= 1;
}
}
bool VaapiDecoderVP9::ensurePicture(const PicturePtr& picture, const Vp9FrameHdr* hdr)
{
VADecPictureParameterBufferVP9* param;
if (!picture->editPicture(param))
return false;
param->frame_width = hdr->width;
param->frame_height = hdr->height;
if (!fillReference(param, hdr))
return false;
#define FILL_PIC_FIELD(field) param->pic_fields.bits.field = hdr->field;
FILL_PIC_FIELD(subsampling_x)
FILL_PIC_FIELD(subsampling_y)
FILL_PIC_FIELD(frame_type)
FILL_PIC_FIELD(show_frame)
FILL_PIC_FIELD(error_resilient_mode)
FILL_PIC_FIELD(intra_only)
FILL_PIC_FIELD(allow_high_precision_mv)
FILL_PIC_FIELD(mcomp_filter_type)
FILL_PIC_FIELD(frame_parallel_decoding_mode)
FILL_PIC_FIELD(reset_frame_context)
FILL_PIC_FIELD(refresh_frame_context)
FILL_PIC_FIELD(frame_context_idx)
#undef FILL_PIC_FIELD
param->pic_fields.bits.segmentation_enabled = hdr->segmentation.enabled;
param->pic_fields.bits.segmentation_temporal_update = hdr->segmentation.temporal_update;
param->pic_fields.bits.segmentation_update_map = hdr->segmentation.update_map;
param->pic_fields.bits.lossless_flag = m_parser->lossless_flag;
param->filter_level = hdr->loopfilter.filter_level;
param->sharpness_level = hdr->loopfilter.sharpness_level;
#define FILL_FIELD(field) param->field = hdr->field;
FILL_FIELD(log2_tile_rows);
FILL_FIELD(log2_tile_columns);
FILL_FIELD(frame_header_length_in_bytes)
FILL_FIELD(first_partition_size)
#undef FILL_FIELD
assert(sizeof(param->mb_segment_tree_probs) == sizeof(m_parser->mb_segment_tree_probs));
assert(sizeof(param->segment_pred_probs) == sizeof(m_parser->segment_pred_probs));
memcpy(param->mb_segment_tree_probs, m_parser->mb_segment_tree_probs, sizeof(m_parser->mb_segment_tree_probs));
memcpy(param->segment_pred_probs, m_parser->segment_pred_probs, sizeof(m_parser->segment_pred_probs));
return true;
}
bool VaapiDecoderVP9::ensureSlice(const PicturePtr& picture, const void* data, int size)
{
#define FILL_FIELD(field) vaseg.field = seg.field;
VASliceParameterBufferVP9* slice;
if (!picture->newSlice(slice, data, size))
return false;
for (int i = 0; i < VP9_MAX_SEGMENTS; i++) {
VASegmentParameterVP9& vaseg = slice->seg_param[i];
Vp9Segmentation& seg = m_parser->segmentation[i];
memcpy(vaseg.filter_level, seg.filter_level, sizeof(seg.filter_level));
FILL_FIELD(luma_ac_quant_scale)
FILL_FIELD(luma_dc_quant_scale)
FILL_FIELD(chroma_ac_quant_scale)
FILL_FIELD(chroma_dc_quant_scale)
vaseg.segment_flags.fields.segment_reference_skipped = seg.reference_skip;
vaseg.segment_flags.fields.segment_reference_enabled = seg.reference_frame_enabled;
vaseg.segment_flags.fields.segment_reference = seg.reference_frame;
}
#undef FILL_FIELD
return true;
}
Decode_Status VaapiDecoderVP9::decode(const Vp9FrameHdr* hdr, const uint8_t* data, uint32_t size, uint64_t timeStamp)
{
Decode_Status ret;
ret = ensureContext(hdr);
if (ret != DECODE_SUCCESS)
return ret;
PicturePtr picture = createPicture(timeStamp);
if (!picture)
return DECODE_MEMORY_FAIL;
if (hdr->show_existing_frame) {
SurfacePtr& surface = m_reference[hdr->frame_to_show];
if (!surface) {
ERROR("frame to show is invalid, idx = %d", hdr->frame_to_show);
return DECODE_SUCCESS;
}
picture->setSurface(surface);
return outputPicture(picture);
}
if (!picture->getSurface()->resize(hdr->width, hdr->height)) {
ERROR("resize to %dx%d failed", hdr->width, hdr->height);
return DECODE_MEMORY_FAIL;
}
if (!ensurePicture(picture, hdr))
return DECODE_FAIL;
if (!ensureSlice(picture, data, size))
return DECODE_FAIL;
ret = picture->decode();
if (ret != DECODE_SUCCESS)
return ret;
updateReference(picture, hdr);
if (hdr->show_frame)
return outputPicture(picture);
return DECODE_SUCCESS;
}
static bool parse_super_frame(std::vector<uint32_t>& frameSize, const uint8_t* data, const size_t size)
{
if (!data || !size)
return false;
uint8_t marker;
marker = *(data + size - 1);
if ((marker & 0xe0) != 0xc0) {
frameSize.push_back(size);
return true;
}
const uint32_t frames = (marker & 0x7) + 1;
const uint32_t mag = ((marker >> 3) & 0x3) + 1;
const size_t indexSz = 2 + mag * frames;
if (size < indexSz)
return false;
data += size - indexSz;
const uint8_t marker2 = *data++;
if (marker != marker2)
return false;
for (uint32_t i = 0; i < frames; i++) {
uint32_t sz = 0;
for (uint32_t j = 0; j < mag; j++) {
sz |= (*data++) << (j * 8);
}
frameSize.push_back(sz);
}
return true;
}
Decode_Status VaapiDecoderVP9::decode(VideoDecodeBuffer * buffer)
{
Decode_Status status;
if (!buffer)
return DECODE_INVALID_DATA;
uint8_t* data = buffer->data;
size_t size = buffer->size;
uint8_t* end = data + size;
std::vector<uint32_t> frameSize;
if (!parse_super_frame(frameSize, data, size))
return DECODE_INVALID_DATA;
for (size_t i = 0; i < frameSize.size(); i++) {
uint32_t sz = frameSize[i];
if (data + sz > end)
return DECODE_INVALID_DATA;
status = decode(data, sz, buffer->timeStamp);
if (status != DECODE_SUCCESS)
return status;
data += sz;
}
return DECODE_SUCCESS;
}
Decode_Status VaapiDecoderVP9::decode(const uint8_t* data, uint32_t size, uint64_t timeStamp)
{
Vp9FrameHdr hdr;
if (!m_parser)
return DECODE_MEMORY_FAIL;
if (vp9_parse_frame_header(m_parser.get(), &hdr, data, size) != VP9_PARSER_OK)
return DECODE_INVALID_DATA;
if (hdr.first_partition_size + hdr.frame_header_length_in_bytes > size)
return DECODE_INVALID_DATA;
return decode(&hdr, data, size, timeStamp);
}
const bool VaapiDecoderVP9::s_registered =
VaapiDecoderFactory::register_<VaapiDecoderVP9>(YAMI_MIME_VP9);
}
|
/*
* Copyright (C) 2013-2014 Intel Corporation. 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#ifdef ANDROID
#include <functional>
#else
#include <tr1/functional>
#endif
#include "common/log.h"
#include "vaapidecoder_vp9.h"
#include "vaapidecoder_factory.h"
namespace YamiMediaCodec{
typedef VaapiDecoderVP9::PicturePtr PicturePtr;
VaapiDecoderVP9::VaapiDecoderVP9()
{
m_parser.reset(vp9_parser_new(), vp9_parser_free);
m_reference.resize(VP9_REF_FRAMES);
}
VaapiDecoderVP9::~VaapiDecoderVP9()
{
stop();
}
Decode_Status VaapiDecoderVP9::start(VideoConfigBuffer * buffer)
{
DEBUG("VP9: start() buffer size: %d x %d", buffer->width,
buffer->height);
buffer->profile = VAProfileVP9Profile0;
//8 reference frame + extra number
buffer->surfaceNumber = 8 + VP9_EXTRA_SURFACE_NUMBER;
DEBUG("disable native graphics buffer");
buffer->flag &= ~USE_NATIVE_GRAPHIC_BUFFER;
m_configBuffer = *buffer;
m_configBuffer.data = NULL;
m_configBuffer.size = 0;
if (m_configBuffer.width && m_configBuffer.height) {
m_configBuffer.surfaceWidth = ALIGN8(m_configBuffer.width);
m_configBuffer.surfaceHeight = ALIGN32(m_configBuffer.height);
Decode_Status status = VaapiDecoderBase::start(&m_configBuffer);
if (status != DECODE_SUCCESS)
return status;
}
return DECODE_SUCCESS;
}
Decode_Status VaapiDecoderVP9::reset(VideoConfigBuffer * buffer)
{
DEBUG("VP9: reset()");
return VaapiDecoderBase::reset(buffer);
}
void VaapiDecoderVP9::stop(void)
{
DEBUG("VP9: stop()");
flush();
VaapiDecoderBase::stop();
}
void VaapiDecoderVP9::flush(void)
{
m_parser.reset(vp9_parser_new(), vp9_parser_free);
m_reference.clear();
m_reference.resize(VP9_REF_FRAMES);
VaapiDecoderBase::flush();
}
Decode_Status VaapiDecoderVP9::ensureContext(const Vp9FrameHdr* hdr)
{
// only reset va context when there is a larger frame
if (m_configBuffer.width < hdr->width
|| m_configBuffer.height < hdr->height) {
INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d",
m_configBuffer.width, m_configBuffer.height, hdr->width, hdr->height);
Decode_Status status = VaapiDecoderBase::terminateVA();
if (status != DECODE_SUCCESS)
return status;
m_configBuffer.width = hdr->width;
m_configBuffer.height = hdr->height;
m_configBuffer.surfaceWidth = ALIGN8(hdr->width);
m_configBuffer.surfaceHeight = ALIGN32(hdr->height);
status = VaapiDecoderBase::start(&m_configBuffer);
if (status != DECODE_SUCCESS)
return status;
return DECODE_FORMAT_CHANGE;
} else if ((m_videoFormatInfo.width != hdr->width
|| m_videoFormatInfo.height != hdr->height) &&
(!hdr->show_existing_frame)) {
// notify client of resolution change, no need to reset hw context
INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d\n", m_videoFormatInfo.width, m_videoFormatInfo.height, hdr->width, hdr->height);
m_videoFormatInfo.width = hdr->width;
m_videoFormatInfo.height = hdr->height;
return DECODE_FORMAT_CHANGE;
}
return DECODE_SUCCESS;
}
bool VaapiDecoderVP9::fillReference(VADecPictureParameterBufferVP9* param, const Vp9FrameHdr* hdr)
{
#define FILL_REFERENCE(vafield, ref) \
do { \
int idx = ref - VP9_LAST_FRAME; \
if (!m_reference[idx]) { \
ERROR("reference to %d is invalid", idx); \
return false; \
} \
param->pic_fields.bits.vafield = hdr->ref_frame_indices[idx]; \
param->pic_fields.bits.vafield##_sign_bias = hdr->ref_frame_sign_bias[idx]; \
} while (0)
if (hdr->frame_type == VP9_KEY_FRAME) {
m_reference.clear();
m_reference.resize(VP9_REF_FRAMES);
} else {
FILL_REFERENCE(last_ref_frame, VP9_LAST_FRAME);
FILL_REFERENCE(golden_ref_frame, VP9_GOLDEN_FRAME);
FILL_REFERENCE(alt_ref_frame, VP9_ALTREF_FRAME);
}
for (size_t i = 0; i < m_reference.size(); i++) {
SurfacePtr& surface = m_reference[i];
param->reference_frames[i] = surface.get() ? surface->getID():VA_INVALID_SURFACE;
}
return true;
#undef FILL_REFERENCE
}
void VaapiDecoderVP9::updateReference(const PicturePtr& picture, const Vp9FrameHdr* hdr)
{
uint8_t flag = 1;
uint8_t refresh_frame_flags;
if (hdr->frame_type == VP9_KEY_FRAME) {
refresh_frame_flags = 0xff;
} else {
refresh_frame_flags = hdr->refresh_frame_flags;
}
for (int i = 0; i < VP9_REF_FRAMES; i++) {
if (refresh_frame_flags & flag) {
m_reference[i] = picture->getSurface();
}
flag <<= 1;
}
}
bool VaapiDecoderVP9::ensurePicture(const PicturePtr& picture, const Vp9FrameHdr* hdr)
{
VADecPictureParameterBufferVP9* param;
if (!picture->editPicture(param))
return false;
param->frame_width = hdr->width;
param->frame_height = hdr->height;
if (!fillReference(param, hdr))
return false;
#define FILL_PIC_FIELD(field) param->pic_fields.bits.field = hdr->field;
FILL_PIC_FIELD(subsampling_x)
FILL_PIC_FIELD(subsampling_y)
FILL_PIC_FIELD(frame_type)
FILL_PIC_FIELD(show_frame)
FILL_PIC_FIELD(error_resilient_mode)
FILL_PIC_FIELD(intra_only)
FILL_PIC_FIELD(allow_high_precision_mv)
FILL_PIC_FIELD(mcomp_filter_type)
FILL_PIC_FIELD(frame_parallel_decoding_mode)
FILL_PIC_FIELD(reset_frame_context)
FILL_PIC_FIELD(refresh_frame_context)
FILL_PIC_FIELD(frame_context_idx)
#undef FILL_PIC_FIELD
param->pic_fields.bits.segmentation_enabled = hdr->segmentation.enabled;
param->pic_fields.bits.segmentation_temporal_update = hdr->segmentation.temporal_update;
param->pic_fields.bits.segmentation_update_map = hdr->segmentation.update_map;
param->pic_fields.bits.lossless_flag = m_parser->lossless_flag;
param->filter_level = hdr->loopfilter.filter_level;
param->sharpness_level = hdr->loopfilter.sharpness_level;
#define FILL_FIELD(field) param->field = hdr->field;
FILL_FIELD(log2_tile_rows);
FILL_FIELD(log2_tile_columns);
FILL_FIELD(frame_header_length_in_bytes)
FILL_FIELD(first_partition_size)
#undef FILL_FIELD
assert(sizeof(param->mb_segment_tree_probs) == sizeof(m_parser->mb_segment_tree_probs));
assert(sizeof(param->segment_pred_probs) == sizeof(m_parser->segment_pred_probs));
memcpy(param->mb_segment_tree_probs, m_parser->mb_segment_tree_probs, sizeof(m_parser->mb_segment_tree_probs));
memcpy(param->segment_pred_probs, m_parser->segment_pred_probs, sizeof(m_parser->segment_pred_probs));
return true;
}
bool VaapiDecoderVP9::ensureSlice(const PicturePtr& picture, const void* data, int size)
{
#define FILL_FIELD(field) vaseg.field = seg.field;
VASliceParameterBufferVP9* slice;
if (!picture->newSlice(slice, data, size))
return false;
for (int i = 0; i < VP9_MAX_SEGMENTS; i++) {
VASegmentParameterVP9& vaseg = slice->seg_param[i];
Vp9Segmentation& seg = m_parser->segmentation[i];
memcpy(vaseg.filter_level, seg.filter_level, sizeof(seg.filter_level));
FILL_FIELD(luma_ac_quant_scale)
FILL_FIELD(luma_dc_quant_scale)
FILL_FIELD(chroma_ac_quant_scale)
FILL_FIELD(chroma_dc_quant_scale)
vaseg.segment_flags.fields.segment_reference_skipped = seg.reference_skip;
vaseg.segment_flags.fields.segment_reference_enabled = seg.reference_frame_enabled;
vaseg.segment_flags.fields.segment_reference = seg.reference_frame;
}
#undef FILL_FIELD
return true;
}
Decode_Status VaapiDecoderVP9::decode(const Vp9FrameHdr* hdr, const uint8_t* data, uint32_t size, uint64_t timeStamp)
{
Decode_Status ret;
ret = ensureContext(hdr);
if (ret != DECODE_SUCCESS)
return ret;
PicturePtr picture = createPicture(timeStamp);
if (!picture)
return DECODE_MEMORY_FAIL;
if (hdr->show_existing_frame) {
SurfacePtr& surface = m_reference[hdr->frame_to_show];
if (!surface) {
ERROR("frame to show is invalid, idx = %d", hdr->frame_to_show);
return DECODE_SUCCESS;
}
picture->setSurface(surface);
return outputPicture(picture);
}
if (!picture->getSurface()->setCrop(0, 0, hdr->width, hdr->height)) {
ERROR("resize to %dx%d failed", hdr->width, hdr->height);
return DECODE_MEMORY_FAIL;
}
if (!ensurePicture(picture, hdr))
return DECODE_FAIL;
if (!ensureSlice(picture, data, size))
return DECODE_FAIL;
ret = picture->decode();
if (ret != DECODE_SUCCESS)
return ret;
updateReference(picture, hdr);
if (hdr->show_frame)
return outputPicture(picture);
return DECODE_SUCCESS;
}
static bool parse_super_frame(std::vector<uint32_t>& frameSize, const uint8_t* data, const size_t size)
{
if (!data || !size)
return false;
uint8_t marker;
marker = *(data + size - 1);
if ((marker & 0xe0) != 0xc0) {
frameSize.push_back(size);
return true;
}
const uint32_t frames = (marker & 0x7) + 1;
const uint32_t mag = ((marker >> 3) & 0x3) + 1;
const size_t indexSz = 2 + mag * frames;
if (size < indexSz)
return false;
data += size - indexSz;
const uint8_t marker2 = *data++;
if (marker != marker2)
return false;
for (uint32_t i = 0; i < frames; i++) {
uint32_t sz = 0;
for (uint32_t j = 0; j < mag; j++) {
sz |= (*data++) << (j * 8);
}
frameSize.push_back(sz);
}
return true;
}
Decode_Status VaapiDecoderVP9::decode(VideoDecodeBuffer * buffer)
{
Decode_Status status;
if (!buffer)
return DECODE_INVALID_DATA;
uint8_t* data = buffer->data;
size_t size = buffer->size;
uint8_t* end = data + size;
std::vector<uint32_t> frameSize;
if (!parse_super_frame(frameSize, data, size))
return DECODE_INVALID_DATA;
for (size_t i = 0; i < frameSize.size(); i++) {
uint32_t sz = frameSize[i];
if (data + sz > end)
return DECODE_INVALID_DATA;
status = decode(data, sz, buffer->timeStamp);
if (status != DECODE_SUCCESS)
return status;
data += sz;
}
return DECODE_SUCCESS;
}
Decode_Status VaapiDecoderVP9::decode(const uint8_t* data, uint32_t size, uint64_t timeStamp)
{
Vp9FrameHdr hdr;
if (!m_parser)
return DECODE_MEMORY_FAIL;
if (vp9_parse_frame_header(m_parser.get(), &hdr, data, size) != VP9_PARSER_OK)
return DECODE_INVALID_DATA;
if (hdr.first_partition_size + hdr.frame_header_length_in_bytes > size)
return DECODE_INVALID_DATA;
return decode(&hdr, data, size, timeStamp);
}
const bool VaapiDecoderVP9::s_registered =
VaapiDecoderFactory::register_<VaapiDecoderVP9>(YAMI_MIME_VP9);
}
|
fix compiler issue
|
vp9dec: fix compiler issue
Function resize() has been removed. Use setCrop() instead.
Change-Id: I85f05e104a62b052d2d00617e6226f208484abbe
Signed-off-by: Zhong Li <[email protected]>
|
C++
|
apache-2.0
|
clearlylin/libyami,clearlylin/libyami,lizhong1008/libyami,YuJiankang/libyami,chivakker/libyami,01org/libyami,yizhouwei/libyami,lizhong1008/libyami,zhaobob/libyami,clearlylin/libyami,lizhong1008/libyami,seanvk/libyami,seanvk/libyami,stripes416/libyami,dspmeng/libyami,zhaobob/libyami,YuJiankang/libyami,yizhouwei/libyami,uartie/libyami,yizhouwei/libyami,chivakker/libyami,chivakker/libyami,seanvk/libyami,dspmeng/libyami,zhaobob/libyami,uartie/libyami,YuJiankang/libyami,stripes416/libyami,uartie/libyami,01org/libyami,dspmeng/libyami,stripes416/libyami,01org/libyami
|
0034add9e55933d716519a1998319f89fefdc499
|
urmem.hpp
|
urmem.hpp
|
#ifndef URMEM_H_
#define URMEM_H_
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
#include <vector>
#include <iterator>
#include <algorithm>
#include <memory>
#include <mutex>
class urmem {
public:
using address_t = unsigned long;
using byte_t = unsigned char;
using bytearray_t = std::vector<byte_t>;
enum class calling_convention {
cdeclcall,
stdcall,
thiscall
};
template<calling_convention CConv, typename Ret = void, typename ... Args>
static Ret call_function(address_t address, Args ... args) {
#ifdef _WIN32
return invoker<CConv>::call<Ret, Args...>(address, args...);
#else
return (reinterpret_cast<Ret(*)(Args...)>(address))(args...);
#endif
}
template<typename T>
static address_t get_func_addr(T func) {
union {
T func;
address_t addr;
} u{func};
return u.addr;
};
template<typename T>
class bit_manager {
public:
bit_manager(void) = delete;
bit_manager(T &src) :_data(src) {}
class bit {
public:
bit(void) = delete;
bit(T &src, size_t index) : _data(src), _mask(1 << index), _index(index) {}
bit &operator=(bool value) {
if (value) {
_data |= _mask;
} else {
_data &= ~_mask;
}
return *this;
}
operator bool() const {
return (_data & _mask) != 0;
}
private:
T &_data;
const T _mask;
const size_t _index;
};
bit operator [](size_t index) const {
return bit(_data, index);
};
private:
T &_data;
};
class pointer {
public:
pointer(void) = delete;
template<typename T>
pointer(T *address) : pointer{reinterpret_cast<address_t>(address)} {}
pointer(address_t address) : _pointer(address) {}
template<typename T>
T &field(size_t offset) {
return *reinterpret_cast<T *>(_pointer + offset);
}
pointer ptr_field(size_t offset) {
return pointer(field<address_t>(offset));
}
template<typename T>
operator T *() const {
return reinterpret_cast<T *>(_pointer);
}
private:
const address_t _pointer;
};
class unprotect_scope {
public:
unprotect_scope(void) = delete;
unprotect_scope(address_t addr, size_t length) :_addr(addr), _lenght(length) {
#ifdef _WIN32
VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, PAGE_EXECUTE_READWRITE, &_original_protect);
#else
auto pagesize = sysconf(_SC_PAGE_SIZE);
_addr = _addr & ~(pagesize - 1);
mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif
}
~unprotect_scope(void) {
#ifdef _WIN32
VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, _original_protect, nullptr);
#else
mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_EXEC);
#endif
}
private:
#ifdef _WIN32
unsigned long _original_protect;
#endif
address_t _addr;
const size_t _lenght;
};
class sig_scanner {
public:
bool init(void *addr_in_module) {
return init(reinterpret_cast<address_t>(addr_in_module));
}
bool init(address_t addr_in_module) {
#ifdef _WIN32
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(reinterpret_cast<void *>(addr_in_module), &info, sizeof(info))) {
return false;
}
auto dos = reinterpret_cast<IMAGE_DOS_HEADER *>(info.AllocationBase);
auto pe = reinterpret_cast<IMAGE_NT_HEADERS *>(reinterpret_cast<address_t>(dos) + dos->e_lfanew);
if (pe->Signature != IMAGE_NT_SIGNATURE) {
return false;
}
_base = reinterpret_cast<address_t>(info.AllocationBase);
_size = pe->OptionalHeader.SizeOfImage;
#else
Dl_info info{};
struct stat buf {};
if (!dladdr(reinterpret_cast<void *>(addr_in_module), &info)) {
return false;
}
if (stat(info.dli_fname, &buf) != 0) {
return false;
}
_base = reinterpret_cast<address_t>(info.dli_fbase);
_size = buf.st_size;
#endif
return true;
}
bool find(const char *pattern, const char *mask, address_t &addr) const {
auto current_byte = reinterpret_cast<byte_t *>(_base);
auto last_byte = current_byte + _size;
size_t i{};
while (current_byte < last_byte) {
for (i = 0; mask[i]; ++i) {
if (¤t_byte[i] >= last_byte ||
((mask[i] != '?') && (static_cast<byte_t>(pattern[i]) != current_byte[i]))) {
break;
}
}
if (!mask[i]) {
addr = reinterpret_cast<address_t>(current_byte);
return true;
}
++current_byte;
}
return false;
}
private:
address_t _base{};
size_t _size{};
};
class patch {
public:
patch(void) = delete;
patch(void *addr, const bytearray_t &new_data)
: patch{reinterpret_cast<address_t>(addr), new_data} {}
patch(address_t addr, const bytearray_t &new_data)
: _patch_addr(addr), _new_data(new_data), _enabled(false) {
enable();
}
~patch(void) {
disable();
}
void enable(void) {
if (_enabled) {
return;
}
unprotect_scope scope(_patch_addr, _new_data.size());
_original_data.clear();
std::copy_n(
reinterpret_cast<bytearray_t::value_type*>(_patch_addr),
_new_data.size(),
std::back_inserter<bytearray_t>(_original_data)
);
std::copy_n(
_new_data.data(),
_new_data.size(),
reinterpret_cast<bytearray_t::value_type*>(_patch_addr)
);
_enabled = true;
}
void disable(void) {
if (!_enabled) {
return;
}
unprotect_scope scope(_patch_addr, _new_data.size());
std::copy_n(
_original_data.data(),
_original_data.size(),
reinterpret_cast<bytearray_t::value_type*>(_patch_addr)
);
_enabled = false;
}
bool is_enabled(void) const {
return _enabled;
}
private:
address_t _patch_addr;
bytearray_t _original_data;
bytearray_t _new_data;
bool _enabled;
};
class hook {
public:
enum class type {
jmp,
call
};
class raii {
public:
raii(void) = delete;
raii(hook &h) : _hook(h) {
_hook.disable();
}
~raii(void) {
_hook.enable();
}
private:
hook &_hook;
};
hook(void) = delete;
hook(void *inject_addr, void *handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) :
hook{reinterpret_cast<address_t>(inject_addr), reinterpret_cast<address_t>(handle_addr), h_type, length} {};
hook(address_t inject_addr, address_t handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) {
bytearray_t new_bytes(length, 0x90);
switch (h_type) {
case type::jmp:
{
new_bytes[0] = 0xE9;
_original_addr = inject_addr;
break;
}
case type::call:
{
new_bytes[0] = 0xE8;
_original_addr = pointer(inject_addr).field<address_t>(1) + (inject_addr + 5);
break;
}
}
*reinterpret_cast<address_t *>(new_bytes.data() + 1) = handle_addr - (inject_addr + 5);
_patch = std::make_shared<patch>(inject_addr, new_bytes);
}
void enable(void) {
_patch->enable();
}
void disable(void) {
_patch->disable();
}
bool is_enabled(void) const {
return _patch->is_enabled();
}
address_t get_original_addr(void) const {
return _original_addr;
}
private:
address_t _original_addr{};
std::shared_ptr<patch> _patch;
};
template<size_t, calling_convention, typename Sig>
class smart_hook;
template<size_t Id, calling_convention CConv, typename Ret, typename ... Args>
class smart_hook<Id, CConv, Ret(Args...)> {
public:
using func = std::function<Ret(Args...)>;
smart_hook(void *inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) :
smart_hook{reinterpret_cast<address_t>(inject_addr), h_type, length} {};
smart_hook(address_t inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) {
get_data() = this;
_hook = std::make_shared<hook>(inject_addr, reinterpret_cast<address_t>(_interlayer.func), h_type, length);
}
void attach(const func &f) {
_cb = f;
}
void detach(void) {
_cb = nullptr;
}
Ret call(Args ... args) {
return call_function<CConv, Ret>(_hook->get_original_addr(), args...);
}
private:
static smart_hook<Id, CConv, Ret(Args...)> *&get_data(void) {
static smart_hook<Id, CConv, Ret(Args...)> *d{};
return d;
}
#ifdef _WIN32
template<calling_convention>
struct interlayer;
template<>
struct interlayer<calling_convention::cdeclcall> {
static Ret __cdecl func(Args ... args) {
return get_data()->call_cb(args...);
}
};
template<>
struct interlayer<calling_convention::stdcall> {
static Ret __stdcall func(Args ... args) {
return get_data()->call_cb(args...);
}
};
template<>
struct interlayer<calling_convention::thiscall> {
static Ret __thiscall func(Args ... args) {
return get_data()->call_cb(args...);
}
};
#else
struct interlayer {
static Ret func(Args ... args) {
return get_data()->call_cb(args...);
}
};
#endif
inline Ret call_cb(Args ... args) {
std::lock_guard<std::mutex> guard(_mutex);
hook::raii scope(*_hook);
return _cb ? _cb(args...) : call(args...);
}
std::shared_ptr<hook> _hook;
std::mutex _mutex;
#ifdef _WIN32
interlayer<CConv> _interlayer;
#else
interlayer _interlayer;
#endif
func _cb;
};
private:
#ifdef _WIN32
template<calling_convention>
struct invoker;
template<>
struct invoker<calling_convention::cdeclcall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__cdecl *)(Args...)>(address))(args...);
}
};
template<>
struct invoker<calling_convention::stdcall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__stdcall *)(Args...)>(address))(args...);
}
};
template<>
struct invoker<calling_convention::thiscall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__thiscall *)(Args...)>(address))(args...);
}
};
#endif
};
#endif // URMEM_H_
|
#ifndef URMEM_H_
#define URMEM_H_
#ifdef _WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
#include <vector>
#include <iterator>
#include <algorithm>
#include <memory>
#include <mutex>
class urmem {
public:
using address_t = unsigned long;
using byte_t = unsigned char;
using bytearray_t = std::vector<byte_t>;
enum class calling_convention {
cdeclcall,
stdcall,
thiscall
};
template<calling_convention CConv, typename Ret = void, typename ... Args>
static Ret call_function(address_t address, Args ... args) {
#ifdef _WIN32
return invoker<CConv>::call<Ret, Args...>(address, args...);
#else
return (reinterpret_cast<Ret(*)(Args...)>(address))(args...);
#endif
}
template<typename T>
static address_t get_func_addr(T func) {
union {
T func;
address_t addr;
} u{func};
return u.addr;
};
static void unprotect_memory(address_t addr, size_t length) {
#ifdef _WIN32
unsigned long original_protect;
VirtualProtect(reinterpret_cast<void *>(addr), length, PAGE_EXECUTE_READWRITE, &original_protect);
#else
auto pagesize = sysconf(_SC_PAGE_SIZE);
addr = addr & ~(pagesize - 1);
mprotect(reinterpret_cast<void *>(addr), length, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif
}
template<typename T>
class bit_manager {
public:
bit_manager(void) = delete;
bit_manager(T &src) :_data(src) {}
class bit {
public:
bit(void) = delete;
bit(T &src, size_t index) : _data(src), _mask(1 << index), _index(index) {}
bit &operator=(bool value) {
if (value) {
_data |= _mask;
} else {
_data &= ~_mask;
}
return *this;
}
operator bool() const {
return (_data & _mask) != 0;
}
private:
T &_data;
const T _mask;
const size_t _index;
};
bit operator [](size_t index) const {
return bit(_data, index);
};
private:
T &_data;
};
class pointer {
public:
pointer(void) = delete;
template<typename T>
pointer(T *address) : pointer{reinterpret_cast<address_t>(address)} {}
pointer(address_t address) : _pointer(address) {}
template<typename T>
T &field(size_t offset) {
return *reinterpret_cast<T *>(_pointer + offset);
}
pointer ptr_field(size_t offset) {
return pointer(field<address_t>(offset));
}
template<typename T>
operator T *() const {
return reinterpret_cast<T *>(_pointer);
}
private:
const address_t _pointer;
};
class unprotect_scope {
public:
unprotect_scope(void) = delete;
unprotect_scope(address_t addr, size_t length) :_addr(addr), _lenght(length) {
#ifdef _WIN32
VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, PAGE_EXECUTE_READWRITE, &_original_protect);
#else
auto pagesize = sysconf(_SC_PAGE_SIZE);
_addr = _addr & ~(pagesize - 1);
mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif
}
~unprotect_scope(void) {
#ifdef _WIN32
VirtualProtect(reinterpret_cast<void *>(_addr), _lenght, _original_protect, nullptr);
#else
mprotect(reinterpret_cast<void *>(_addr), _lenght, PROT_READ | PROT_EXEC);
#endif
}
private:
#ifdef _WIN32
unsigned long _original_protect;
#endif
address_t _addr;
const size_t _lenght;
};
class sig_scanner {
public:
bool init(void *addr_in_module) {
return init(reinterpret_cast<address_t>(addr_in_module));
}
bool init(address_t addr_in_module) {
#ifdef _WIN32
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(reinterpret_cast<void *>(addr_in_module), &info, sizeof(info))) {
return false;
}
auto dos = reinterpret_cast<IMAGE_DOS_HEADER *>(info.AllocationBase);
auto pe = reinterpret_cast<IMAGE_NT_HEADERS *>(reinterpret_cast<address_t>(dos) + dos->e_lfanew);
if (pe->Signature != IMAGE_NT_SIGNATURE) {
return false;
}
_base = reinterpret_cast<address_t>(info.AllocationBase);
_size = pe->OptionalHeader.SizeOfImage;
#else
Dl_info info{};
struct stat buf {};
if (!dladdr(reinterpret_cast<void *>(addr_in_module), &info)) {
return false;
}
if (stat(info.dli_fname, &buf) != 0) {
return false;
}
_base = reinterpret_cast<address_t>(info.dli_fbase);
_size = buf.st_size;
#endif
return true;
}
bool find(const char *pattern, const char *mask, address_t &addr) const {
auto current_byte = reinterpret_cast<byte_t *>(_base);
auto last_byte = current_byte + _size;
size_t i{};
while (current_byte < last_byte) {
for (i = 0; mask[i]; ++i) {
if (¤t_byte[i] >= last_byte ||
((mask[i] != '?') && (static_cast<byte_t>(pattern[i]) != current_byte[i]))) {
break;
}
}
if (!mask[i]) {
addr = reinterpret_cast<address_t>(current_byte);
return true;
}
++current_byte;
}
return false;
}
private:
address_t _base{};
size_t _size{};
};
class patch {
public:
patch(void) = delete;
patch(void *addr, const bytearray_t &new_data)
: patch{reinterpret_cast<address_t>(addr), new_data} {}
patch(address_t addr, const bytearray_t &new_data)
: _patch_addr(addr), _new_data(new_data), _enabled(false) {
unprotect_memory(_patch_addr, _new_data.size());
enable();
}
~patch(void) {
disable();
}
void enable(void) {
if (_enabled) {
return;
}
_original_data.clear();
std::copy_n(
reinterpret_cast<bytearray_t::value_type*>(_patch_addr),
_new_data.size(),
std::back_inserter<bytearray_t>(_original_data)
);
std::copy_n(
_new_data.data(),
_new_data.size(),
reinterpret_cast<bytearray_t::value_type*>(_patch_addr)
);
_enabled = true;
}
void disable(void) {
if (!_enabled) {
return;
}
std::copy_n(
_original_data.data(),
_original_data.size(),
reinterpret_cast<bytearray_t::value_type*>(_patch_addr)
);
_enabled = false;
}
bool is_enabled(void) const {
return _enabled;
}
private:
address_t _patch_addr;
bytearray_t _original_data;
bytearray_t _new_data;
bool _enabled;
};
class hook {
public:
enum class type {
jmp,
call
};
class raii {
public:
raii(void) = delete;
raii(hook &h) : _hook(h) {
_hook.disable();
}
~raii(void) {
_hook.enable();
}
private:
hook &_hook;
};
hook(void) = delete;
hook(void *inject_addr, void *handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) :
hook{reinterpret_cast<address_t>(inject_addr), reinterpret_cast<address_t>(handle_addr), h_type, length} {};
hook(address_t inject_addr, address_t handle_addr, hook::type h_type = hook::type::jmp, size_t length = 5) {
bytearray_t new_bytes(length, 0x90);
switch (h_type) {
case type::jmp:
{
new_bytes[0] = 0xE9;
_original_addr = inject_addr;
break;
}
case type::call:
{
new_bytes[0] = 0xE8;
_original_addr = pointer(inject_addr).field<address_t>(1) + (inject_addr + 5);
break;
}
}
*reinterpret_cast<address_t *>(new_bytes.data() + 1) = handle_addr - (inject_addr + 5);
_patch = std::make_shared<patch>(inject_addr, new_bytes);
}
void enable(void) {
_patch->enable();
}
void disable(void) {
_patch->disable();
}
bool is_enabled(void) const {
return _patch->is_enabled();
}
address_t get_original_addr(void) const {
return _original_addr;
}
private:
address_t _original_addr{};
std::shared_ptr<patch> _patch;
};
template<size_t, calling_convention, typename Sig>
class smart_hook;
template<size_t Id, calling_convention CConv, typename Ret, typename ... Args>
class smart_hook<Id, CConv, Ret(Args...)> {
public:
using func = std::function<Ret(Args...)>;
smart_hook(void *inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) :
smart_hook{reinterpret_cast<address_t>(inject_addr), h_type, length} {};
smart_hook(address_t inject_addr, hook::type h_type = hook::type::jmp, size_t length = 5) {
get_data() = this;
_hook = std::make_shared<hook>(inject_addr, reinterpret_cast<address_t>(_interlayer.func), h_type, length);
}
void attach(const func &f) {
_cb = f;
}
void detach(void) {
_cb = nullptr;
}
Ret call(Args ... args) {
return call_function<CConv, Ret>(_hook->get_original_addr(), args...);
}
private:
static smart_hook<Id, CConv, Ret(Args...)> *&get_data(void) {
static smart_hook<Id, CConv, Ret(Args...)> *d{};
return d;
}
#ifdef _WIN32
template<calling_convention>
struct interlayer;
template<>
struct interlayer<calling_convention::cdeclcall> {
static Ret __cdecl func(Args ... args) {
return get_data()->call_cb(args...);
}
};
template<>
struct interlayer<calling_convention::stdcall> {
static Ret __stdcall func(Args ... args) {
return get_data()->call_cb(args...);
}
};
template<>
struct interlayer<calling_convention::thiscall> {
static Ret __thiscall func(Args ... args) {
return get_data()->call_cb(args...);
}
};
#else
struct interlayer {
static Ret func(Args ... args) {
return get_data()->call_cb(args...);
}
};
#endif
inline Ret call_cb(Args ... args) {
std::lock_guard<std::mutex> guard(_mutex);
hook::raii scope(*_hook);
return _cb ? _cb(args...) : call(args...);
}
std::shared_ptr<hook> _hook;
std::mutex _mutex;
#ifdef _WIN32
interlayer<CConv> _interlayer;
#else
interlayer _interlayer;
#endif
func _cb;
};
private:
#ifdef _WIN32
template<calling_convention>
struct invoker;
template<>
struct invoker<calling_convention::cdeclcall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__cdecl *)(Args...)>(address))(args...);
}
};
template<>
struct invoker<calling_convention::stdcall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__stdcall *)(Args...)>(address))(args...);
}
};
template<>
struct invoker<calling_convention::thiscall> {
template<typename Ret, typename ... Args>
static inline Ret call(address_t address, Args... args) {
return (reinterpret_cast<Ret(__thiscall *)(Args...)>(address))(args...);
}
};
#endif
};
#endif // URMEM_H_
|
Add unprotect_memory method
|
Add unprotect_memory method
|
C++
|
mit
|
urShadow/urmem
|
e9c81095481a9d234a51fed7d7a6fae1c2f99b03
|
akregator/src/tagfolderitem.cpp
|
akregator/src/tagfolderitem.cpp
|
/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <frank.osterfeld at kdemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "actionmanager.h"
#include "tagfolder.h"
#include "tagfolderitem.h"
#include "treenode.h"
#include <qpopupmenu.h>
#include <kaction.h>
#include <kiconloader.h>
namespace Akregator {
TagFolderItem::TagFolderItem(FolderItem* parent, TagFolder* node) : FolderItem(parent, node)
{
}
TagFolderItem::TagFolderItem(FolderItem* parent, TreeNodeItem* after, TagFolder* node) : FolderItem(parent, after, node)
{
}
TagFolderItem::TagFolderItem(KListView* parent, TagFolder* node) : FolderItem(parent, node)
{
}
TagFolderItem::TagFolderItem(KListView* parent, TreeNodeItem* after, TagFolder* node) : FolderItem(parent, after, node)
{
setPixmap ( 0, KGlobal::iconLoader()->loadIcon("bookmark_folder", KIcon::Small) );
}
TagFolder* TagFolderItem::node()
{
return static_cast<TagFolder*> (m_node);
}
TagFolderItem::~TagFolderItem()
{}
void TagFolderItem::showContextMenu(const QPoint& p)
{
QWidget* w = ActionManager::getInstance()->container("tagfolder_popup");
if (w)
static_cast<QPopupMenu *>(w)->exec(p);
}
}
|
/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <frank.osterfeld at kdemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "actionmanager.h"
#include "tagfolder.h"
#include "tagfolderitem.h"
#include "treenode.h"
#include <qpopupmenu.h>
#include <kaction.h>
#include <kiconloader.h>
namespace Akregator {
TagFolderItem::TagFolderItem(FolderItem* parent, TagFolder* node) : FolderItem(parent, node)
{
}
TagFolderItem::TagFolderItem(FolderItem* parent, TreeNodeItem* after, TagFolder* node) : FolderItem(parent, after, node)
{
}
TagFolderItem::TagFolderItem(KListView* parent, TagFolder* node) : FolderItem(parent, node)
{
}
TagFolderItem::TagFolderItem(KListView* parent, TreeNodeItem* after, TagFolder* node) : FolderItem(parent, after, node)
{
}
TagFolder* TagFolderItem::node()
{
return static_cast<TagFolder*> (m_node);
}
TagFolderItem::~TagFolderItem()
{}
void TagFolderItem::showContextMenu(const QPoint& p)
{
QWidget* w = ActionManager::getInstance()->container("tagfolder_popup");
if (w)
static_cast<QPopupMenu *>(w)->exec(p);
}
}
|
use normal folder icon for tag folders
|
use normal folder icon for tag folders
svn path=/trunk/KDE/kdepim/akregator/; revision=428827
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
496989d358bb06e34ba55e271ed92b6742dff37c
|
examples/ccsd.cxx
|
examples/ccsd.cxx
|
/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/
/** \addtogroup examples
* @{
* \defgroup CCSD
* @{
* \brief A Coupled Cluster Singles and Doubles contraction code extracted from Aquarius
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <math.h>
#include <assert.h>
#include <algorithm>
#include <ctf.hpp>
#include "../src/shared/util.h"
void divide(double const alpha, double const a, double const b, double & c){
if (fabs(b) > 0.0);
c+=alpha*(a/b);
}
class Integrals {
public:
CTF_World * dw;
CTF_Tensor aa;
CTF_Tensor ii;
CTF_Tensor ab;
CTF_Tensor ai;
CTF_Tensor ia;
CTF_Tensor ij;
CTF_Tensor abcd;
CTF_Tensor abci;
CTF_Tensor aibc;
CTF_Tensor aibj;
CTF_Tensor abij;
CTF_Tensor ijab;
CTF_Tensor aijk;
CTF_Tensor ijak;
CTF_Tensor ijkl;
Integrals(int no, int nv, CTF_World &dw_){
int shapeASAS[] = {AS,NS,AS,NS};
int shapeASNS[] = {AS,NS,NS,NS};
int shapeNSNS[] = {NS,NS,NS,NS};
int shapeNSAS[] = {NS,NS,AS,NS};
int vvvv[] = {nv,nv,nv,nv};
int vvvo[] = {nv,nv,nv,no};
int vovv[] = {nv,no,nv,nv};
int vovo[] = {nv,no,nv,no};
int vvoo[] = {nv,nv,no,no};
int oovv[] = {no,no,nv,nv};
int vooo[] = {nv,no,no,no};
int oovo[] = {no,no,nv,no};
int oooo[] = {no,no,no,no};
dw = &dw_;
aa = CTF_Vector(nv,dw_);
ii = CTF_Vector(no,dw_);
ab = CTF_Matrix(nv,nv,AS,dw_,"Vab",1);
ai = CTF_Matrix(nv,no,NS,dw_,"Vai",1);
ia = CTF_Matrix(no,nv,NS,dw_,"Via",1);
ij = CTF_Matrix(no,no,AS,dw_,"Vij",1);
abcd = CTF_Tensor(4,vvvv,shapeASAS,dw_,"Vabcd",1);
abci = CTF_Tensor(4,vvvo,shapeASNS,dw_,"Vabci",1);
aibc = CTF_Tensor(4,vovv,shapeNSAS,dw_,"Vaibc",1);
aibj = CTF_Tensor(4,vovo,shapeNSNS,dw_,"Vaibj",1);
abij = CTF_Tensor(4,vvoo,shapeASAS,dw_,"Vabij",1);
ijab = CTF_Tensor(4,oovv,shapeASAS,dw_,"Vijab",1);
aijk = CTF_Tensor(4,vooo,shapeNSAS,dw_,"Vaijk",1);
ijak = CTF_Tensor(4,oovo,shapeASNS,dw_,"Vijak",1);
ijkl = CTF_Tensor(4,oooo,shapeASAS,dw_,"Vijkl",1);
}
void fill_rand(){
int i, rank;
long_int j, sz, * indices;
double * values;
CTF_Tensor * tarr[] = {&aa, &ii, &ab, &ai, &ia, &ij,
&abcd, &abci, &aibc, &aibj,
&abij, &ijab, &aijk, &ijak, &ijkl};
MPI_Comm comm = dw->comm;
MPI_Comm_rank(comm, &rank);
srand48(rank*13);
for (i=0; i<15; i++){
tarr[i]->read_local(&sz, &indices, &values);
// for (j=0; j<sz; j++) values[j] = drand48()-.5;
for (j=0; j<sz; j++) values[j] = ((indices[j]*16+i)%13077)/13077. -.5;
tarr[i]->write(sz, indices, values);
free(indices), free(values);
}
}
tCTF_Idx_Tensor<double> operator[](char const * idx_map_){
int i, lenm, no, nv;
lenm = strlen(idx_map_);
char new_idx_map[lenm+1];
new_idx_map[lenm]='\0';
no = 0;
nv = 0;
for (i=0; i<lenm; i++){
if (idx_map_[i] >= 'a' && idx_map_[i] <= 'h'){
new_idx_map[i] = 'a'+nv;
nv++;
} else if (idx_map_[i] >= 'i' && idx_map_[i] <= 'n'){
new_idx_map[i] = 'i'+no;
no++;
}
}
// printf("indices %s are %s\n",idx_map_,new_idx_map);
if (0 == strcmp("a",new_idx_map)) return aa[idx_map_];
if (0 == strcmp("i",new_idx_map)) return ii[idx_map_];
if (0 == strcmp("ab",new_idx_map)) return ab[idx_map_];
if (0 == strcmp("ai",new_idx_map)) return ai[idx_map_];
if (0 == strcmp("ia",new_idx_map)) return ia[idx_map_];
if (0 == strcmp("ij",new_idx_map)) return ij[idx_map_];
if (0 == strcmp("abcd",new_idx_map)) return abcd[idx_map_];
if (0 == strcmp("abci",new_idx_map)) return abci[idx_map_];
if (0 == strcmp("aibc",new_idx_map)) return aibc[idx_map_];
if (0 == strcmp("aibj",new_idx_map)) return aibj[idx_map_];
if (0 == strcmp("abij",new_idx_map)) return abij[idx_map_];
if (0 == strcmp("ijab",new_idx_map)) return ijab[idx_map_];
if (0 == strcmp("aijk",new_idx_map)) return aijk[idx_map_];
if (0 == strcmp("ijak",new_idx_map)) return ijak[idx_map_];
if (0 == strcmp("ijkl",new_idx_map)) return ijkl[idx_map_];
printf("Invalid integral indices\n");
ABORT;
//shut up compiler
return aa[idx_map_];
}
};
class Amplitudes {
public:
CTF_Tensor ai;
CTF_Tensor abij;
CTF_World * dw;
Amplitudes(int no, int nv, CTF_World &dw_){
dw = &dw_;
int shapeASAS[] = {AS,NS,AS,NS};
int vvoo[] = {nv,nv,no,no};
ai = CTF_Matrix(nv,no,NS,dw_,"Tai",1);
abij = CTF_Tensor(4,vvoo,shapeASAS,dw_,"Tabij",1);
}
tCTF_Idx_Tensor<double> operator[](char const * idx_map_){
if (strlen(idx_map_) == 4) return abij[idx_map_];
else return ai[idx_map_];
}
void fill_rand(){
int i, rank;
long_int j, sz, * indices;
double * values;
CTF_Tensor * tarr[] = {&ai, &abij};
MPI_Comm comm = dw->comm;
MPI_Comm_rank(comm, &rank);
srand48(rank*25);
for (i=0; i<2; i++){
tarr[i]->read_local(&sz, &indices, &values);
// for (j=0; j<sz; j++) values[j] = drand48()-.5;
for (j=0; j<sz; j++) values[j] = ((indices[j]*13+i)%13077)/13077. -.5;
tarr[i]->write(sz, indices, values);
free(indices), free(values);
}
}
};
void ccsd(Integrals &V,
Amplitudes &T){
CTF_Tensor T21 = CTF_Tensor(T.abij);
T21["abij"] += .5*T["ai"]*T["bj"];
CTF_Tensor tFme(*V["me"].parent);
CTF_Idx_Tensor Fme(&tFme,"me");
Fme += V["me"];
Fme += V["mnef"]*T["fn"];
CTF_Tensor tFae(*V["ae"].parent);
CTF_Idx_Tensor Fae(&tFae,"ae");
Fae += V["ae"];
Fae -= Fme*T["am"];
Fae -=.5*V["mnef"]*T["afmn"];
Fae += V["anef"]*T["fn"];
CTF_Tensor tFmi(*V["mi"].parent);
CTF_Idx_Tensor Fmi(&tFmi,"mi");
Fmi += V["mi"];
Fmi += Fme*T["ei"];
Fmi += .5*V["mnef"]*T["efin"];
Fmi += V["mnfi"]*T["fn"];
CTF_Tensor tWmnei(*V["mnei"].parent);
CTF_Idx_Tensor Wmnei(&tWmnei,"mnei");
Wmnei += V["mnei"];
Wmnei += V["mnei"];
Wmnei += V["mnef"]*T["fi"];
CTF_Tensor tWmnij(*V["mnij"].parent);
CTF_Idx_Tensor Wmnij(&tWmnij,"mnij");
Wmnij += V["mnij"];
Wmnij -= V["mnei"]*T["ej"];
Wmnij += V["mnef"]*T21["efij"];
CTF_Tensor tWamei(*V["amei"].parent);
CTF_Idx_Tensor Wamei(&tWamei,"amei");
Wamei += V["amei"];
Wamei -= Wmnei*T["an"];
Wamei += V["amef"]*T["fi"];
Wamei += .5*V["mnef"]*T["afin"];
CTF_Tensor tWamij(*V["amij"].parent);
CTF_Idx_Tensor Wamij(&tWamij,"amij");
Wamij += V["amij"];
Wamij += V["amei"]*T["ej"];
Wamij += V["amef"]*T["efij"];
CTF_Tensor tZai(*V["ai"].parent);
CTF_Idx_Tensor Zai(&tZai,"ai");
Zai += V["ai"];
Zai -= Fmi*T["am"];
Zai += V["ae"]*T["ei"];
Zai += V["amei"]*T["em"];
Zai += V["aeim"]*Fme;
Zai += .5*V["amef"]*T21["efim"];
Zai -= .5*Wmnei*T21["eamn"];
CTF_Tensor tZabij(*V["abij"].parent);
CTF_Idx_Tensor Zabij(&tZabij,"abij");
Zabij += V["abij"];
Zabij += V["abei"]*T["ej"];
Zabij += Wamei*T["ebmj"];
Zabij -= Wamij*T["bm"];
Zabij += Fae*T["ebij"];
Zabij -= Fmi*T["abmj"];
Zabij += .5*V["abef"]*T21["efij"];
Zabij += .5*Wmnij*T21["abmn"];
CTF_fctr fctr;
fctr.func_ptr = ÷
CTF_Tensor Dai(2, V.ai.len, V.ai.sym, *V.dw);
int sh_sym[4] = {SH, NS, SH, NS};
CTF_Tensor Dabij(4, V.abij.len, sh_sym, *V.dw);
Dai["ai"] += V["i"];
Dai["ai"] -= V["a"];
Dabij["abij"] += V["i"];
Dabij["abij"] += V["j"];
Dabij["abij"] -= V["a"];
Dabij["abij"] -= V["b"];
T.ai.contract(1.0, *(Zai.parent), "ai", Dai, "ai", 0.0, "ai", fctr);
T.abij.contract(1.0, *(Zabij.parent), "abij", Dabij, "abij", 0.0, "abij", fctr);
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, niter, no, nv, i;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-no")){
no = atoi(getCmdOption(input_str, input_str+in_num, "-no"));
if (no < 0) no= 4;
} else no = 4;
if (getCmdOption(input_str, input_str+in_num, "-nv")){
nv = atoi(getCmdOption(input_str, input_str+in_num, "-nv"));
if (nv < 0) nv = 6;
} else nv = 6;
if (getCmdOption(input_str, input_str+in_num, "-niter")){
niter = atoi(getCmdOption(input_str, input_str+in_num, "-niter"));
if (niter < 0) niter = 1;
} else niter = 1;
{
CTF_World dw(argc, argv);
{
Integrals V(no, nv, dw);
V.fill_rand();
Amplitudes T(no, nv, dw);
for (i=0; i<niter; i++){
T.fill_rand();
double d = MPI_Wtime();
ccsd(V,T);
if (rank == 0)
printf("Completed %dth CCSD iteration in time = %lf, |T| is %lf\n",
i, MPI_Wtime()-d, T.ai.norm2()+T.abij.norm2());
else {
T.ai.norm2();
T.abij.norm2();
}
T["ai"] = (1./T.ai.norm2())*T["ai"];
T["abij"] = (1./T.abij.norm2())*T["abij"];
}
}
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
|
/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/
/** \addtogroup examples
* @{
* \defgroup CCSD
* @{
* \brief A Coupled Cluster Singles and Doubles contraction code extracted from Aquarius
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <math.h>
#include <assert.h>
#include <algorithm>
#include <ctf.hpp>
#include "../src/shared/util.h"
void divide(double const alpha, double const a, double const b, double & c){
if (fabs(b) > 0.0);
c+=alpha*(a/b);
}
class Integrals {
public:
CTF_World * dw;
CTF_Tensor aa;
CTF_Tensor ii;
CTF_Tensor ab;
CTF_Tensor ai;
CTF_Tensor ia;
CTF_Tensor ij;
CTF_Tensor abcd;
CTF_Tensor abci;
CTF_Tensor aibc;
CTF_Tensor aibj;
CTF_Tensor abij;
CTF_Tensor ijab;
CTF_Tensor aijk;
CTF_Tensor ijak;
CTF_Tensor ijkl;
Integrals(int no, int nv, CTF_World &dw_){
int shapeASAS[] = {AS,NS,AS,NS};
int shapeASNS[] = {AS,NS,NS,NS};
int shapeNSNS[] = {NS,NS,NS,NS};
int shapeNSAS[] = {NS,NS,AS,NS};
int vvvv[] = {nv,nv,nv,nv};
int vvvo[] = {nv,nv,nv,no};
int vovv[] = {nv,no,nv,nv};
int vovo[] = {nv,no,nv,no};
int vvoo[] = {nv,nv,no,no};
int oovv[] = {no,no,nv,nv};
int vooo[] = {nv,no,no,no};
int oovo[] = {no,no,nv,no};
int oooo[] = {no,no,no,no};
dw = &dw_;
aa = CTF_Vector(nv,dw_);
ii = CTF_Vector(no,dw_);
ab = CTF_Matrix(nv,nv,AS,dw_,"Vab",1);
ai = CTF_Matrix(nv,no,NS,dw_,"Vai",1);
ia = CTF_Matrix(no,nv,NS,dw_,"Via",1);
ij = CTF_Matrix(no,no,AS,dw_,"Vij",1);
abcd = CTF_Tensor(4,vvvv,shapeASAS,dw_,"Vabcd",1);
abci = CTF_Tensor(4,vvvo,shapeASNS,dw_,"Vabci",1);
aibc = CTF_Tensor(4,vovv,shapeNSAS,dw_,"Vaibc",1);
aibj = CTF_Tensor(4,vovo,shapeNSNS,dw_,"Vaibj",1);
abij = CTF_Tensor(4,vvoo,shapeASAS,dw_,"Vabij",1);
ijab = CTF_Tensor(4,oovv,shapeASAS,dw_,"Vijab",1);
aijk = CTF_Tensor(4,vooo,shapeNSAS,dw_,"Vaijk",1);
ijak = CTF_Tensor(4,oovo,shapeASNS,dw_,"Vijak",1);
ijkl = CTF_Tensor(4,oooo,shapeASAS,dw_,"Vijkl",1);
}
void fill_rand(){
int i, rank;
long_int j, sz, * indices;
double * values;
CTF_Tensor * tarr[] = {&aa, &ii, &ab, &ai, &ia, &ij,
&abcd, &abci, &aibc, &aibj,
&abij, &ijab, &aijk, &ijak, &ijkl};
MPI_Comm comm = dw->comm;
MPI_Comm_rank(comm, &rank);
srand48(rank*13);
for (i=0; i<15; i++){
tarr[i]->read_local(&sz, &indices, &values);
// for (j=0; j<sz; j++) values[j] = drand48()-.5;
for (j=0; j<sz; j++) values[j] = ((indices[j]*16+i)%13077)/13077. -.5;
tarr[i]->write(sz, indices, values);
free(indices), free(values);
}
}
tCTF_Idx_Tensor<double> operator[](char const * idx_map_){
int i, lenm, no, nv;
lenm = strlen(idx_map_);
char new_idx_map[lenm+1];
new_idx_map[lenm]='\0';
no = 0;
nv = 0;
for (i=0; i<lenm; i++){
if (idx_map_[i] >= 'a' && idx_map_[i] <= 'h'){
new_idx_map[i] = 'a'+nv;
nv++;
} else if (idx_map_[i] >= 'i' && idx_map_[i] <= 'n'){
new_idx_map[i] = 'i'+no;
no++;
}
}
// printf("indices %s are %s\n",idx_map_,new_idx_map);
if (0 == strcmp("a",new_idx_map)) return aa[idx_map_];
if (0 == strcmp("i",new_idx_map)) return ii[idx_map_];
if (0 == strcmp("ab",new_idx_map)) return ab[idx_map_];
if (0 == strcmp("ai",new_idx_map)) return ai[idx_map_];
if (0 == strcmp("ia",new_idx_map)) return ia[idx_map_];
if (0 == strcmp("ij",new_idx_map)) return ij[idx_map_];
if (0 == strcmp("abcd",new_idx_map)) return abcd[idx_map_];
if (0 == strcmp("abci",new_idx_map)) return abci[idx_map_];
if (0 == strcmp("aibc",new_idx_map)) return aibc[idx_map_];
if (0 == strcmp("aibj",new_idx_map)) return aibj[idx_map_];
if (0 == strcmp("abij",new_idx_map)) return abij[idx_map_];
if (0 == strcmp("ijab",new_idx_map)) return ijab[idx_map_];
if (0 == strcmp("aijk",new_idx_map)) return aijk[idx_map_];
if (0 == strcmp("ijak",new_idx_map)) return ijak[idx_map_];
if (0 == strcmp("ijkl",new_idx_map)) return ijkl[idx_map_];
printf("Invalid integral indices\n");
ABORT;
//shut up compiler
return aa[idx_map_];
}
};
class Amplitudes {
public:
CTF_Tensor ai;
CTF_Tensor abij;
CTF_World * dw;
Amplitudes(int no, int nv, CTF_World &dw_){
dw = &dw_;
int shapeASAS[] = {AS,NS,AS,NS};
int vvoo[] = {nv,nv,no,no};
ai = CTF_Matrix(nv,no,NS,dw_,"Tai",1);
abij = CTF_Tensor(4,vvoo,shapeASAS,dw_,"Tabij",1);
}
tCTF_Idx_Tensor<double> operator[](char const * idx_map_){
if (strlen(idx_map_) == 4) return abij[idx_map_];
else return ai[idx_map_];
}
void fill_rand(){
int i, rank;
long_int j, sz, * indices;
double * values;
CTF_Tensor * tarr[] = {&ai, &abij};
MPI_Comm comm = dw->comm;
MPI_Comm_rank(comm, &rank);
srand48(rank*25);
for (i=0; i<2; i++){
tarr[i]->read_local(&sz, &indices, &values);
// for (j=0; j<sz; j++) values[j] = drand48()-.5;
for (j=0; j<sz; j++) values[j] = ((indices[j]*13+i)%13077)/13077. -.5;
tarr[i]->write(sz, indices, values);
free(indices), free(values);
}
}
};
void ccsd(Integrals &V,
Amplitudes &T){
tCTF_Schedule<double> sched;
sched.record();
CTF_Tensor T21 = CTF_Tensor(T.abij);
T21["abij"] += .5*T["ai"]*T["bj"];
CTF_Tensor tFme(*V["me"].parent);
CTF_Idx_Tensor Fme(&tFme,"me");
Fme += V["me"];
Fme += V["mnef"]*T["fn"];
CTF_Tensor tFae(*V["ae"].parent);
CTF_Idx_Tensor Fae(&tFae,"ae");
Fae += V["ae"];
Fae -= Fme*T["am"];
Fae -=.5*V["mnef"]*T["afmn"];
Fae += V["anef"]*T["fn"];
CTF_Tensor tFmi(*V["mi"].parent);
CTF_Idx_Tensor Fmi(&tFmi,"mi");
Fmi += V["mi"];
Fmi += Fme*T["ei"];
Fmi += .5*V["mnef"]*T["efin"];
Fmi += V["mnfi"]*T["fn"];
CTF_Tensor tWmnei(*V["mnei"].parent);
CTF_Idx_Tensor Wmnei(&tWmnei,"mnei");
Wmnei += V["mnei"];
Wmnei += V["mnei"];
Wmnei += V["mnef"]*T["fi"];
CTF_Tensor tWmnij(*V["mnij"].parent);
CTF_Idx_Tensor Wmnij(&tWmnij,"mnij");
Wmnij += V["mnij"];
Wmnij -= V["mnei"]*T["ej"];
Wmnij += V["mnef"]*T21["efij"];
CTF_Tensor tWamei(*V["amei"].parent);
CTF_Idx_Tensor Wamei(&tWamei,"amei");
Wamei += V["amei"];
Wamei -= Wmnei*T["an"];
Wamei += V["amef"]*T["fi"];
Wamei += .5*V["mnef"]*T["afin"];
CTF_Tensor tWamij(*V["amij"].parent);
CTF_Idx_Tensor Wamij(&tWamij,"amij");
Wamij += V["amij"];
Wamij += V["amei"]*T["ej"];
Wamij += V["amef"]*T["efij"];
CTF_Tensor tZai(*V["ai"].parent);
CTF_Idx_Tensor Zai(&tZai,"ai");
Zai += V["ai"];
Zai -= Fmi*T["am"];
Zai += V["ae"]*T["ei"];
Zai += V["amei"]*T["em"];
Zai += V["aeim"]*Fme;
Zai += .5*V["amef"]*T21["efim"];
Zai -= .5*Wmnei*T21["eamn"];
CTF_Tensor tZabij(*V["abij"].parent);
CTF_Idx_Tensor Zabij(&tZabij,"abij");
Zabij += V["abij"];
Zabij += V["abei"]*T["ej"];
Zabij += Wamei*T["ebmj"];
Zabij -= Wamij*T["bm"];
Zabij += Fae*T["ebij"];
Zabij -= Fmi*T["abmj"];
Zabij += .5*V["abef"]*T21["efij"];
Zabij += .5*Wmnij*T21["abmn"];
CTF_fctr fctr;
fctr.func_ptr = ÷
CTF_Tensor Dai(2, V.ai.len, V.ai.sym, *V.dw);
int sh_sym[4] = {SH, NS, SH, NS};
CTF_Tensor Dabij(4, V.abij.len, sh_sym, *V.dw);
Dai["ai"] += V["i"];
Dai["ai"] -= V["a"];
Dabij["abij"] += V["i"];
Dabij["abij"] += V["j"];
Dabij["abij"] -= V["a"];
Dabij["abij"] -= V["b"];
sched.execute();
T.ai.contract(1.0, *(Zai.parent), "ai", Dai, "ai", 0.0, "ai", fctr);
T.abij.contract(1.0, *(Zabij.parent), "abij", Dabij, "abij", 0.0, "abij", fctr);
}
#ifndef TEST_SUITE
char* getCmdOption(char ** begin,
char ** end,
const std::string & option){
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end){
return *itr;
}
return 0;
}
int main(int argc, char ** argv){
int rank, np, niter, no, nv, i;
int const in_num = argc;
char ** input_str = argv;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &np);
if (getCmdOption(input_str, input_str+in_num, "-no")){
no = atoi(getCmdOption(input_str, input_str+in_num, "-no"));
if (no < 0) no= 4;
} else no = 4;
if (getCmdOption(input_str, input_str+in_num, "-nv")){
nv = atoi(getCmdOption(input_str, input_str+in_num, "-nv"));
if (nv < 0) nv = 6;
} else nv = 6;
if (getCmdOption(input_str, input_str+in_num, "-niter")){
niter = atoi(getCmdOption(input_str, input_str+in_num, "-niter"));
if (niter < 0) niter = 1;
} else niter = 1;
{
CTF_World dw(argc, argv);
{
Integrals V(no, nv, dw);
V.fill_rand();
Amplitudes T(no, nv, dw);
for (i=0; i<niter; i++){
T.fill_rand();
double d = MPI_Wtime();
ccsd(V,T);
if (rank == 0)
printf("Completed %dth CCSD iteration in time = %lf, |T| is %lf\n",
i, MPI_Wtime()-d, T.ai.norm2()+T.abij.norm2());
else {
T.ai.norm2();
T.abij.norm2();
}
T["ai"] = (1./T.ai.norm2())*T["ai"];
T["abij"] = (1./T.abij.norm2())*T["abij"];
}
}
}
MPI_Finalize();
return 0;
}
/**
* @}
* @}
*/
#endif
|
Make CCSD use schedule record
|
Make CCSD use schedule record
|
C++
|
bsd-2-clause
|
devinamatthews/ctf,devinamatthews/ctf,devinamatthews/ctf
|
89371385dd2bcb02a99a1308ca809cbbe69b6f0f
|
examples/mongocxx/connect.cpp
|
examples/mongocxx/connect.cpp
|
// Copyright 2015 MongoDB 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 <cstdlib>
#include <iostream>
#include <string>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/make_unique.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/logger.hpp>
#include <mongocxx/options/client.hpp>
#include <mongocxx/uri.hpp>
namespace {
class logger final : public mongocxx::logger {
public:
explicit logger(std::ostream* stream) : _stream(stream) {
}
void operator()(mongocxx::log_level level, mongocxx::stdx::string_view domain,
mongocxx::stdx::string_view message) noexcept override {
if (level >= mongocxx::log_level::k_trace) return;
*_stream << '[' << mongocxx::to_string(level) << '@' << domain << "] " << message << '\n';
}
private:
std::ostream* const _stream;
};
} // namespace
int main(int argc, char* argv[]) {
using bsoncxx::builder::stream::document;
mongocxx::instance inst{bsoncxx::stdx::make_unique<logger>(&std::cout)};
try {
const auto uri = mongocxx::uri{(argc >= 2) ? argv[1] : mongocxx::uri::k_default_uri};
mongocxx::options::client client_options;
if (uri.ssl()) {
mongocxx::options::ssl ssl_options;
// NOTE: To test SSL, you may need to set options. The following
// would enable certificates for Homebrew OpenSSL on OS X.
// options.ca_file("/usr/local/etc/openssl/cert.pem");
// ssl_options.ca_file("/usr/local/etc/openssl/cert.pem");
client_options.ssl_opts(ssl_options);
}
auto client = mongocxx::client{uri, client_options};
auto admin = client["admin"];
document ismaster;
ismaster << "isMaster" << 1;
auto result = admin.run_command(ismaster.view());
std::cout << bsoncxx::to_json(result) << "\n";
return EXIT_SUCCESS;
} catch (const std::exception& xcp) {
std::cout << "connection failed: " << xcp.what() << "\n";
return EXIT_FAILURE;
}
}
|
// Copyright 2015 MongoDB 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 <cstdlib>
#include <iostream>
#include <string>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/make_unique.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/logger.hpp>
#include <mongocxx/options/client.hpp>
#include <mongocxx/uri.hpp>
namespace {
class logger final : public mongocxx::logger {
public:
explicit logger(std::ostream* stream) : _stream(stream) {
}
void operator()(mongocxx::log_level level, mongocxx::stdx::string_view domain,
mongocxx::stdx::string_view message) noexcept override {
if (level >= mongocxx::log_level::k_trace) return;
*_stream << '[' << mongocxx::to_string(level) << '@' << domain << "] " << message << '\n';
}
private:
std::ostream* const _stream;
};
} // namespace
int main(int argc, char* argv[]) {
using bsoncxx::builder::stream::document;
mongocxx::instance inst{bsoncxx::stdx::make_unique<logger>(&std::cout)};
try {
const auto uri = mongocxx::uri{(argc >= 2) ? argv[1] : mongocxx::uri::k_default_uri};
mongocxx::options::client client_options;
if (uri.ssl()) {
mongocxx::options::ssl ssl_options;
// NOTE: To test SSL, you may need to set options.
//
// If the server certificate is not signed by a well-known CA,
// you can set a custom CA file with the `ca_file` option.
// ssl_options.ca_file("/path/to/custom/cert.pem");
//
// If you want to disable certificate verification, you
// can set the `allow_invalid_certificates` option.
// ssl_options.allow_invalid_certificates(true);
client_options.ssl_opts(ssl_options);
}
auto client = mongocxx::client{uri, client_options};
auto admin = client["admin"];
document ismaster;
ismaster << "isMaster" << 1;
auto result = admin.run_command(ismaster.view());
std::cout << bsoncxx::to_json(result) << "\n";
return EXIT_SUCCESS;
} catch (const std::exception& xcp) {
std::cout << "connection failed: " << xcp.what() << "\n";
return EXIT_FAILURE;
}
}
|
Update SSL config comments in connection example program
|
minor: Update SSL config comments in connection example program
|
C++
|
apache-2.0
|
xdg/mongo-cxx-driver,mongodb/mongo-cxx-driver,acmorrow/mongo-cxx-driver,mongodb/mongo-cxx-driver,xdg/mongo-cxx-driver,acmorrow/mongo-cxx-driver,mongodb/mongo-cxx-driver,acmorrow/mongo-cxx-driver,xdg/mongo-cxx-driver,acmorrow/mongo-cxx-driver,xdg/mongo-cxx-driver,mongodb/mongo-cxx-driver
|
7c9ca68bc22e7b88d694a412c460bb4b903a6bb3
|
include/BinaryTree.hpp
|
include/BinaryTree.hpp
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
void _deleteElements(Node<T>*);
Node<T>* root;
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
Node<T>*root_();
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root_();
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
BinaryTree(const std::initializer_list<T>&);
void _deleteElements(Node<T>*);
Node<T>* root;
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& output(std::ostream& ost, const Node<T>* temp);
friend std::ostream& operator<<(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp)
{
if (temp == nullptr)
{
throw "error";
}
else
{
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
show(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
show(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
if (!temp.root)
throw "error";
show(ost, temp.root, 0);
return ost;
}
|
Update BinaryTree.hpp
|
Update BinaryTree.hpp
|
C++
|
mit
|
rtv22/BinaryTree_S
|
ae49eaac765b3073d682b9d88e3e658811557421
|
examples/src/apriltag_rgb.cpp
|
examples/src/apriltag_rgb.cpp
|
#include <chrono>
#include <iostream>
// Inludes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
int main() {
using namespace std;
using namespace std::chrono;
// Create pipeline
dai::Pipeline pipeline;
// Define sources and outputs
auto camRgb = pipeline.create<dai::node::ColorCamera>();
auto aprilTag = pipeline.create<dai::node::AprilTag>();
auto manip = pipeline.create<dai::node::ImageManip>();
auto xoutAprilTag = pipeline.create<dai::node::XLinkOut>();
auto manipOut = pipeline.create<dai::node::XLinkOut>();
xoutAprilTag->setStreamName("aprilTagData");
manipOut->setStreamName("manip");
// Properties
camRgb->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P);
camRgb->setBoardSocket(dai::CameraBoardSocket::RGB);
manip->initialConfig.setResize(480, 270);
manip->initialConfig.setFrameType(dai::ImgFrame::Type::GRAY8);
aprilTag->initialConfig.setType(dai::AprilTagType::Type::TAG_36H11);
// Linking
aprilTag->passthroughInputImage.link(manipOut->input);
camRgb->video.link(manip->inputImage);
manip->out.link(aprilTag->inputImage);
manip->out.link(manipOut->input);
aprilTag->out.link(xoutAprilTag->input);
// Connect to device and start pipeline
dai::Device device(pipeline);
// Output queue will be used to get the mono frames from the outputs defined above
auto manipQueue = device.getOutputQueue("manip", 8, false);
auto aprilTagQueue = device.getOutputQueue("aprilTagData", 8, false);
auto color = cv::Scalar(0, 255, 0);
auto startTime = steady_clock::now();
int counter = 0;
float fps = 0;
while(true) {
auto inFrame = manipQueue->get<dai::ImgFrame>();
counter++;
auto currentTime = steady_clock::now();
auto elapsed = duration_cast<duration<float>>(currentTime - startTime);
if(elapsed > seconds(1)) {
fps = counter / elapsed.count();
counter = 0;
startTime = currentTime;
}
cv::Mat frame = inFrame->getCvFrame();
auto aprilTagData = aprilTagQueue->get<dai::AprilTagData>()->aprilTags;
for(auto aprilTag : aprilTagData) {
auto xmin = (int)aprilTag.points.x;
auto ymin = (int)aprilTag.points.y;
auto xmax = xmin + (int)aprilTag.points.width;
auto ymax = ymin + (int)aprilTag.points.height;
std::stringstream idStr;
idStr << "ID: " << aprilTag.id;
cv::putText(frame, idStr.str(), cv::Point(xmin + 10, ymin + 35), cv::FONT_HERSHEY_TRIPLEX, 0.5, color);
cv::rectangle(frame, cv::Rect(cv::Point(xmin, ymin), cv::Point(xmax, ymax)), color, cv::FONT_HERSHEY_SIMPLEX);
}
std::stringstream fpsStr;
fpsStr << "fps:" << std::fixed << std::setprecision(2) << fps;
cv::putText(frame, fpsStr.str(), cv::Point(2, inFrame->getHeight() - 4), cv::FONT_HERSHEY_TRIPLEX, 0.4, color);
cv::imshow("manip", frame);
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
|
#include <chrono>
#include <iostream>
// Inludes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
int main() {
using namespace std;
using namespace std::chrono;
// Create pipeline
dai::Pipeline pipeline;
// Define sources and outputs
auto camRgb = pipeline.create<dai::node::ColorCamera>();
auto aprilTag = pipeline.create<dai::node::AprilTag>();
auto manip = pipeline.create<dai::node::ImageManip>();
auto xoutAprilTag = pipeline.create<dai::node::XLinkOut>();
auto manipOut = pipeline.create<dai::node::XLinkOut>();
xoutAprilTag->setStreamName("aprilTagData");
manipOut->setStreamName("manip");
// Properties
camRgb->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P);
camRgb->setBoardSocket(dai::CameraBoardSocket::RGB);
manip->initialConfig.setResize(480, 270);
manip->initialConfig.setFrameType(dai::ImgFrame::Type::GRAY8);
aprilTag->initialConfig.setType(dai::AprilTagType::Type::TAG_36H11);
// Linking
aprilTag->passthroughInputImage.link(manipOut->input);
camRgb->video.link(manip->inputImage);
manip->out.link(aprilTag->inputImage);
aprilTag->out.link(xoutAprilTag->input);
// Connect to device and start pipeline
dai::Device device(pipeline);
// Output queue will be used to get the mono frames from the outputs defined above
auto manipQueue = device.getOutputQueue("manip", 8, false);
auto aprilTagQueue = device.getOutputQueue("aprilTagData", 8, false);
auto color = cv::Scalar(0, 255, 0);
auto startTime = steady_clock::now();
int counter = 0;
float fps = 0;
while(true) {
auto inFrame = manipQueue->get<dai::ImgFrame>();
counter++;
auto currentTime = steady_clock::now();
auto elapsed = duration_cast<duration<float>>(currentTime - startTime);
if(elapsed > seconds(1)) {
fps = counter / elapsed.count();
counter = 0;
startTime = currentTime;
}
cv::Mat frame = inFrame->getCvFrame();
auto aprilTagData = aprilTagQueue->get<dai::AprilTagData>()->aprilTags;
for(auto aprilTag : aprilTagData) {
auto xmin = (int)aprilTag.points.x;
auto ymin = (int)aprilTag.points.y;
auto xmax = xmin + (int)aprilTag.points.width;
auto ymax = ymin + (int)aprilTag.points.height;
std::stringstream idStr;
idStr << "ID: " << aprilTag.id;
cv::putText(frame, idStr.str(), cv::Point(xmin + 10, ymin + 35), cv::FONT_HERSHEY_TRIPLEX, 0.5, color);
cv::rectangle(frame, cv::Rect(cv::Point(xmin, ymin), cv::Point(xmax, ymax)), color, cv::FONT_HERSHEY_SIMPLEX);
}
std::stringstream fpsStr;
fpsStr << "fps:" << std::fixed << std::setprecision(2) << fps;
cv::putText(frame, fpsStr.str(), cv::Point(2, inFrame->getHeight() - 4), cv::FONT_HERSHEY_TRIPLEX, 0.4, color);
cv::imshow("manip", frame);
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
|
Update linking
|
Update linking
|
C++
|
mit
|
luxonis/depthai-core,luxonis/depthai-core,luxonis/depthai-core
|
33ae1cb0efe0b82939ecb278e3c0de2294cca3e5
|
include/BinaryTree.hpp
|
include/BinaryTree.hpp
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <typename T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <typename T>
struct Node {
Node *left;
Node *right;
T data;
};
template <class T>
class BinaryTree
{
private:
Node<T>*root;
int CountElements = 0;
public:
BinaryTree();
~BinaryTree();
Node<T>* root_();
unsigned int count() const;
void insert_node(const T&x);
Node<T> *find_node(const T&, Node<T>*)const;
void deleteNode(Node<T>* temp);
void writing(const std::string& filename)const;
friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);
};
template <typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<typename T>
Node<T>* BinaryTree<T>::root_()
{
return root;
}
template <typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
{
throw "error";
}
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
template <typename T>
std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level)
{
if (!node)
return ost;
output(ost, node->right, level + 1);
for (unsigned int i = 0; i < level; i++)
ost << "\t";
ost << node->data << std::endl;
output(ost, node->left, level + 1);
return ost;
}
template <typename T>
std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)
{
//if (!temp.root)
//throw "error";
output(ost, temp.root, 0);
return ost;
}
|
Update BinaryTree.hpp
|
Update BinaryTree.hpp
|
C++
|
mit
|
rtv22/BinaryTree_S
|
01f06abf31f66dc3f2fdfab38082021d6fa0116f
|
distbench_node_manager.cc
|
distbench_node_manager.cc
|
// Copyright 2021 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 "distbench_node_manager.h"
#include "distbench_utils.h"
#include "protocol_driver_allocator.h"
#include "absl/strings/str_split.h"
#include "glog/logging.h"
namespace distbench {
NodeManager::NodeManager(SimpleClock* clock) {
clock_ = clock;
}
grpc::Status NodeManager::ConfigureNode(
grpc::ServerContext* context,
const NodeServiceConfig* request,
ServiceEndpointMap* response) {
LOG(INFO) << request->DebugString();
absl::MutexLock m (&mutex_);
traffic_config_ = request->traffic_config();
ClearServices();
auto& service_map = *response->mutable_service_endpoints();
for (const auto& service_name : request->services()) {
std::vector<std::string> service_instance =
absl::StrSplit(service_name, '/');
CHECK_EQ(service_instance.size(), 2lu);
int port = AllocatePort();
service_ports_.push_back(port);
int instance;
CHECK(absl::SimpleAtoi(service_instance[1], &instance));
absl::Status ret = AllocService({
service_name,
service_instance[0],
instance,
port,
traffic_config_.default_protocol(),
"eth0"});
if (!ret.ok())
grpc::Status(grpc::StatusCode::UNKNOWN,
absl::StrCat("AllocService failure: ", ret.ToString()));
auto& service_entry = service_map[service_name];
service_entry.set_endpoint_address(SocketAddressForDevice("", port));
service_entry.set_hostname(Hostname());
}
return grpc::Status::OK;
}
void NodeManager::ClearServices() {
service_engines_.clear();
for (const auto& port : service_ports_) {
FreePort(port);
}
service_ports_.clear();
}
absl::Status NodeManager::AllocService(
const ServiceOpts& service_opts) {
CHECK(service_opts.port);
ProtocolDriverOptions pd_opts;
pd_opts.set_protocol_name(std::string(service_opts.protocol));
pd_opts.set_netdev_name(std::string(service_opts.netdev));
std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(pd_opts);
absl::Status ret = pd->Initialize("eth0", AllocatePort());
if (!ret.ok()) return ret;
auto engine = std::make_unique<DistBenchEngine>(std::move(pd), clock_);
ret = engine->Initialize(
service_opts.port, traffic_config_, service_opts.service_type,
service_opts.service_instance);
if (!ret.ok()) return ret;
service_engines_[std::string(service_opts.service_name)] = std::move(engine);
return absl::OkStatus();
}
grpc::Status NodeManager::IntroducePeers(grpc::ServerContext* context,
const ServiceEndpointMap* request,
IntroducePeersResult* response) {
absl::MutexLock m (&mutex_);
peers_ = *request;
for (const auto& service_engine : service_engines_) {
auto ret = service_engine.second->ConfigurePeers(peers_);
if (!ret.ok())
return grpc::Status(grpc::StatusCode::UNKNOWN, "ConfigurePeers failure");
}
return grpc::Status::OK;
}
grpc::Status NodeManager::RunTraffic(grpc::ServerContext* context,
const RunTrafficRequest* request,
ServiceLogs* response) {
absl::ReaderMutexLock m (&mutex_);
for (const auto& service_engine : service_engines_) {
auto ret = service_engine.second->RunTraffic(request);
if (!ret.ok())
return grpc::Status(grpc::StatusCode::UNKNOWN, "RunTraffic failure");
}
for (const auto& service_engine : service_engines_) {
auto log = service_engine.second->FinishTrafficAndGetLogs();
if (!log.peer_logs().empty()) {
(*response->mutable_instance_logs())[service_engine.first] =
std::move(log);
}
}
return grpc::Status::OK;
}
grpc::Status NodeManager::CancelTraffic(grpc::ServerContext* context,
const CancelTrafficRequest* request,
CancelTrafficResult* response) {
LOG(INFO) << "saw the cancelation now";
absl::ReaderMutexLock m (&mutex_);
for (const auto& service_engine : service_engines_) {
service_engine.second->CancelTraffic();
}
LOG(INFO) << "finished all the cancelations now";
return grpc::Status::OK;
}
void NodeManager::Shutdown() {
if (grpc_server_) {
grpc_server_->Shutdown();
}
}
void NodeManager::Wait() {
if (grpc_server_) {
grpc_server_->Wait();
}
}
NodeManager::~NodeManager() {
ClearServices();
if (grpc_server_) {
grpc_server_->Shutdown();
grpc_server_->Wait();
}
}
absl::Status NodeManager::Initialize(const NodeManagerOpts& opts) {
opts_ = opts;
if (opts_.test_sequencer_service_address.empty()) {
return absl::InvalidArgumentError(
"node_manager requires the --test_sequencer flag.");
}
std::shared_ptr<grpc::ChannelCredentials> client_creds =
MakeChannelCredentials();
std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(
opts_.test_sequencer_service_address, client_creds);
std::unique_ptr<DistBenchTestSequencer::Stub> test_sequencer_stub =
DistBenchTestSequencer::NewStub(channel);
service_address_ = absl::StrCat("[::]:", opts_.port);
grpc::ServerBuilder builder;
std::shared_ptr<grpc::ServerCredentials> server_creds =
MakeServerCredentials();
builder.AddListeningPort(service_address_, server_creds);
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.RegisterService(this);
grpc_server_ = builder.BuildAndStart();
if (grpc_server_) {
LOG(INFO) << "Server listening on " << service_address_;
}
if (!grpc_server_) {
return absl::UnknownError("NodeManager service failed to start");
}
NodeRegistration reg;
reg.set_hostname(Hostname());
reg.set_control_port(opts_.port);
NodeConfig config;
grpc::ClientContext context;
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::seconds(60);
context.set_deadline(deadline);
context.set_wait_for_ready(true);
grpc::Status status =
test_sequencer_stub->RegisterNode(&context, reg, &config);
if (status.ok()) {
LOG(INFO) << "NodeConfig: " << config.ShortDebugString();
} else {
status = Annotate(status, absl::StrCat(
"While registering node to test sequencer(",
opts_.test_sequencer_service_address,
"): "));
grpc_server_->Shutdown();
}
if (status.ok())
return absl::OkStatus();
return absl::InvalidArgumentError(status.error_message());
}
} // namespace distbench
|
// Copyright 2021 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 "distbench_node_manager.h"
#include "distbench_utils.h"
#include "protocol_driver_allocator.h"
#include "absl/strings/str_split.h"
#include "glog/logging.h"
namespace distbench {
NodeManager::NodeManager(SimpleClock* clock) {
clock_ = clock;
}
grpc::Status NodeManager::ConfigureNode(
grpc::ServerContext* context,
const NodeServiceConfig* request,
ServiceEndpointMap* response) {
LOG(INFO) << request->DebugString();
absl::MutexLock m (&mutex_);
traffic_config_ = request->traffic_config();
ClearServices();
auto& service_map = *response->mutable_service_endpoints();
for (const auto& service_name : request->services()) {
std::vector<std::string> service_instance =
absl::StrSplit(service_name, '/');
CHECK_EQ(service_instance.size(), 2lu);
int port = AllocatePort();
service_ports_.push_back(port);
int instance;
CHECK(absl::SimpleAtoi(service_instance[1], &instance));
absl::Status ret = AllocService({
service_name,
service_instance[0],
instance,
port,
traffic_config_.default_protocol(),
"eth0"});
if (!ret.ok()) {
return grpc::Status(grpc::StatusCode::UNKNOWN,
absl::StrCat("AllocService failure: ", ret.ToString()));
}
auto& service_entry = service_map[service_name];
service_entry.set_endpoint_address(SocketAddressForDevice("", port));
service_entry.set_hostname(Hostname());
}
return grpc::Status::OK;
}
void NodeManager::ClearServices() {
service_engines_.clear();
for (const auto& port : service_ports_) {
FreePort(port);
}
service_ports_.clear();
}
absl::Status NodeManager::AllocService(
const ServiceOpts& service_opts) {
CHECK(service_opts.port);
ProtocolDriverOptions pd_opts;
pd_opts.set_protocol_name(std::string(service_opts.protocol));
pd_opts.set_netdev_name(std::string(service_opts.netdev));
std::unique_ptr<ProtocolDriver> pd = AllocateProtocolDriver(pd_opts);
absl::Status ret = pd->Initialize("eth0", AllocatePort());
if (!ret.ok()) return ret;
auto engine = std::make_unique<DistBenchEngine>(std::move(pd), clock_);
ret = engine->Initialize(
service_opts.port, traffic_config_, service_opts.service_type,
service_opts.service_instance);
if (!ret.ok()) return ret;
service_engines_[std::string(service_opts.service_name)] = std::move(engine);
return absl::OkStatus();
}
grpc::Status NodeManager::IntroducePeers(grpc::ServerContext* context,
const ServiceEndpointMap* request,
IntroducePeersResult* response) {
absl::MutexLock m (&mutex_);
peers_ = *request;
for (const auto& service_engine : service_engines_) {
auto ret = service_engine.second->ConfigurePeers(peers_);
if (!ret.ok())
return grpc::Status(grpc::StatusCode::UNKNOWN, "ConfigurePeers failure");
}
return grpc::Status::OK;
}
grpc::Status NodeManager::RunTraffic(grpc::ServerContext* context,
const RunTrafficRequest* request,
ServiceLogs* response) {
absl::ReaderMutexLock m (&mutex_);
for (const auto& service_engine : service_engines_) {
auto ret = service_engine.second->RunTraffic(request);
if (!ret.ok())
return grpc::Status(grpc::StatusCode::UNKNOWN, "RunTraffic failure");
}
for (const auto& service_engine : service_engines_) {
auto log = service_engine.second->FinishTrafficAndGetLogs();
if (!log.peer_logs().empty()) {
(*response->mutable_instance_logs())[service_engine.first] =
std::move(log);
}
}
return grpc::Status::OK;
}
grpc::Status NodeManager::CancelTraffic(grpc::ServerContext* context,
const CancelTrafficRequest* request,
CancelTrafficResult* response) {
LOG(INFO) << "saw the cancelation now";
absl::ReaderMutexLock m (&mutex_);
for (const auto& service_engine : service_engines_) {
service_engine.second->CancelTraffic();
}
LOG(INFO) << "finished all the cancelations now";
return grpc::Status::OK;
}
void NodeManager::Shutdown() {
if (grpc_server_) {
grpc_server_->Shutdown();
}
}
void NodeManager::Wait() {
if (grpc_server_) {
grpc_server_->Wait();
}
}
NodeManager::~NodeManager() {
ClearServices();
if (grpc_server_) {
grpc_server_->Shutdown();
grpc_server_->Wait();
}
}
absl::Status NodeManager::Initialize(const NodeManagerOpts& opts) {
opts_ = opts;
if (opts_.test_sequencer_service_address.empty()) {
return absl::InvalidArgumentError(
"node_manager requires the --test_sequencer flag.");
}
std::shared_ptr<grpc::ChannelCredentials> client_creds =
MakeChannelCredentials();
std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(
opts_.test_sequencer_service_address, client_creds);
std::unique_ptr<DistBenchTestSequencer::Stub> test_sequencer_stub =
DistBenchTestSequencer::NewStub(channel);
service_address_ = absl::StrCat("[::]:", opts_.port);
grpc::ServerBuilder builder;
std::shared_ptr<grpc::ServerCredentials> server_creds =
MakeServerCredentials();
builder.AddListeningPort(service_address_, server_creds);
builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);
builder.RegisterService(this);
grpc_server_ = builder.BuildAndStart();
if (grpc_server_) {
LOG(INFO) << "Server listening on " << service_address_;
}
if (!grpc_server_) {
return absl::UnknownError("NodeManager service failed to start");
}
NodeRegistration reg;
reg.set_hostname(Hostname());
reg.set_control_port(opts_.port);
NodeConfig config;
grpc::ClientContext context;
std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::seconds(60);
context.set_deadline(deadline);
context.set_wait_for_ready(true);
grpc::Status status =
test_sequencer_stub->RegisterNode(&context, reg, &config);
if (status.ok()) {
LOG(INFO) << "NodeConfig: " << config.ShortDebugString();
} else {
status = Annotate(status, absl::StrCat(
"While registering node to test sequencer(",
opts_.test_sequencer_service_address,
"): "));
grpc_server_->Shutdown();
}
if (status.ok())
return absl::OkStatus();
return absl::InvalidArgumentError(status.error_message());
}
} // namespace distbench
|
Fix typo of missing return statement for error handling.
|
distbench_node_manager.cc: Fix typo of missing return statement for error handling.
|
C++
|
apache-2.0
|
google/distbench,google/distbench,google/distbench
|
214ea7c06496e4accce258d0d1c1b7178be615fa
|
include/pod_vector.hpp
|
include/pod_vector.hpp
|
///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdint.h>
#include <type_traits>
#include <utility>
namespace primecount {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primecount's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T,
typename Allocator = std::allocator<T>>
class pod_vector
{
public:
// The default C++ std::allocator is stateless. We use this
// allocator and do not support other statefull allocators,
// which simplifies our implementation.
//
// "The default allocator is stateless, that is, all instances
// of the given allocator are interchangeable, compare equal
// and can deallocate memory allocated by any other instance
// of the same allocator type."
// https://en.cppreference.com/w/cpp/memory/allocator
//
// "The member type is_always_equal of std::allocator_traits
// is intendedly used for determining whether an allocator
// type is stateless."
// https://en.cppreference.com/w/cpp/named_req/Allocator
static_assert(std::allocator_traits<Allocator>::is_always_equal::value,
"pod_vector<T> only supports stateless allocators!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
destroy(array_, end_);
Allocator().deallocate(array_, capacity());
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void deallocate() noexcept
{
this->~pod_vector<T>();
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
destroy(array_, end_);
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
swap(other);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
swap(other);
return *this;
}
/// Better assembly than: std::swap(vect1, vect2)
void swap(pod_vector& other) noexcept
{
T* tmp_array = array_;
T* tmp_end = end_;
T* tmp_capacity = capacity_;
array_ = other.array_;
end_ = other.end_;
capacity_ = other.capacity_;
other.array_ = tmp_array;
other.end_ = tmp_end;
other.capacity_ = tmp_capacity;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
ASSERT(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
ASSERT(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
const T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
ASSERT(!empty());
return *array_;
}
const T& front() const noexcept
{
ASSERT(!empty());
return *array_;
}
T& back() noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
const T& back() const noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(value);
end_++;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Without std::move() the copy constructor will
// be called instead of the move constructor.
new(end_) T(std::move(value));
end_++;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(std::forward<Args>(args)...);
end_++;
}
template <class InputIt>
void insert(T* const pos, InputIt first, InputIt last)
{
static_assert(std::is_trivially_copyable<T>::value,
"pod_vector<T>::insert() supports only trivially copyable types!");
// We only support appending to the vector
ASSERT(pos == end_);
(void) pos;
if (first < last)
{
std::size_t new_size = size() + (std::size_t) (last - first);
reserve(new_size);
std::uninitialized_copy(first, last, end_);
end_ = array_ + new_size;
}
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
void resize(std::size_t n)
{
if (n > size())
{
if (n > capacity())
reserve_unchecked(n);
// This default initializes memory of classes and structs
// with constructors (and with in-class initialization of
// non-static members). But it does not default initialize
// memory for POD types like int, long.
if (!std::is_trivial<T>::value)
uninitialized_default_construct(end_, array_ + n);
end_ = array_ + n;
}
else if (n < size())
{
destroy(array_ + n, end_);
end_ = array_ + n;
}
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
void reserve_unchecked(std::size_t n)
{
ASSERT(n > capacity());
std::size_t old_size = size();
std::size_t old_capacity = capacity();
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (old_capacity * 3) / 2;
new_capacity = std::max(new_capacity, n);
ASSERT(new_capacity > old_size);
T* old = array_;
array_ = Allocator().allocate(new_capacity);
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
// Both primesieve & primecount require that byte arrays are
// aligned to at least a alignof(uint64_t) boundary. This is
// needed because our code casts byte arrays into uint64_t arrays
// in some places in order to improve performance. The default
// allocator guarantees that each memory allocation is at least
// aligned to the largest built-in type (usually 16 or 32).
ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0);
if (old)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"pod_vector<T> only supports nothrow moveable types!");
uninitialized_move_n(old, old_size, array_);
Allocator().deallocate(old, old_capacity);
}
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
// We can use memcpy to move trivially copyable types.
// https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class
// https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy
std::uninitialized_copy_n(first, count, d_first);
}
/// Same as std::uninitialized_move_n() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n
///
/// Unlike std::uninitialized_move_n() our implementation uses
/// __restrict pointers which improves the generated assembly
/// (using GCC & Clang). We can do this because we only use this
/// method for non-overlapping arrays.
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
for (std::size_t i = 0; i < count; i++)
new (d_first++) T(std::move(*first++));
}
/// Same as std::uninitialized_default_construct() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct
ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last)
{
// Default initialize array using placement new.
// Note that `new (first) T();` zero initializes built-in integer types,
// whereas `new (first) T;` does not initialize built-in integer types.
for (; first != last; first++)
new (first) T;
}
/// Same as std::destroy() from C++17.
/// https://en.cppreference.com/w/cpp/memory/destroy
ALWAYS_INLINE void destroy(T* first, T* last)
{
if (!std::is_trivially_destructible<T>::value)
{
// Theoretically deallocating in reverse order is more
// cache efficient. Clang's std::vector implementation
// also deallocates in reverse order.
while (first != last)
(--last)->~T();
}
}
};
template <typename T, std::size_t N>
class pod_array
{
public:
using value_type = T;
T array_[N];
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return array_ + N;
}
const T* end() const noexcept
{
return array_ + N;
}
T& back() noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
const T& back() const noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr std::size_t size() const noexcept
{
return N;
}
};
} // namespace
#endif
|
///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdint.h>
#include <type_traits>
#include <utility>
namespace primecount {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primecount's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T,
typename Allocator = std::allocator<T>>
class pod_vector
{
public:
// The default C++ std::allocator is stateless. We use this
// allocator and do not support other statefull allocators,
// which simplifies our implementation.
//
// "The default allocator is stateless, that is, all instances
// of the given allocator are interchangeable, compare equal
// and can deallocate memory allocated by any other instance
// of the same allocator type."
// https://en.cppreference.com/w/cpp/memory/allocator
//
// "The member type is_always_equal of std::allocator_traits
// is intendedly used for determining whether an allocator
// type is stateless."
// https://en.cppreference.com/w/cpp/named_req/Allocator
static_assert(std::allocator_traits<Allocator>::is_always_equal::value,
"pod_vector<T> only supports stateless allocators!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
destroy(array_, end_);
Allocator().deallocate(array_, capacity());
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void deallocate() noexcept
{
this->~pod_vector<T>();
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
destroy(array_, end_);
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
swap(other);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
swap(other);
return *this;
}
/// Better assembly than: std::swap(vect1, vect2)
void swap(pod_vector& other) noexcept
{
T* tmp_array = array_;
T* tmp_end = end_;
T* tmp_capacity = capacity_;
array_ = other.array_;
end_ = other.end_;
capacity_ = other.capacity_;
other.array_ = tmp_array;
other.end_ = tmp_end;
other.capacity_ = tmp_capacity;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
ASSERT(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
ASSERT(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
const T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
ASSERT(!empty());
return *array_;
}
const T& front() const noexcept
{
ASSERT(!empty());
return *array_;
}
T& back() noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
const T& back() const noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(value);
end_++;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Without std::move() the copy constructor will
// be called instead of the move constructor.
new(end_) T(std::move(value));
end_++;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(std::forward<Args>(args)...);
end_++;
}
template <class InputIt>
void insert(T* const pos, InputIt first, InputIt last)
{
static_assert(std::is_trivially_copyable<T>::value,
"pod_vector<T>::insert() supports only trivially copyable types!");
// We only support appending to the vector
ASSERT(pos == end_);
(void) pos;
if (first < last)
{
std::size_t new_size = size() + (std::size_t) (last - first);
reserve(new_size);
std::uninitialized_copy(first, last, end_);
end_ = array_ + new_size;
}
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
void resize(std::size_t n)
{
if (n > size())
{
if (n > capacity())
reserve_unchecked(n);
// This default initializes memory of classes and structs
// with constructors (and with in-class initialization of
// non-static members). But it does not default initialize
// memory for POD types like int, long.
if (!std::is_trivial<T>::value)
uninitialized_default_construct(end_, array_ + n);
end_ = array_ + n;
}
else if (n < size())
{
destroy(array_ + n, end_);
end_ = array_ + n;
}
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
/// Requires n > capacity()
void reserve_unchecked(std::size_t n)
{
ASSERT(n > capacity());
ASSERT(size() <= capacity());
std::size_t old_size = size();
std::size_t old_capacity = capacity();
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (old_capacity * 3) / 2;
new_capacity = std::max(new_capacity, n);
ASSERT(old_capacity < new_capacity);
T* old = array_;
array_ = Allocator().allocate(new_capacity);
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
ASSERT(size() < capacity());
// Both primesieve & primecount require that byte arrays are
// aligned to at least a alignof(uint64_t) boundary. This is
// needed because our code casts byte arrays into uint64_t arrays
// in some places in order to improve performance. The default
// allocator guarantees that each memory allocation is at least
// aligned to the largest built-in type (usually 16 or 32).
ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0);
if (old)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"pod_vector<T> only supports nothrow moveable types!");
uninitialized_move_n(old, old_size, array_);
Allocator().deallocate(old, old_capacity);
}
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
// We can use memcpy to move trivially copyable types.
// https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class
// https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy
std::uninitialized_copy_n(first, count, d_first);
}
/// Same as std::uninitialized_move_n() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n
///
/// Unlike std::uninitialized_move_n() our implementation uses
/// __restrict pointers which improves the generated assembly
/// (using GCC & Clang). We can do this because we only use this
/// method for non-overlapping arrays.
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
for (std::size_t i = 0; i < count; i++)
new (d_first++) T(std::move(*first++));
}
/// Same as std::uninitialized_default_construct() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct
ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last)
{
// Default initialize array using placement new.
// Note that `new (first) T();` zero initializes built-in integer types,
// whereas `new (first) T;` does not initialize built-in integer types.
for (; first != last; first++)
new (first) T;
}
/// Same as std::destroy() from C++17.
/// https://en.cppreference.com/w/cpp/memory/destroy
ALWAYS_INLINE void destroy(T* first, T* last)
{
if (!std::is_trivially_destructible<T>::value)
{
// Theoretically deallocating in reverse order is more
// cache efficient. Clang's std::vector implementation
// also deallocates in reverse order.
while (first != last)
(--last)->~T();
}
}
};
template <typename T, std::size_t N>
class pod_array
{
public:
using value_type = T;
T array_[N];
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return array_ + N;
}
const T* end() const noexcept
{
return array_ + N;
}
T& back() noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
const T& back() const noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr std::size_t size() const noexcept
{
return N;
}
};
} // namespace
#endif
|
Add more assertions
|
Add more assertions
|
C++
|
bsd-2-clause
|
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
|
43bae8e9c60a726a73218434c97e744fad938d0a
|
include/pdal/Utils.hpp
|
include/pdal/Utils.hpp
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/pdal_internal.hpp>
#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <ostream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/numeric/conversion/cast.hpp>
namespace pdal
{
class PDAL_DLL Utils
{
public:
static void random_seed(unsigned int seed);
static double random(double minimum, double maximum);
static double uniform(const double& minimum=0.0f, const double& maximum=1.0f, boost::uint32_t seed=0);
static double normal(const double& mean=0.0f, const double& sigma=1.0f, boost::uint32_t seed=0);
// compares two values to within the datatype's epsilon
template<class T>
static bool compare_distance(const T& actual, const T& expected)
{
const T epsilon = std::numeric_limits<T>::epsilon();
return compare_approx<T>(actual, expected, epsilon);
}
// compares two values to within a given tolerance
// the value |tolerance| is compared to |actual - expected|
template<class T>
static bool compare_approx(const T& actual, const T& expected,
const T& tolerance)
{
double diff = std::abs((double)actual - (double)expected);
return diff <= std::abs((double) tolerance);
}
// Copy v into *t and increment dest by the sizeof v
template<class T>
static inline void write_field(boost::uint8_t*& dest, T v)
{
*(T*)(void*)dest = v;
dest += sizeof(T);
}
// Return a 'T' from a stream and increment src by the sizeof 'T'
template<class T>
static inline T read_field(boost::uint8_t*& src)
{
T tmp = *(T*)(void*)src;
src += sizeof(T);
return tmp;
}
// Copy data from dest to src and increment dest by the copied size.
template<class T>
static inline void read_array_field(boost::uint8_t*& src, T* dest,
std::size_t count)
{
memcpy((boost::uint8_t*)dest, (boost::uint8_t*)(T*)src,
sizeof(T)*count);
src += sizeof(T) * count;
}
// Read 'num' items from the source stream to the dest location
template <typename T>
static inline void read_n(T& dest, std::istream& src,
std::streamsize const& num)
{
if (!src.good())
throw pdal::invalid_stream("pdal::Utils::read_n<T> input stream is "
"not readable");
char* p = as_buffer(dest);
src.read(p, num);
assert(check_stream_state(src));
}
template <typename T>
static inline void write_n(std::ostream& dest, T const& src,
std::streamsize const& num)
{
if (!dest.good())
throw std::runtime_error("pdal::Utils::write_n<T>: output stream "
"is not writable");
T& tmp = const_cast<T&>(src);
char const* p = as_bytes(tmp);
dest.rdbuf()->sputn(p, num);
assert(check_stream_state(dest));
}
// From http://stackoverflow.com/questions/485525/round-for-float-in-c
static inline double sround(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
static inline std::vector<boost::uint8_t>hex_string_to_binary(std::string const& source)
{
// Stolen from http://stackoverflow.com/questions/7363774/c-converting-binary-data-to-a-hex-string-and-back
static int nibbles[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15 };
std::vector<unsigned char> retval;
for (std::string::const_iterator it = source.begin(); it < source.end(); it += 2) {
unsigned char v = 0;
if (::isxdigit(*it))
v = (unsigned char)nibbles[::toupper(*it) - '0'] << 4;
if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
v += (unsigned char)nibbles[::toupper(*(it + 1)) - '0'];
retval.push_back(v);
}
return retval;
}
static inline void binary_to_hex_stream(unsigned char* source,
std::ostream& destination, int start, int end )
{
static char syms[] = "0123456789ABCDEF";
for (int i = start; i != end; i++)
destination << syms[((source[i] >> 4) & 0xf)] <<
syms[source[i] & 0xf];
}
static inline std::string binary_to_hex_string(
const std::vector<unsigned char>& source)
{
static char syms[] = "0123456789ABCDEF";
std::stringstream ss;
for (std::vector<unsigned char>::const_iterator it = source.begin();
it != source.end(); it++)
ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];
return ss.str();
}
template<typename Target, typename Source>
static inline Target saturation_cast(Source const& src)
{
try
{
return boost::numeric_cast<Target>(src);
}
catch (boost::numeric::negative_overflow const&)
{
return std::numeric_limits<Target>::min();
}
catch (boost::numeric::positive_overflow const&)
{
return std::numeric_limits<Target>::max();
}
}
static void* registerPlugin( void* stageFactoryPtr,
std::string const& filename,
std::string const& registerMethodName,
std::string const& versionMethodName);
static char* getenv(const char* env);
static std::string getenv(std::string const& name);
static int putenv(const char* env);
// aid to operator>> parsers
static void eatwhitespace(std::istream& s);
static void removeTrailingBlanks(std::string& s);
// aid to operator>> parsers
// if char found, eats it and returns true; otherwise, don't eat it and
// then return false
static bool eatcharacter(std::istream& s, char x);
static boost::uint32_t getStreamPrecision(double scale);
static boost::uint32_t safeconvert64to32(boost::uint64_t x64);
// Generates a random temporary filename
static std::string generate_filename();
static std::string generate_tempfile();
static void* getDLLSymbol(std::string const& library,
std::string const& name);
static std::string base64_encode(std::vector<uint8_t> const& bytes)
{ return base64_encode(bytes.data(), bytes.size()); }
static std::string base64_encode(const unsigned char *buf, size_t size);
static std::vector<boost::uint8_t> base64_decode(std::string const& input);
static FILE* portable_popen(const std::string& command,
const std::string& mode);
static int portable_pclose(FILE* fp);
static int run_shell_command(const std::string& cmd, std::string& output);
static std::string replaceAll(std::string result,
const std::string& replaceWhat,
const std::string& replaceWithWhat);
static void wordWrap(std::string const& inputString,
std::vector<std::string>& outputString,
unsigned int lineLength);
static std::string escapeJSON(const std::string &s);
static std::string demangle(const std::string& s);
template<typename T>
static std::string typeidName()
{ return Utils::demangle(typeid(T).name()); }
private:
template<typename T>
static inline char* as_buffer(T& data)
{
return static_cast<char*>(static_cast<void*>(&data));
}
template<typename T>
static inline char* as_buffer(T* data)
{
return static_cast<char*>(static_cast<void*>(data));
}
template<typename T>
static inline char const* as_bytes(T const& data)
{
return static_cast<char const*>(static_cast<void const*>(&data));
}
template<typename T>
static inline char const* as_bytes(T const* data)
{
return static_cast<char const*>(static_cast<void const*>(data));
}
template <typename C, typename T>
static inline bool check_stream_state(std::basic_ios<C, T>& srtm)
{
// Test stream state bits
if (srtm.eof())
throw std::out_of_range("end of file encountered");
else if (srtm.fail())
throw std::runtime_error("non-fatal I/O error occured");
else if (srtm.bad())
throw std::runtime_error("fatal I/O error occured");
return true;
}
};
} // namespace pdal
|
/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/pdal_internal.hpp>
#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <fstream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/numeric/conversion/cast.hpp>
namespace pdal
{
class PDAL_DLL Utils
{
public:
static void random_seed(unsigned int seed);
static double random(double minimum, double maximum);
static double uniform(const double& minimum=0.0f,
const double& maximum=1.0f, boost::uint32_t seed=0);
static double normal(const double& mean=0.0f, const double& sigma=1.0f,
boost::uint32_t seed=0);
// compares two values to within the datatype's epsilon
template<class T>
static bool compare_distance(const T& actual, const T& expected)
{
const T epsilon = std::numeric_limits<T>::epsilon();
return compare_approx<T>(actual, expected, epsilon);
}
// compares two values to within a given tolerance
// the value |tolerance| is compared to |actual - expected|
template<class T>
static bool compare_approx(const T& actual, const T& expected,
const T& tolerance)
{
double diff = std::abs((double)actual - (double)expected);
return diff <= std::abs((double) tolerance);
}
// Copy v into *t and increment dest by the sizeof v
template<class T>
static inline void write_field(boost::uint8_t*& dest, T v)
{
*(T*)(void*)dest = v;
dest += sizeof(T);
}
// Return a 'T' from a stream and increment src by the sizeof 'T'
template<class T>
static inline T read_field(boost::uint8_t*& src)
{
T tmp = *(T*)(void*)src;
src += sizeof(T);
return tmp;
}
// Copy data from dest to src and increment dest by the copied size.
template<class T>
static inline void read_array_field(boost::uint8_t*& src, T* dest,
std::size_t count)
{
memcpy((boost::uint8_t*)dest, (boost::uint8_t*)(T*)src,
sizeof(T)*count);
src += sizeof(T) * count;
}
// Read 'num' items from the source stream to the dest location
template <typename T>
static inline void read_n(T& dest, std::istream& src,
std::streamsize const& num)
{
if (!src.good())
throw pdal::invalid_stream("pdal::Utils::read_n<T> input stream is "
"not readable");
char* p = as_buffer(dest);
src.read(p, num);
assert(check_stream_state(src));
}
template <typename T>
static inline void write_n(std::ostream& dest, T const& src,
std::streamsize const& num)
{
if (!dest.good())
throw std::runtime_error("pdal::Utils::write_n<T>: output stream "
"is not writable");
T& tmp = const_cast<T&>(src);
char const* p = as_bytes(tmp);
dest.rdbuf()->sputn(p, num);
assert(check_stream_state(dest));
}
// From http://stackoverflow.com/questions/485525/round-for-float-in-c
static inline double sround(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
static inline std::vector<boost::uint8_t>hex_string_to_binary(
std::string const& source)
{
// Stolen from http://stackoverflow.com/questions/7363774/ ...
// c-converting-binary-data-to-a-hex-string-and-back
static int nibbles[] =
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15 };
std::vector<unsigned char> retval;
for (auto it = source.begin(); it < source.end(); it += 2) {
unsigned char v = 0;
if (::isxdigit(*it))
v = (unsigned char)nibbles[::toupper(*it) - '0'] << 4;
if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
v += (unsigned char)nibbles[::toupper(*(it + 1)) - '0'];
retval.push_back(v);
}
return retval;
}
static inline void binary_to_hex_stream(unsigned char* source,
std::ostream& destination, int start, int end )
{
static char syms[] = "0123456789ABCDEF";
for (int i = start; i != end; i++)
destination << syms[((source[i] >> 4) & 0xf)] <<
syms[source[i] & 0xf];
}
static inline std::string binary_to_hex_string(
const std::vector<unsigned char>& source)
{
static char syms[] = "0123456789ABCDEF";
std::stringstream ss;
for (std::vector<unsigned char>::const_iterator it = source.begin();
it != source.end(); it++)
ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];
return ss.str();
}
template<typename Target, typename Source>
static inline Target saturation_cast(Source const& src)
{
try
{
return boost::numeric_cast<Target>(src);
}
catch (boost::numeric::negative_overflow const&)
{
return std::numeric_limits<Target>::min();
}
catch (boost::numeric::positive_overflow const&)
{
return std::numeric_limits<Target>::max();
}
}
static void* registerPlugin( void* stageFactoryPtr,
std::string const& filename,
std::string const& registerMethodName,
std::string const& versionMethodName);
static char* getenv(const char* env);
static std::string getenv(std::string const& name);
static int putenv(const char* env);
// aid to operator>> parsers
static void eatwhitespace(std::istream& s);
static void removeTrailingBlanks(std::string& s);
// aid to operator>> parsers
// if char found, eats it and returns true; otherwise, don't eat it and
// then return false
static bool eatcharacter(std::istream& s, char x);
static boost::uint32_t getStreamPrecision(double scale);
static boost::uint32_t safeconvert64to32(boost::uint64_t x64);
// Generates a random temporary filename
static std::string generate_filename();
static std::string generate_tempfile();
static void* getDLLSymbol(std::string const& library,
std::string const& name);
static std::string base64_encode(std::vector<uint8_t> const& bytes)
{ return base64_encode(bytes.data(), bytes.size()); }
static std::string base64_encode(const unsigned char *buf, size_t size);
static std::vector<boost::uint8_t> base64_decode(std::string const& input);
static FILE* portable_popen(const std::string& command,
const std::string& mode);
static int portable_pclose(FILE* fp);
static int run_shell_command(const std::string& cmd, std::string& output);
static std::string replaceAll(std::string result,
const std::string& replaceWhat,
const std::string& replaceWithWhat);
static void wordWrap(std::string const& inputString,
std::vector<std::string>& outputString,
unsigned int lineLength);
static std::string escapeJSON(const std::string &s);
static std::string demangle(const std::string& s);
template<typename T>
static std::string typeidName()
{ return Utils::demangle(typeid(T).name()); }
struct RedirectCtx
{
std::ofstream *m_out;
std::streambuf *m_buf;
};
/// Redirect a stream to some file, by default /dev/null.
/// \param[in] out Stream to redirect.
/// \param[in] file Name of file where stream should be redirected.
/// \return Context for stream restoration (see restore()).
static RedirectCtx redirect(std::ostream& out,
const std::string& file = "/dev/null")
{
RedirectCtx ctx;
ctx.m_out = new std::ofstream(file);
ctx.m_buf = out.rdbuf();
out.rdbuf(ctx.m_out->rdbuf());
return ctx;
}
/// Restore a stream redirected with redirect().
/// \param[in] out Stream to be restored.
/// \param[in] ctx Context returned from corresponding redirect() call.
static void restore(std::ostream& out, RedirectCtx ctx)
{
out.rdbuf(ctx.m_buf);
ctx.m_out->close();
}
private:
template<typename T>
static inline char* as_buffer(T& data)
{
return static_cast<char*>(static_cast<void*>(&data));
}
template<typename T>
static inline char* as_buffer(T* data)
{
return static_cast<char*>(static_cast<void*>(data));
}
template<typename T>
static inline char const* as_bytes(T const& data)
{
return static_cast<char const*>(static_cast<void const*>(&data));
}
template<typename T>
static inline char const* as_bytes(T const* data)
{
return static_cast<char const*>(static_cast<void const*>(data));
}
template <typename C, typename T>
static inline bool check_stream_state(std::basic_ios<C, T>& srtm)
{
// Test stream state bits
if (srtm.eof())
throw std::out_of_range("end of file encountered");
else if (srtm.fail())
throw std::runtime_error("non-fatal I/O error occured");
else if (srtm.bad())
throw std::runtime_error("fatal I/O error occured");
return true;
}
};
} // namespace pdal
|
Add support for stream redirection/restoration.
|
Add support for stream redirection/restoration.
|
C++
|
bsd-3-clause
|
lucadelu/PDAL,DougFirErickson/PDAL,mtCarto/PDAL,DougFirErickson/PDAL,mpgerlek/PDAL-old,jwomeara/PDAL,jwomeara/PDAL,DougFirErickson/PDAL,radiantbluetechnologies/PDAL,boundlessgeo/PDAL,lucadelu/PDAL,DougFirErickson/PDAL,radiantbluetechnologies/PDAL,Sciumo/PDAL,mtCarto/PDAL,lucadelu/PDAL,jwomeara/PDAL,boundlessgeo/PDAL,mtCarto/PDAL,mpgerlek/PDAL-old,mpgerlek/PDAL-old,Sciumo/PDAL,jwomeara/PDAL,mpgerlek/PDAL-old,boundlessgeo/PDAL,lucadelu/PDAL,Sciumo/PDAL,radiantbluetechnologies/PDAL,mtCarto/PDAL,radiantbluetechnologies/PDAL,Sciumo/PDAL,boundlessgeo/PDAL
|
d824795400bf02da596151f629489650d81796b0
|
include/сomplex_t.hpp
|
include/сomplex_t.hpp
|
#include <iostream>
using namespace std;
class complex_t
{
private:
float a;
float b;
public:
Сomplex_t();
complex_t(double x, double y);
complex_t(const complex_t&cop);
double a_();
double b_();
complex_t operator * (const complex_t& c2) const;
complex_t operator / (const complex_t& c2) const;
complex_t operator += (const complex_t& c2);
complex_t operator -= (const complex_t& c2);
complex_t operator *= (const complex_t& c2);
complex_t operator /= (const complex_t& c2);
complex_t operator = (const complex_t& result);
bool operator == (const complex_t& c2) const;
friend istream& operator >> (istream&cin, complex_t& result);
friend ostream& operator << (ostream&cout, complex_t& result);
};
|
#include <iostream>
using namespace std;
class complex_t
{
private:
float a;
float b;
public:
сomplex_t();
complex_t(double x, double y);
complex_t(const complex_t&cop);
double a_();
double b_();
complex_t operator * (const complex_t& c2) const;
complex_t operator / (const complex_t& c2) const;
complex_t operator += (const complex_t& c2);
complex_t operator -= (const complex_t& c2);
complex_t operator *= (const complex_t& c2);
complex_t operator /= (const complex_t& c2);
complex_t operator = (const complex_t& result);
bool operator == (const complex_t& c2) const;
friend istream& operator >> (istream&cin, complex_t& result);
friend ostream& operator << (ostream&cout, complex_t& result);
};
|
Update сomplex_t.hpp
|
Update сomplex_t.hpp
|
C++
|
mit
|
Ivanopulopulo/Complex
|
2bd5a1d75c3c387f014b4ed0a569b74cd0bcddff
|
examples/auth/src/auth.cpp
|
examples/auth/src/auth.cpp
|
#if defined(__WIN32__) || defined(_WIN32)
#include <rpc.h>
#else
#include <unistd.h>
#include <fcntl.h>
#endif
#include <iostream>
#include <orm/MetaDataSingleton.h>
#include "md5.h"
#include "logger.h"
#include "micro_http.h"
#include "domain/User.h"
#include "domain/LoginSession.h"
using namespace std;
using namespace Domain;
#define INIT_SESSION \
Yb::Logger::Ptr ormlog = g_log->new_logger("orm"); \
Yb::Engine engine(Yb::Engine::MANUAL); \
Yb::Session session(Yb::theMetaData::instance(), &engine); \
engine.get_connect()->set_logger(ormlog.get()); \
engine.get_connect()->set_echo(true);
Yb::LongInt
get_random()
{
Yb::LongInt buf;
#if defined(__WIN32__) || defined(_WIN32)
UUID new_uuid;
UuidCreate(&new_uuid);
buf = new_uuid.Data1;
buf <<= 32;
Yb::LongInt buf2 = (new_uuid.Data2 << 16) | new_uuid.Data3;
buf += buf2;
#else
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
throw std::runtime_error("can't open /dev/urandom");
if (read(fd, &buf, sizeof(buf)) != sizeof(buf)) {
close(fd);
throw std::runtime_error("can't read from /dev/urandom");
}
close(fd);
#endif
return buf;
}
Yb::LongInt
get_checked_session_by_token(Yb::Session &session, StringMap ¶ms, int admin_flag=0)
{
LoginSession::ResultSet rs = Yb::query<LoginSession>(
session, Yb::filter_eq(_T("TOKEN"), params["token"]));
LoginSession::ResultSet::iterator q = rs.begin(), qend=rs.end();
if (q == qend)
return -1;
if (admin_flag) {
if (q->get_user().get_status() != 0)
return -1;
}
if (Yb::now() >= q->get_end_session())
return -1;
return q->get_id();
}
string
check(StringMap ¶ms)
{
INIT_SESSION;
return get_checked_session_by_token(session, params) == -1? BAD_RESP: OK_RESP;
}
string
md5_hash(const string &str)
{
MD5_CTX mdContext;
MD5Init(&mdContext);
MD5Update(&mdContext, (unsigned char *)str.c_str(), str.size());
MD5Final(&mdContext);
string rez;
char omg[3];
for (int i = 0; i < 16; ++i) {
sprintf(omg, "%02x", mdContext.digest[i]);
rez.append(omg, 2);
}
return rez;
}
string
registration(StringMap ¶ms)
{
INIT_SESSION;
if (-1 == get_checked_session_by_token(session, params, 1))
return BAD_RESP;
User::ResultSet rs = Yb::query<User>(
session, Yb::filter_eq(_T("NAME"), params["login"]));
User::ResultSet::iterator q = rs.begin(), qend = rs.end();
if (q != qend)
return BAD_RESP;
User user(session);
user.set_name(params["login"]);
user.set_pass(md5_hash(params["pass"]));
user.set_status(boost::lexical_cast<int>(params["status"]));
session.flush();
engine.commit();
return OK_RESP;
}
Yb::LongInt
get_checked_user_by_creds(Yb::Session &session, StringMap ¶ms)
{
User::ResultSet rs = Yb::query<User>(
session, Yb::filter_eq(_T("NAME"), params["login"]));
User::ResultSet::iterator q = rs.begin(), qend = rs.end();
if (q == qend)
return -1;
if (q->get_pass() != md5_hash(params["pass"]))
return -1;
return q->get_id();
}
string
login(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt uid = get_checked_user_by_creds(session, params);
if (-1 == uid)
return BAD_RESP;
User user(session, uid);
while (user.get_login_sessions().begin() != user.get_login_sessions().end())
user.get_login_sessions().begin()->delete_object();
LoginSession login_session(session);
login_session.set_user(user);
Yb::LongInt token = get_random();
login_session.set_token(boost::lexical_cast<string>(token));
login_session.set_end_session(Yb::now() + boost::posix_time::hours(11));
session.flush();
engine.commit();
stringstream ss;
ss << "<token>" << token << "</token>";
return ss.str();
}
string
session_info(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt sid = get_checked_session_by_token(session, params);
if (-1 == sid)
return BAD_RESP;
LoginSession ls(session, sid);
return ls.xmlize(1)->serialize();
}
string
logout(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt sid = get_checked_session_by_token(session, params);
if (-1 == sid)
return BAD_RESP;
LoginSession ls(session, sid);
ls.delete_object();
session.flush();
engine.commit();
return OK_RESP;
}
int
main()
{
try {
const char *log_fname = "log.txt"; // TODO: read from config
g_log.reset(new Log(log_fname));
g_log->info("start log");
}
catch (const std::exception &ex) {
std::cerr << "exception: " << ex.what() << "\n";
std::cerr << "Can't open log file! Stop!\n";
return 1;
}
try {
Yb::init_default_meta();
int port = 9090; // TODO: read from config
HttpHandlerMap handlers;
handlers["/session_info"] = session_info;
handlers["/registration"] = registration;
handlers["/check"] = check;
handlers["/login"] = login;
handlers["/logout"] = logout;
HttpServer server(port, handlers);
server.serve();
}
catch (const std::exception &ex) {
g_log->error(string("exception: ") + ex.what());
return 1;
}
return 0;
}
// vim:ts=4:sts=4:sw=4:et:
|
#if defined(__WIN32__) || defined(_WIN32)
#include <rpc.h>
#else
#include <unistd.h>
#include <fcntl.h>
#endif
#include <iostream>
#include <orm/MetaDataSingleton.h>
#include "md5.h"
#include "logger.h"
#include "micro_http.h"
#include "domain/User.h"
#include "domain/LoginSession.h"
using namespace std;
using namespace Domain;
#define INIT_SESSION \
Yb::Logger::Ptr ormlog = g_log->new_logger("orm"); \
Yb::Engine engine(Yb::Engine::MANUAL); \
Yb::Session session(Yb::theMetaData::instance(), &engine); \
engine.get_connect()->set_logger(ormlog.get()); \
engine.get_connect()->set_echo(true);
Yb::LongInt
get_random()
{
Yb::LongInt buf;
#if defined(__WIN32__) || defined(_WIN32)
UUID new_uuid;
UuidCreate(&new_uuid);
buf = new_uuid.Data1;
buf <<= 32;
Yb::LongInt buf2 = (new_uuid.Data2 << 16) | new_uuid.Data3;
buf += buf2;
#else
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
throw std::runtime_error("can't open /dev/urandom");
if (read(fd, &buf, sizeof(buf)) != sizeof(buf)) {
close(fd);
throw std::runtime_error("can't read from /dev/urandom");
}
close(fd);
#endif
return buf;
}
Yb::LongInt
get_checked_session_by_token(Yb::Session &session, StringMap ¶ms, int admin_flag=0)
{
LoginSession::ResultSet rs = Yb::query<LoginSession>(
session, Yb::filter_eq(_T("TOKEN"), params["token"]));
LoginSession::ResultSet::iterator q = rs.begin(), qend=rs.end();
if (q == qend)
return -1;
if (admin_flag) {
if (q->get_user().get_status() != 0)
return -1;
}
if (Yb::now() >= q->get_end_session())
return -1;
return q->get_id();
}
string
check(StringMap ¶ms)
{
INIT_SESSION;
return get_checked_session_by_token(session, params) == -1? BAD_RESP: OK_RESP;
}
string
md5_hash(const string &str)
{
MD5_CTX mdContext;
MD5Init(&mdContext);
MD5Update(&mdContext, (unsigned char *)str.c_str(), str.size());
MD5Final(&mdContext);
string rez;
char omg[3];
for (int i = 0; i < 16; ++i) {
sprintf(omg, "%02x", mdContext.digest[i]);
rez.append(omg, 2);
}
return rez;
}
string
registration(StringMap ¶ms)
{
INIT_SESSION;
User::ResultSet all = Yb::query<User>(
session, Yb::Filter(_T("1=1"))); // query all
User::ResultSet::iterator p = all.begin(), pend = all.end();
if (p != pend) {
// when user table is empty it is allowed to create the first user
// w/o password check, otherwise we should check permissions
if (-1 == get_checked_session_by_token(session, params, 1))
return BAD_RESP;
}
User::ResultSet rs = Yb::query<User>(
session, Yb::filter_eq(_T("NAME"), params["login"]));
User::ResultSet::iterator q = rs.begin(), qend = rs.end();
if (q != qend)
return BAD_RESP;
User user(session);
user.set_name(params["login"]);
user.set_pass(md5_hash(params["pass"]));
user.set_status(boost::lexical_cast<int>(params["status"]));
session.flush();
engine.commit();
return OK_RESP;
}
Yb::LongInt
get_checked_user_by_creds(Yb::Session &session, StringMap ¶ms)
{
User::ResultSet rs = Yb::query<User>(
session, Yb::filter_eq(_T("NAME"), params["login"]));
User::ResultSet::iterator q = rs.begin(), qend = rs.end();
if (q == qend)
return -1;
if (q->get_pass() != md5_hash(params["pass"]))
return -1;
return q->get_id();
}
string
login(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt uid = get_checked_user_by_creds(session, params);
if (-1 == uid)
return BAD_RESP;
User user(session, uid);
while (user.get_login_sessions().begin() != user.get_login_sessions().end())
user.get_login_sessions().begin()->delete_object();
LoginSession login_session(session);
login_session.set_user(user);
Yb::LongInt token = get_random();
login_session.set_token(boost::lexical_cast<string>(token));
login_session.set_end_session(Yb::now() + boost::posix_time::hours(11));
session.flush();
engine.commit();
stringstream ss;
ss << "<token>" << token << "</token>";
return ss.str();
}
string
session_info(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt sid = get_checked_session_by_token(session, params);
if (-1 == sid)
return BAD_RESP;
LoginSession ls(session, sid);
return ls.xmlize(1)->serialize();
}
string
logout(StringMap ¶ms)
{
INIT_SESSION;
Yb::LongInt sid = get_checked_session_by_token(session, params);
if (-1 == sid)
return BAD_RESP;
LoginSession ls(session, sid);
ls.delete_object();
session.flush();
engine.commit();
return OK_RESP;
}
int
main()
{
try {
const char *log_fname = "log.txt"; // TODO: read from config
g_log.reset(new Log(log_fname));
g_log->info("start log");
}
catch (const std::exception &ex) {
std::cerr << "exception: " << ex.what() << "\n";
std::cerr << "Can't open log file! Stop!\n";
return 1;
}
try {
Yb::init_default_meta();
int port = 9090; // TODO: read from config
HttpHandlerMap handlers;
handlers["/session_info"] = session_info;
handlers["/registration"] = registration;
handlers["/check"] = check;
handlers["/login"] = login;
handlers["/logout"] = logout;
HttpServer server(port, handlers);
server.serve();
}
catch (const std::exception &ex) {
g_log->error(string("exception: ") + ex.what());
return 1;
}
return 0;
}
// vim:ts=4:sts=4:sw=4:et:
|
Allow to register the first user via HTTP
|
Allow to register the first user via HTTP
git-svn-id: a972155c8e22ef3cf1b5c433ca9ba368ece90725@95 6e3d5a94-014d-4e71-8e65-48e4780539f1
|
C++
|
mit
|
kamaroly/yb-orm,kamaroly/yb-orm,kamaroly/yb-orm,kamaroly/yb-orm
|
568ce905d5ad8866d5396e690f596549fa89c8a6
|
Common/r_functionwhitelist.cpp
|
Common/r_functionwhitelist.cpp
|
#include "r_functionwhitelist.h"
#include "stringutils.h"
//The following functions (and keywords that can be followed by a '(') will be allowed in user-entered R-code, such as filters or computed columns. This is for security because otherwise JASP-files could become a vector of attack and that doesn't refer to an R-datatype.
const std::set<std::string> R_FunctionWhiteList::functionWhiteList {
"AIC",
"Arg",
"Conj",
"Im",
"Mod",
"NCOL",
"Re",
"abs",
"acos",
"aggregate",
"anova",
"aov",
"apply",
"approx",
"array",
"as.Date",
"as.POSIXct",
"as.array",
"as.character",
"as.complex",
"as.data.frame",
"as.logical",
"as.numeric",
"as.factor",
"as.list",
"as.integer",
"asin",
"atan",
"atanh",
"atan2",
"attr",
"attributes",
"binom.test",
"by",
"c",
"cat",
"cbind",
"choose",
"class",
"coef",
"colMeans",
"colSums",
"colsum",
"convolve",
"cor",
"cos",
"cummax",
"cummin",
"cumprod",
"cumsum",
"cut",
"data.frame",
"density",
"deviance",
"df.residual",
"diag",
"diff",
"dim",
"dimnames",
"exp",
"expand.grid",
"factor",
"fft",
"filter",
"fitted",
"fishZ",
"for",
"format",
"function",
"gl",
"glm",
"grep",
"gsub",
"if",
"ifelse",
"ifElse",
"intersect",
"invFishZ",
"is.array",
"is.character",
"is.complex",
"is.data.frame",
"is.element",
"is.logical",
"is.na",
"is.null",
"is.numeric",
"lag",
"lapply",
"length",
"library",
"list",
"local",
"lm",
"loess",
"log",
"log10",
"logLik",
"ls",
"ls.srt",
"match",
"matrix",
"max",
"mean",
"median",
"merge",
"methods",
"min",
"mvfft",
"na.fail",
"na.omit",
"nchar",
"ncol",
"nlm",
"nls",
"nrow",
"optim",
"pairwise.t.test",
"paste",
"paste0",
"pmatch",
"pmax",
"pmin",
"power.t.test",
"predict",
"print",
"prod",
"prop.table",
"prop.test",
"quantile",
"range",
"rank",
"rbeta",
"rbind",
"rbinom",
"rcauchy",
"rchisq",
"rep",
"replicate",
"reshape",
"residuals",
"return",
"rev",
"rexp",
"rf",
"rgamma",
"rgeom",
"rhyper",
"rlnorm",
"rlogis",
"rnbinom",
"rnorm",
"round",
"rowMeans",
"rowSums",
"rowsum",
"rpois",
"rt",
"runif",
"rweibull",
"rwilcox",
"sample",
"scale",
"sd",
"seq",
"setdiff",
"setequal",
"sin",
"solve",
"sort",
"spline",
"sqrt",
"stack",
"str",
"strsplit",
"subset",
"substr",
"sum",
"summary",
"t",
"t.test",
"table",
"tan",
"tanh",
"tapply",
"tolower",
"toString",
"toupper",
"trimws",
"unclass",
"union",
"unique",
"unstack",
"var",
"weighted.mean",
"which",
"which.max",
"which.min",
"xtabs",
".setColumnDataAsScale", ".setColumnDataAsOrdinal", ".setColumnDataAsNominal", ".setColumnDataAsNominalText", "function", "stop",
"normalDist", "tDist", "chiSqDist", "fDist", "binomDist", "negBinomDist", "geomDist", "poisDist", "integerDist", "betaDist", "unifDist", "gammaDist", "expDist", "logNormDist", "weibullDist",
"replaceNA",
//Some distribution related stuff:
"dbeta", "pbeta", "qbeta", "rbeta",
"dbinom", "pbinom", "qbinom", "rbinom",
"dcauchy", "pcauchy", "qcauchy", "rcauchy",
"dchisq", "pchisq", "qchisq", "rchisq",
"dexp", "pexp", "qexp", "rexp",
"df", "pf", "qf", "rf",
"dgamma", "pgamma", "qgamma", "rgamma",
"dgeom", "pgeom", "qgeom", "rgeom",
"dhyper", "phyper", "qhyper", "rhyper",
"dlnorm", "plnorm", "qlnorm", "rlnorm",
"dmultinom", "pmultinom", "qmultinom", "rmultinom",
"dnbinom", "pnbinom", "qnbinom", "rnbinom",
"dnorm", "pnorm", "qnorm", "rnorm",
"dpois", "ppois", "qpois", "rpois",
"dt", "pt", "qt", "rt",
"dunif", "punif", "qunif", "runif",
"dweibull", "pweibull", "qweibull", "rweibull",
"dsignrank", "psignrank", "qsignrank", "rsignrank",
"zScores",
"hasSubstring",
"pbirthday",
"ptukey",
"dwilcox",
"switch"
#ifdef JASP_DEBUG
,"Sys.sleep", ".crashPlease", "stringi::stri_enc_mark", "stringi::stri_enc_toutf8", "Encoding"
#endif
};
std::string R_FunctionWhiteList::returnOrderedWhiteList()
{
std::stringstream out;
for(auto & s : functionWhiteList)
out << "\"" << s << "\"," << std::endl;
out << std::flush;
return out.str();
}
const std::string R_FunctionWhiteList::functionStartDelimit("(?:[;\\s\\(\"\\[\\+\\-\\=\\*\\%\\/\\{\\|&!]|^)"); //These should be all possible non-funtion-name-characters that could be right in front of any function-name in R.
const std::string R_FunctionWhiteList::functionNameStart("(?:\\.?[[:alpha:]])");
const std::string R_FunctionWhiteList::functionNameBody("(?:\\w|\\.|::)+");
const std::regex R_FunctionWhiteList::functionNameMatcher(functionStartDelimit + "(" + functionNameStart + functionNameBody + ")(?=[\\t \\r]*\\()");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctions(std::string const & script)
{
std::set<std::string> blackListedFunctionsFound;
auto foundFunctionsBegin = std::sregex_iterator(script.begin(), script.end(), functionNameMatcher);
auto foundFunctionsEnd = std::sregex_iterator();
for(auto foundFunctionIter = foundFunctionsBegin; foundFunctionIter != foundFunctionsEnd; foundFunctionIter++ )
{
std::string foundFunction((*foundFunctionIter)[1].str());
bool whiteListed = functionWhiteList.count(foundFunction) > 0;
if(!whiteListed && blackListedFunctionsFound.count(foundFunction) == 0)
blackListedFunctionsFound.insert(foundFunction);
}
return blackListedFunctionsFound;
}
const std::string R_FunctionWhiteList::operatorsR("`(?:\\+|-|\\*|/|%(?:/|\\*|in)?%|\\^|<=?|>=?|==?|!=?|<?<-|->>?|\\|\\|?|&&?|:|\\$)`");
const std::regex R_FunctionWhiteList::assignmentWhiteListedRightMatcher( "(" + functionNameStart + functionNameBody + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentWhiteListedLeftMatcher( "(?:->>?)\\s*(" + functionNameStart + functionNameBody + ")");
const std::regex R_FunctionWhiteList::assignmentOperatorRightMatcher( "(" + operatorsR + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentOperatorLeftMatcher( "(?:->>?)\\s*(" + operatorsR + ")");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctionsAliases(std::string const & script)
{
//Log::log() << "findIllegalFunctionsAliases with " << script << std::endl;
std::set<std::string> illegalAliasesFound;
auto aliasSearcher = [&illegalAliasesFound, &script](std::regex aliasAssignmentMatcher, bool (*lambdaMatchChecker)(std::string) )
{
auto foundAliasesBegin = std::sregex_iterator(script.begin(), script.end(), aliasAssignmentMatcher);
auto foundAliasesEnd = std::sregex_iterator();
for(auto foundAliasesIter = foundAliasesBegin; foundAliasesIter != foundAliasesEnd; foundAliasesIter++ )
{
std::string foundAlias((*foundAliasesIter)[1].str());
bool allowed = (*lambdaMatchChecker)(foundAlias);
//Log::log() << "I found alias assignment: " << foundAlias << " which is " << (allowed ? "allowed" : "not allowed") << ".." << std::endl;
if(!allowed)
illegalAliasesFound.insert(foundAlias);
}
};
aliasSearcher(assignmentOperatorLeftMatcher, [](std::string alias) { return false; }); //operators are never allowed
aliasSearcher(assignmentOperatorRightMatcher, [](std::string alias) { return false; });
aliasSearcher(assignmentWhiteListedLeftMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; }); //only allowed when the token being assigned to is not in whitelist
aliasSearcher(assignmentWhiteListedRightMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; });
//Log::log() << std::flush;
return illegalAliasesFound;
}
void R_FunctionWhiteList::scriptIsSafe(const std::string &script)
{
std::string commentFree = stringUtils::stripRComments(script);
static std::string errorMsg;
std::set<std::string> blackListedFunctions = findIllegalFunctions(commentFree);
if(blackListedFunctions.size() > 0)
{
bool moreThanOne = blackListedFunctions.size() > 1;
std::stringstream ssm;
ssm << "Non-whitelisted function" << (moreThanOne ? "s" : "") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & black : blackListedFunctions)
ssm << black << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
std::set<std::string> illegalAliasesFound = findIllegalFunctionsAliases(commentFree);
if(illegalAliasesFound.size() > 0)
{
bool moreThanOne = illegalAliasesFound.size() > 1;
std::stringstream ssm;
ssm << "Illegal assignment to " << (moreThanOne ? "operators or whitelisted functions" : "an operator or whitelisted function") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & alias : illegalAliasesFound)
ssm << alias << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
}
|
#include "r_functionwhitelist.h"
#include "stringutils.h"
//The following functions (and keywords that can be followed by a '(') will be allowed in user-entered R-code, such as filters or computed columns. This is for security because otherwise JASP-files could become a vector of attack and that doesn't refer to an R-datatype.
const std::set<std::string> R_FunctionWhiteList::functionWhiteList {
"AIC",
"Arg",
"Conj",
"Im",
"Mod",
"NCOL",
"Re",
"abs",
"acos",
"aggregate",
"anova",
"aov",
"apply",
"approx",
"array",
"as.Date",
"as.POSIXct",
"as.array",
"as.character",
"as.complex",
"as.data.frame",
"as.logical",
"as.numeric",
"as.factor",
"as.list",
"as.integer",
"asin",
"atan",
"atanh",
"atan2",
"attr",
"attributes",
"binom.test",
"by",
"c",
"cat",
"cbind",
"choose",
"class",
"coef",
"colMeans",
"colSums",
"colsum",
"convolve",
"cor",
"cos",
"cummax",
"cummin",
"cumprod",
"cumsum",
"cut",
"data.frame",
"density",
"deviance",
"df.residual",
"diag",
"diff",
"dim",
"dimnames",
"exp",
"expand.grid",
"factor",
"fft",
"filter",
"fitted",
"fishZ",
"for",
"format",
"function",
"gl",
"glm",
"gregexpr",
"grep",
"grepl",
"gsub",
"if",
"ifelse",
"ifElse",
"intersect",
"invFishZ",
"is.array",
"is.character",
"is.complex",
"is.data.frame",
"is.element",
"is.logical",
"is.na",
"is.null",
"is.numeric",
"lag",
"lapply",
"length",
"library",
"list",
"local",
"lm",
"loess",
"log",
"log10",
"logLik",
"ls",
"ls.srt",
"match",
"matrix",
"max",
"mean",
"median",
"merge",
"methods",
"min",
"mvfft",
"na.fail",
"na.omit",
"nchar",
"ncol",
"nlm",
"nls",
"nrow",
"optim",
"pairwise.t.test",
"paste",
"paste0",
"pmatch",
"pmax",
"pmin",
"power.t.test",
"predict",
"print",
"prod",
"prop.table",
"prop.test",
"quantile",
"range",
"rank",
"rbeta",
"rbind",
"rbinom",
"rcauchy",
"rchisq",
"regexec",
"regexpr",
"rep",
"replicate",
"reshape",
"residuals",
"return",
"rev",
"rexp",
"rf",
"rgamma",
"rgeom",
"rhyper",
"rlnorm",
"rlogis",
"rnbinom",
"rnorm",
"round",
"rowMeans",
"rowSums",
"rowsum",
"rpois",
"rt",
"runif",
"rweibull",
"rwilcox",
"sample",
"scale",
"sd",
"seq",
"setdiff",
"setequal",
"sin",
"solve",
"sort",
"spline",
"sqrt",
"stack",
"str",
"strsplit",
"sub",
"subset",
"substr",
"sum",
"summary",
"t",
"t.test",
"table",
"tan",
"tanh",
"tapply",
"tolower",
"toString",
"toupper",
"trimws",
"unclass",
"union",
"unique",
"unstack",
"var",
"weighted.mean",
"which",
"which.max",
"which.min",
"xtabs",
".setColumnDataAsScale", ".setColumnDataAsOrdinal", ".setColumnDataAsNominal", ".setColumnDataAsNominalText", "function", "stop",
"normalDist", "tDist", "chiSqDist", "fDist", "binomDist", "negBinomDist", "geomDist", "poisDist", "integerDist", "betaDist", "unifDist", "gammaDist", "expDist", "logNormDist", "weibullDist",
"replaceNA",
//Some distribution related stuff:
"dbeta", "pbeta", "qbeta", "rbeta",
"dbinom", "pbinom", "qbinom", "rbinom",
"dcauchy", "pcauchy", "qcauchy", "rcauchy",
"dchisq", "pchisq", "qchisq", "rchisq",
"dexp", "pexp", "qexp", "rexp",
"df", "pf", "qf", "rf",
"dgamma", "pgamma", "qgamma", "rgamma",
"dgeom", "pgeom", "qgeom", "rgeom",
"dhyper", "phyper", "qhyper", "rhyper",
"dlnorm", "plnorm", "qlnorm", "rlnorm",
"dmultinom", "pmultinom", "qmultinom", "rmultinom",
"dnbinom", "pnbinom", "qnbinom", "rnbinom",
"dnorm", "pnorm", "qnorm", "rnorm",
"dpois", "ppois", "qpois", "rpois",
"dt", "pt", "qt", "rt",
"dunif", "punif", "qunif", "runif",
"dweibull", "pweibull", "qweibull", "rweibull",
"dsignrank", "psignrank", "qsignrank", "rsignrank",
"zScores",
"hasSubstring",
"pbirthday",
"ptukey",
"dwilcox",
"switch"
#ifdef JASP_DEBUG
,"Sys.sleep", ".crashPlease", "stringi::stri_enc_mark", "stringi::stri_enc_toutf8", "Encoding"
#endif
};
std::string R_FunctionWhiteList::returnOrderedWhiteList()
{
std::stringstream out;
for(auto & s : functionWhiteList)
out << "\"" << s << "\"," << std::endl;
out << std::flush;
return out.str();
}
const std::string R_FunctionWhiteList::functionStartDelimit("(?:[;\\s\\(\"\\[\\+\\-\\=\\*\\%\\/\\{\\|&!]|^)"); //These should be all possible non-funtion-name-characters that could be right in front of any function-name in R.
const std::string R_FunctionWhiteList::functionNameStart("(?:\\.?[[:alpha:]])");
const std::string R_FunctionWhiteList::functionNameBody("(?:\\w|\\.|::)+");
const std::regex R_FunctionWhiteList::functionNameMatcher(functionStartDelimit + "(" + functionNameStart + functionNameBody + ")(?=[\\t \\r]*\\()");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctions(std::string const & script)
{
std::set<std::string> blackListedFunctionsFound;
auto foundFunctionsBegin = std::sregex_iterator(script.begin(), script.end(), functionNameMatcher);
auto foundFunctionsEnd = std::sregex_iterator();
for(auto foundFunctionIter = foundFunctionsBegin; foundFunctionIter != foundFunctionsEnd; foundFunctionIter++ )
{
std::string foundFunction((*foundFunctionIter)[1].str());
bool whiteListed = functionWhiteList.count(foundFunction) > 0;
if(!whiteListed && blackListedFunctionsFound.count(foundFunction) == 0)
blackListedFunctionsFound.insert(foundFunction);
}
return blackListedFunctionsFound;
}
const std::string R_FunctionWhiteList::operatorsR("`(?:\\+|-|\\*|/|%(?:/|\\*|in)?%|\\^|<=?|>=?|==?|!=?|<?<-|->>?|\\|\\|?|&&?|:|\\$)`");
const std::regex R_FunctionWhiteList::assignmentWhiteListedRightMatcher( "(" + functionNameStart + functionNameBody + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentWhiteListedLeftMatcher( "(?:->>?)\\s*(" + functionNameStart + functionNameBody + ")");
const std::regex R_FunctionWhiteList::assignmentOperatorRightMatcher( "(" + operatorsR + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentOperatorLeftMatcher( "(?:->>?)\\s*(" + operatorsR + ")");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctionsAliases(std::string const & script)
{
//Log::log() << "findIllegalFunctionsAliases with " << script << std::endl;
std::set<std::string> illegalAliasesFound;
auto aliasSearcher = [&illegalAliasesFound, &script](std::regex aliasAssignmentMatcher, bool (*lambdaMatchChecker)(std::string) )
{
auto foundAliasesBegin = std::sregex_iterator(script.begin(), script.end(), aliasAssignmentMatcher);
auto foundAliasesEnd = std::sregex_iterator();
for(auto foundAliasesIter = foundAliasesBegin; foundAliasesIter != foundAliasesEnd; foundAliasesIter++ )
{
std::string foundAlias((*foundAliasesIter)[1].str());
bool allowed = (*lambdaMatchChecker)(foundAlias);
//Log::log() << "I found alias assignment: " << foundAlias << " which is " << (allowed ? "allowed" : "not allowed") << ".." << std::endl;
if(!allowed)
illegalAliasesFound.insert(foundAlias);
}
};
aliasSearcher(assignmentOperatorLeftMatcher, [](std::string alias) { return false; }); //operators are never allowed
aliasSearcher(assignmentOperatorRightMatcher, [](std::string alias) { return false; });
aliasSearcher(assignmentWhiteListedLeftMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; }); //only allowed when the token being assigned to is not in whitelist
aliasSearcher(assignmentWhiteListedRightMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; });
//Log::log() << std::flush;
return illegalAliasesFound;
}
void R_FunctionWhiteList::scriptIsSafe(const std::string &script)
{
std::string commentFree = stringUtils::stripRComments(script);
static std::string errorMsg;
std::set<std::string> blackListedFunctions = findIllegalFunctions(commentFree);
if(blackListedFunctions.size() > 0)
{
bool moreThanOne = blackListedFunctions.size() > 1;
std::stringstream ssm;
ssm << "Non-whitelisted function" << (moreThanOne ? "s" : "") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & black : blackListedFunctions)
ssm << black << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
std::set<std::string> illegalAliasesFound = findIllegalFunctionsAliases(commentFree);
if(illegalAliasesFound.size() > 0)
{
bool moreThanOne = illegalAliasesFound.size() > 1;
std::stringstream ssm;
ssm << "Illegal assignment to " << (moreThanOne ? "operators or whitelisted functions" : "an operator or whitelisted function") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & alias : illegalAliasesFound)
ssm << alias << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
}
|
add functions for pattern matching and replacement to whitelist (grepl, sub, regexpr)
|
add functions for pattern matching and replacement to whitelist (grepl, sub, regexpr)
|
C++
|
agpl-3.0
|
AlexanderLyNL/jasp-desktop,TimKDJ/jasp-desktop,jasp-stats/jasp-desktop,boutinb/jasp-desktop,TimKDJ/jasp-desktop,TimKDJ/jasp-desktop,TimKDJ/jasp-desktop,boutinb/jasp-desktop,boutinb/jasp-desktop,AlexanderLyNL/jasp-desktop,jasp-stats/jasp-desktop,jasp-stats/jasp-desktop,boutinb/jasp-desktop,TimKDJ/jasp-desktop,boutinb/jasp-desktop,jasp-stats/jasp-desktop,jasp-stats/jasp-desktop,jasp-stats/jasp-desktop,jasp-stats/jasp-desktop,AlexanderLyNL/jasp-desktop,AlexanderLyNL/jasp-desktop,boutinb/jasp-desktop,AlexanderLyNL/jasp-desktop,TimKDJ/jasp-desktop,AlexanderLyNL/jasp-desktop,AlexanderLyNL/jasp-desktop,TimKDJ/jasp-desktop,AlexanderLyNL/jasp-desktop,boutinb/jasp-desktop,jasp-stats/jasp-desktop,boutinb/jasp-desktop,TimKDJ/jasp-desktop
|
bccb6f158bc1704f2dc85474128df6dd87d8f4c9
|
Modules/IO/IOGDAL/src/otbDEMHandler.cxx
|
Modules/IO/IOGDAL/src/otbDEMHandler.cxx
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbDEMHandler.h"
#include "otbGDALDriverManagerWrapper.h"
#include "boost/filesystem.hpp"
#include <boost/range/iterator_range.hpp>
#include "gdal_utils.h"
//TODO C++ 17 : use std::optional instead
#include <boost/optional.hpp>
// TODO : RemoveOSSIM
#include <otbOssimDEMHandler.h>
#include <mutex>
#include "ogr_spatialref.h"
namespace otb {
namespace DEMDetails {
// Adapted from boost filesystem documentation : https://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/reference.html
std::vector<std::string> GetFilesInDirectory(const std::string & directoryPath)
{
std::vector<std::string> fileList;
if ( !boost::filesystem::exists( directoryPath) )
{
return fileList;
}
else if (!boost::filesystem::is_directory(directoryPath))
{
fileList.push_back(directoryPath);
return fileList;
}
// End iterator : default construction yields past-the-end
for ( const auto & item : boost::make_iterator_range(boost::filesystem::directory_iterator(directoryPath), {}) )
{
if ( boost::filesystem::is_directory(item.status()) )
{
auto subDirList = GetFilesInDirectory(item.path().string());
fileList.insert(fileList.end(), subDirList.begin(), subDirList.end());
}
else
{
fileList.push_back(item.path().string());
}
}
return fileList;
}
std::mutex demMutex;
boost::optional<double> GetDEMValue(double lon, double lat, GDALDataset& ds)
{
const std::lock_guard<std::mutex> lock(demMutex);
#if GDAL_VERSION_NUM >= 3000000
auto srs = ds.GetSpatialRef();
#else
auto projRef = ds.GetProjectionRef();
std::unique_ptr<OGRSpatialReference> srsUniquePtr;
OGRSpatialReference* srs = nullptr;
// GetProjectionRef() returns an empty non null string if no projection is available
if (strlen(projRef) != 0 )
{
srsUniquePtr = std::make_unique<OGRSpatialReference>(ds.GetProjectionRef());
srs = srsUniquePtr.get();
}
#endif
auto wgs84Srs = OGRSpatialReference::GetWGS84SRS();
// Convert input lon lat into the coordinates defined by the dataset if needed.
if (srs && !srs->IsSame(wgs84Srs))
{
auto poCT = std::unique_ptr<OGRCoordinateTransformation>
(OGRCreateCoordinateTransformation(wgs84Srs, srs));
if (poCT && !poCT->Transform( 1, &lon, &lat ) )
{
return boost::none;
}
}
double geoTransform[6];
ds.GetGeoTransform(geoTransform);
auto x = (lon - geoTransform[0]) / geoTransform[1] - 0.5;
auto y = (lat - geoTransform[3]) / geoTransform[5] - 0.5;
if (x < 0 || y < 0 || x > ds.GetRasterXSize() || y > ds.GetRasterYSize())
{
return boost::none;
}
auto x_int = static_cast<int>(x);
auto y_int = static_cast<int>(y);
auto deltaX = x - x_int;
auto deltaY = y - y_int;
if (x < 0 || y < 0 || x+1 > ds.GetRasterXSize() || y+1 > ds.GetRasterYSize())
{
return boost::none;
}
// Bilinear interpolation.
double elevData[4];
auto err = ds.GetRasterBand(1)->RasterIO( GF_Read, x_int, y_int, 2, 2,
elevData, 2, 2, GDT_Float64,
0, 0, nullptr);
if (err)
{
return boost::none;
}
// Test for no data. Don't return a value if one pixel
// of the interpolation is no data.
for (int i =0; i<4; i++)
{
if (elevData[i] == ds.GetRasterBand(1)->GetNoDataValue())
{
return boost::none;
}
}
auto xBil1 = elevData[0] * (1-deltaX) + elevData[1] * deltaX;
auto xBil2 = elevData[2] * (1-deltaX) + elevData[3] * deltaX;
auto yBil = xBil1 * (1.0 - deltaY) + xBil2 * deltaY;
return yBil;
}
} // namespace DEMDetails
// Meyer singleton design pattern
DEMHandler & DEMHandler::GetInstance()
{
static DEMHandler s_instance;
return s_instance;
}
DEMHandler::DEMHandler() : m_Dataset(nullptr),
m_GeoidDS(nullptr),
m_DefaultHeightAboveEllipsoid(0.0)
{
GDALAllRegister();
};
DEMHandler::~DEMHandler()
{
if (m_GeoidDS)
{
GDALClose(m_GeoidDS);
}
ClearDEMs();
VSIUnlink(DEM_DATASET_PATH.c_str());
}
void DEMHandler::OpenDEMFile(const std::string& path)
{
m_DatasetList.push_back(otb::GDALDriverManagerWrapper::GetInstance().Open(path));
m_Dataset = m_DatasetList.back()->GetDataSet();
m_DEMDirectories.push_back(path);
}
void DEMHandler::OpenDEMDirectory(const std::string& DEMDirectory)
{
// TODO : RemoveOSSIM
OssimDEMHandler::Instance()->OpenDEMDirectory(DEMDirectory);
// Free the previous in-memory dataset (if any)
if (!m_DatasetList.empty())
VSIUnlink(DEM_DATASET_PATH.c_str());
auto demFiles = DEMDetails::GetFilesInDirectory(DEMDirectory);
for (const auto & file : demFiles)
{
auto ds = otb::GDALDriverManagerWrapper::GetInstance().Open(file);
if (ds)
{
m_DatasetList.push_back(ds );
}
}
int vrtSize = m_DatasetList.size();
// Don't build a vrt if there is less than two dataset
if (m_DatasetList.empty())
{
m_Dataset = nullptr;
}
else
{
if (vrtSize == 1)
{
m_Dataset = m_DatasetList[0]->GetDataSet();
m_DEMDirectories.push_back(DEMDirectory);
}
else
{
std::vector<GDALDatasetH> vrtDatasetList(vrtSize);
for (int i = 0; i < vrtSize; i++)
{
vrtDatasetList[i] = m_DatasetList[i]->GetDataSet();
}
auto close_me = GDALBuildVRT(DEM_DATASET_PATH.c_str(), vrtSize, vrtDatasetList.data(),
nullptr, nullptr, nullptr);
// Need to close the dataset, so it is flushed into memory.
GDALClose(close_me);
m_Dataset = static_cast<GDALDataset*>(GDALOpen(DEM_DATASET_PATH.c_str(), GA_ReadOnly));
m_DEMDirectories.push_back(DEMDirectory);
}
}
}
bool DEMHandler::OpenGeoidFile(const std::string& geoidFile)
{
// TODO : RemoveOSSIM
OssimDEMHandler::Instance()->OpenGeoidFile(geoidFile);
int pbError;
auto ds = GDALOpenVerticalShiftGrid(geoidFile.c_str(), &pbError);
// pbError is set to TRUE if an error happens.
if (pbError == 0)
{
if (m_GeoidDS)
{
GDALClose(m_GeoidDS);
}
m_GeoidDS = static_cast<GDALDataset*>(ds);
m_GeoidFilename = geoidFile;
}
return pbError;
}
double DEMHandler::GetHeightAboveEllipsoid(double lon, double lat) const
{
double result = 0.;
boost::optional<double> DEMresult;
boost::optional<double> geoidResult;
if (m_Dataset)
{
DEMresult = DEMDetails::GetDEMValue(lon, lat, *m_Dataset);
if (DEMresult)
{
result += *DEMresult;
}
}
if (m_GeoidDS)
{
geoidResult = DEMDetails::GetDEMValue(lon, lat, *m_GeoidDS);
if (geoidResult)
{
result += *geoidResult;
}
}
if (DEMresult || geoidResult)
return result;
else
return m_DefaultHeightAboveEllipsoid;
}
double DEMHandler::GetHeightAboveEllipsoid(const PointType& geoPoint) const
{
return GetHeightAboveEllipsoid(geoPoint[0], geoPoint[1]);
}
double DEMHandler::GetHeightAboveMSL(double lon, double lat) const
{
if (m_Dataset)
{
auto result = DEMDetails::GetDEMValue(lon, lat, *m_Dataset);
if (result)
{
return *result;
}
}
return 0;
}
double DEMHandler::GetHeightAboveMSL(const PointType& geoPoint) const
{
return GetHeightAboveMSL(geoPoint[0], geoPoint[1]);
}
unsigned int DEMHandler::GetDEMCount() const
{
return m_DatasetList.size();
}
bool DEMHandler::IsValidDEMDirectory(const std::string& DEMDirectory) const
{
for (const auto & filename : DEMDetails::GetFilesInDirectory(DEMDirectory))
{
// test if a driver can identify this dataset
auto identifyDriverH = GDALIdentifyDriver(filename.c_str(), nullptr);
if (identifyDriverH)
{
return true;
}
}
return false;
}
std::string DEMHandler::GetDEMDirectory(unsigned int idx) const
{
if (idx >= m_DEMDirectories.size())
{
std::ostringstream oss;
oss << "Requested DEM diectory " << idx
<< ", but only "<< m_DEMDirectories.size() << "have been set.";
throw std::out_of_range (oss.str());
}
return m_DEMDirectories[idx];
}
std::string DEMHandler::GetGeoidFile() const
{
return m_GeoidFilename;
}
void DEMHandler::ClearDEMs()
{
// TODO : RemoveOSSIM
// This should be call, but this causes a segfault ... OssimDEMHandler will
// be removed in a near future anyway
// OssimDEMHandler::Instance()->ClearDEMs();
m_DEMDirectories.clear();
// This will call GDALClose on all datasets
m_DatasetList.clear();
}
void DEMHandler::SetDefaultHeightAboveEllipsoid(double height)
{
OssimDEMHandler::Instance()->SetDefaultHeightAboveEllipsoid(height);
m_DefaultHeightAboveEllipsoid = height;
}
double DEMHandler::GetDefaultHeightAboveEllipsoid() const
{
return m_DefaultHeightAboveEllipsoid;
}
} // namespace otb
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbDEMHandler.h"
#include "otbGDALDriverManagerWrapper.h"
#include "boost/filesystem.hpp"
#include <boost/range/iterator_range.hpp>
#include "gdal_utils.h"
//TODO C++ 17 : use std::optional instead
#include <boost/optional.hpp>
// TODO : RemoveOSSIM
#include <otbOssimDEMHandler.h>
#include <mutex>
#include "ogr_spatialref.h"
namespace otb {
namespace DEMDetails {
// Adapted from boost filesystem documentation : https://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/reference.html
std::vector<std::string> GetFilesInDirectory(const std::string & directoryPath)
{
std::vector<std::string> fileList;
if ( !boost::filesystem::exists( directoryPath) )
{
return fileList;
}
else if (!boost::filesystem::is_directory(directoryPath))
{
fileList.push_back(directoryPath);
return fileList;
}
// End iterator : default construction yields past-the-end
for ( const auto & item : boost::make_iterator_range(boost::filesystem::directory_iterator(directoryPath), {}) )
{
if ( boost::filesystem::is_directory(item.status()) )
{
auto subDirList = GetFilesInDirectory(item.path().string());
fileList.insert(fileList.end(), subDirList.begin(), subDirList.end());
}
else
{
fileList.push_back(item.path().string());
}
}
return fileList;
}
std::mutex demMutex;
boost::optional<double> GetDEMValue(double lon, double lat, GDALDataset& ds)
{
const std::lock_guard<std::mutex> lock(demMutex);
#if GDAL_VERSION_NUM >= 3000000
auto srs = ds.GetSpatialRef();
#else
auto projRef = ds.GetProjectionRef();
std::unique_ptr<OGRSpatialReference> srsUniquePtr;
OGRSpatialReference* srs = nullptr;
// GetProjectionRef() returns an empty non null string if no projection is available
if (strlen(projRef) != 0 )
{
srsUniquePtr = std::make_unique<OGRSpatialReference>(ds.GetProjectionRef());
srs = srsUniquePtr.get();
}
#endif
auto wgs84Srs = OGRSpatialReference::GetWGS84SRS();
// Convert input lon lat into the coordinates defined by the dataset if needed.
if (srs && !srs->IsSame(wgs84Srs))
{
auto poCT = std::unique_ptr<OGRCoordinateTransformation>
(OGRCreateCoordinateTransformation(wgs84Srs, srs));
if (poCT && !poCT->Transform( 1, &lon, &lat ) )
{
return boost::none;
}
}
double geoTransform[6];
ds.GetGeoTransform(geoTransform);
auto x = (lon - geoTransform[0]) / geoTransform[1] - 0.5;
auto y = (lat - geoTransform[3]) / geoTransform[5] - 0.5;
if (x < 0 || y < 0 || x > ds.GetRasterXSize() || y > ds.GetRasterYSize())
{
return boost::none;
}
auto x_int = static_cast<int>(x);
auto y_int = static_cast<int>(y);
auto deltaX = x - x_int;
auto deltaY = y - y_int;
if (x < 0 || y < 0 || x+1 > ds.GetRasterXSize() || y+1 > ds.GetRasterYSize())
{
return boost::none;
}
// Bilinear interpolation.
double elevData[4];
auto err = ds.GetRasterBand(1)->RasterIO( GF_Read, x_int, y_int, 2, 2,
elevData, 2, 2, GDT_Float64,
0, 0, nullptr);
if (err)
{
return boost::none;
}
// Test for no data. Don't return a value if one pixel
// of the interpolation is no data.
for (int i =0; i<4; i++)
{
if (elevData[i] == ds.GetRasterBand(1)->GetNoDataValue())
{
return boost::none;
}
}
auto xBil1 = elevData[0] * (1-deltaX) + elevData[1] * deltaX;
auto xBil2 = elevData[2] * (1-deltaX) + elevData[3] * deltaX;
auto yBil = xBil1 * (1.0 - deltaY) + xBil2 * deltaY;
return yBil;
}
} // namespace DEMDetails
// Meyer singleton design pattern
DEMHandler & DEMHandler::GetInstance()
{
static DEMHandler s_instance;
return s_instance;
}
DEMHandler::DEMHandler() : m_Dataset(nullptr),
m_GeoidDS(nullptr),
m_DefaultHeightAboveEllipsoid(0.0)
{
GDALAllRegister();
};
DEMHandler::~DEMHandler()
{
if (m_GeoidDS)
{
GDALClose(m_GeoidDS);
}
ClearDEMs();
VSIUnlink(DEM_DATASET_PATH.c_str());
}
void DEMHandler::OpenDEMFile(const std::string& path)
{
m_DatasetList.push_back(otb::GDALDriverManagerWrapper::GetInstance().Open(path));
std::vector<GDALDatasetH> vrtDatasetList(1);
vrtDatasetList[0] = m_DatasetList[0]->GetDataSet();
auto close_me = GDALBuildVRT(DEM_DATASET_PATH.c_str(), 1, vrtDatasetList.data(),
nullptr, nullptr, nullptr);
// Need to close the dataset, so it is flushed into memory.
GDALClose(close_me);
m_Dataset = static_cast<GDALDataset*>(GDALOpen(DEM_DATASET_PATH.c_str(), GA_ReadOnly));
m_DEMDirectories.push_back(path);
}
void DEMHandler::OpenDEMDirectory(const std::string& DEMDirectory)
{
// TODO : RemoveOSSIM
OssimDEMHandler::Instance()->OpenDEMDirectory(DEMDirectory);
// Free the previous in-memory dataset (if any)
if (!m_DatasetList.empty())
VSIUnlink(DEM_DATASET_PATH.c_str());
auto demFiles = DEMDetails::GetFilesInDirectory(DEMDirectory);
for (const auto & file : demFiles)
{
auto ds = otb::GDALDriverManagerWrapper::GetInstance().Open(file);
if (ds)
{
m_DatasetList.push_back(ds );
}
}
int vrtSize = m_DatasetList.size();
// Don't build a vrt if there is no dataset
if (m_DatasetList.empty())
{
m_Dataset = nullptr;
}
else
{
std::vector<GDALDatasetH> vrtDatasetList(vrtSize);
for (int i = 0; i < vrtSize; i++)
{
vrtDatasetList[i] = m_DatasetList[i]->GetDataSet();
}
auto close_me = GDALBuildVRT(DEM_DATASET_PATH.c_str(), vrtSize, vrtDatasetList.data(),
nullptr, nullptr, nullptr);
// Need to close the dataset, so it is flushed into memory.
GDALClose(close_me);
m_Dataset = static_cast<GDALDataset*>(GDALOpen(DEM_DATASET_PATH.c_str(), GA_ReadOnly));
m_DEMDirectories.push_back(DEMDirectory);
}
}
bool DEMHandler::OpenGeoidFile(const std::string& geoidFile)
{
// TODO : RemoveOSSIM
OssimDEMHandler::Instance()->OpenGeoidFile(geoidFile);
int pbError;
auto ds = GDALOpenVerticalShiftGrid(geoidFile.c_str(), &pbError);
// pbError is set to TRUE if an error happens.
if (pbError == 0)
{
if (m_GeoidDS)
{
GDALClose(m_GeoidDS);
}
m_GeoidDS = static_cast<GDALDataset*>(ds);
m_GeoidFilename = geoidFile;
}
return pbError;
}
double DEMHandler::GetHeightAboveEllipsoid(double lon, double lat) const
{
double result = 0.;
boost::optional<double> DEMresult;
boost::optional<double> geoidResult;
if (m_Dataset)
{
DEMresult = DEMDetails::GetDEMValue(lon, lat, *m_Dataset);
if (DEMresult)
{
result += *DEMresult;
}
}
if (m_GeoidDS)
{
geoidResult = DEMDetails::GetDEMValue(lon, lat, *m_GeoidDS);
if (geoidResult)
{
result += *geoidResult;
}
}
if (DEMresult || geoidResult)
return result;
else
return m_DefaultHeightAboveEllipsoid;
}
double DEMHandler::GetHeightAboveEllipsoid(const PointType& geoPoint) const
{
return GetHeightAboveEllipsoid(geoPoint[0], geoPoint[1]);
}
double DEMHandler::GetHeightAboveMSL(double lon, double lat) const
{
if (m_Dataset)
{
auto result = DEMDetails::GetDEMValue(lon, lat, *m_Dataset);
if (result)
{
return *result;
}
}
return 0;
}
double DEMHandler::GetHeightAboveMSL(const PointType& geoPoint) const
{
return GetHeightAboveMSL(geoPoint[0], geoPoint[1]);
}
unsigned int DEMHandler::GetDEMCount() const
{
return m_DatasetList.size();
}
bool DEMHandler::IsValidDEMDirectory(const std::string& DEMDirectory) const
{
for (const auto & filename : DEMDetails::GetFilesInDirectory(DEMDirectory))
{
// test if a driver can identify this dataset
auto identifyDriverH = GDALIdentifyDriver(filename.c_str(), nullptr);
if (identifyDriverH)
{
return true;
}
}
return false;
}
std::string DEMHandler::GetDEMDirectory(unsigned int idx) const
{
if (idx >= m_DEMDirectories.size())
{
std::ostringstream oss;
oss << "Requested DEM diectory " << idx
<< ", but only "<< m_DEMDirectories.size() << "have been set.";
throw std::out_of_range (oss.str());
}
return m_DEMDirectories[idx];
}
std::string DEMHandler::GetGeoidFile() const
{
return m_GeoidFilename;
}
void DEMHandler::ClearDEMs()
{
// TODO : RemoveOSSIM
// This should be call, but this causes a segfault ... OssimDEMHandler will
// be removed in a near future anyway
// OssimDEMHandler::Instance()->ClearDEMs();
m_DEMDirectories.clear();
// This will call GDALClose on all datasets
m_DatasetList.clear();
}
void DEMHandler::SetDefaultHeightAboveEllipsoid(double height)
{
OssimDEMHandler::Instance()->SetDefaultHeightAboveEllipsoid(height);
m_DefaultHeightAboveEllipsoid = height;
}
double DEMHandler::GetDefaultHeightAboveEllipsoid() const
{
return m_DefaultHeightAboveEllipsoid;
}
} // namespace otb
|
Write the DEM to the VSI memory as a VRT
|
ENH: Write the DEM to the VSI memory as a VRT
The DEMHandler creates a VRT in any cases (the user provides a
unique file, or a directory with only one file or with multiple
files). This VRT is loaded into vsi memory, so it can be accessed
by other procvesses.
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
fe17a849b85dd92178830e556258e0df63cf20d3
|
fswork/fswork.cpp
|
fswork/fswork.cpp
|
#include <fstream>
// #include <sys/types.h>
// #include <unistd.h>
// #include <string>
// #include <fcntl.h>
// #include <stdio.h>
// #include <stdlib.h>
#include <dirent.h> // !!!
#include <vector>
#include "../lang/lang.h"
#include "../configurator/configurator.h"
#include <curses.h>
using namespace std;
struct FILEINFO {
string name;
// ... информация о файле ...
};
bool makedir(string path) {
/*if (mkdir(path.c_str(), 0777) != 0) {
}*/
return false;
}
inline bool FileExists(const string& path) {
return ifstream(path.c_str()).good();
}
void files_sort_by(char type_sort, vector<FILEINFO> &filevec) {
FILEINFO temp_1, temp_2, temp_3;
unsigned int k_cycle, itemp_1, itemp_2;
for (unsigned int i = 0; i < filevec.size() - 1; i++) { // Сортировка методом пузырька
for (unsigned int j = 0; j < filevec.size() - i - 1; j++) {
if (type_sort == 'n') { // Сортировка по имени
temp_1 = filevec[j];
temp_2 = filevec[j + 1];
if (llength(temp_1.name) >= llength(temp_2.name)) k_cycle = llength(temp_2.name); // Взятие длины наименьшего
else k_cycle = llength(temp_1.name);
for (unsigned int k = 0; k < k_cycle; k++) { // Чтобы сортировка шла не только по первым буквам, но и по остальным, если они одинаковые
if (((int)temp_1.name[k] >= 97) && ((int)temp_1.name[k] <= 122)) itemp_1 = (int)temp_1.name[k] - 32; // Исправление маленьких букв на большие
else itemp_1 = (int)temp_1.name[k];
if (((int)temp_2.name[k] >= 97) && ((int)temp_2.name[k] <= 122)) itemp_2 = (int)temp_2.name[k] - 32;
else itemp_2 = (int)temp_2.name[k];
if (itemp_1 == itemp_2) continue; // Обработать следующие буквы, если эти одинаковые
if (itemp_1 > itemp_2) { // Поменять местами
temp_3 = filevec[j];
filevec[j] = filevec[j + 1];
filevec[j + 1] = temp_3;
break;
} else break; // Иначе остановиться и перейти к следующим элементам
}
}
}
}
return;
}
int get_files(string path, vector<FILEINFO> &filevec) {
DIR *dir;
if ((dir=opendir(path.c_str())) == NULL)
return -1;
else {
FILEINFO file_info;
struct dirent *f_cur;
while ((f_cur=readdir(dir))!= NULL) {
file_info.name = f_cur->d_name;
if ((file_info.name != "..") && (file_info.name != ".")) {
filevec.insert(filevec.end(), file_info);
}
}
closedir(dir);
return 0;
}
}
|
#include <fstream>
// #include <sys/types.h>
// #include <unistd.h>
// #include <string>
// #include <fcntl.h>
// #include <stdio.h>
// #include <stdlib.h>
#include <dirent.h> // !!!
#include <vector>
#include "../lang/lang.h"
#include "../configurator/configurator.h"
#include "fswork.h"
#include <curses.h>
using namespace std;
bool makedir(string path) {
/*if (mkdir(path.c_str(), 0777) != 0) {
}*/
return false;
}
inline bool FileExists(const string& path) {
return ifstream(path.c_str()).good();
}
void files_sort_by(char type_sort, vector<FILEINFO> &filevec) {
FILEINFO temp_1, temp_2, temp_3;
unsigned int k_cycle, itemp_1, itemp_2;
for (unsigned int i = 0; i < filevec.size() - 1; i++) { // Сортировка методом пузырька
for (unsigned int j = 0; j < filevec.size() - i - 1; j++) {
if (type_sort == 'n') { // Сортировка по имени
temp_1 = filevec[j];
temp_2 = filevec[j + 1];
if (llength(temp_1.name) >= llength(temp_2.name)) k_cycle = llength(temp_2.name); // Взятие длины наименьшего
else k_cycle = llength(temp_1.name);
for (unsigned int k = 0; k < k_cycle; k++) { // Чтобы сортировка шла не только по первым буквам, но и по остальным, если они одинаковые
if (((int)temp_1.name[k] >= 97) && ((int)temp_1.name[k] <= 122)) itemp_1 = (int)temp_1.name[k] - 32; // Исправление маленьких букв на большие
else itemp_1 = (int)temp_1.name[k];
if (((int)temp_2.name[k] >= 97) && ((int)temp_2.name[k] <= 122)) itemp_2 = (int)temp_2.name[k] - 32;
else itemp_2 = (int)temp_2.name[k];
if (itemp_1 == itemp_2) continue; // Обработать следующие буквы, если эти одинаковые
if (itemp_1 > itemp_2) { // Поменять местами
temp_3 = filevec[j];
filevec[j] = filevec[j + 1];
filevec[j + 1] = temp_3;
break;
} else break; // Иначе остановиться и перейти к следующим элементам
}
}
}
}
return;
}
int get_files(string path, vector<FILEINFO> &filevec) {
DIR *dir;
if ((dir=opendir(path.c_str())) == NULL)
return -1;
else {
FILEINFO file_info;
struct dirent *f_cur;
while ((f_cur=readdir(dir))!= NULL) {
file_info.name = f_cur->d_name;
if ((file_info.name != "..") && (file_info.name != ".")) {
filevec.insert(filevec.end(), file_info);
}
}
closedir(dir);
return 0;
}
}
|
Update fswork.cpp
|
Update fswork.cpp
|
C++
|
apache-2.0
|
dima201246/hos,dima201246/hos
|
34e3d3f152ba010b2a7805a8bbb85ed08c7f05cd
|
globalhandler.cpp
|
globalhandler.cpp
|
#include "globalhandler.h"
#include "host-ipmid/ipmid-api.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <mapper.h>
const char *control_object_name = "/org/openbmc/control/bmc0";
const char *control_intf_name = "org.openbmc.control.Bmc";
void register_netfn_global_functions() __attribute__((constructor));
int dbus_reset(const char *method)
{
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message *m = NULL;
sd_bus *bus = NULL;
char* connection = NULL;
int r;
bus = ipmid_get_sd_bus_connection();
r = mapper_get_service(bus, control_object_name, &connection);
if (r < 0) {
fprintf(stderr, "Failed to get connection for %s: %s\n",
control_object_name, strerror(-r));
goto finish;
}
printf("connection: %s\n", connection);
// Open the system bus where most system services are provided.
bus = ipmid_get_sd_bus_connection();
/*
* Bus, service, object path, interface and method are provided to call
* the method.
* Signatures and input arguments are provided by the arguments at the
* end.
*/
r = sd_bus_call_method(bus,
connection, /* service to contact */
control_object_name, /* object path */
control_intf_name, /* interface name */
method, /* method name */
&error, /* object to return error in */
&m, /* return message on success */
NULL,
NULL
);
if (r < 0) {
fprintf(stderr, "Failed to issue method call: %s\n", error.message);
goto finish;
}
finish:
sd_bus_error_free(&error);
sd_bus_message_unref(m);
free(connection);
return r;
}
ipmi_ret_t ipmi_global_warm_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling GLOBAL warmReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// TODO: call the correct dbus method for warmReset.
dbus_reset("warmReset");
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = 0;
return rc;
}
ipmi_ret_t ipmi_global_cold_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
printf("Handling GLOBAL coldReset Netfn:[0x%X], Cmd:[0x%X]\n",netfn, cmd);
// TODO: call the correct dbus method for coldReset.
dbus_reset("coldReset");
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = 0;
return rc;
}
void register_netfn_global_functions()
{
// Cold Reset
printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_COLD_RESET);
ipmi_register_callback(NETFUN_APP, IPMI_CMD_COLD_RESET, NULL, ipmi_global_cold_reset,
PRIVILEGE_ADMIN);
// <Warm Reset>
printf("Registering NetFn:[0x%X], Cmd:[0x%X]\n",NETFUN_APP, IPMI_CMD_WARM_RESET);
ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL, ipmi_global_warm_reset,
PRIVILEGE_ADMIN);
return;
}
|
#include "globalhandler.h"
#include "host-ipmid/ipmid-api.h"
#include <stdio.h>
#include <string>
#include <utils.hpp>
#include <phosphor-logging/log.hpp>
#include <phosphor-logging/elog-errors.hpp>
#include "xyz/openbmc_project/Common/error.hpp"
#include "xyz/openbmc_project/State/BMC/server.hpp"
static constexpr auto bmcStateRoot = "/xyz/openbmc_project/state";
static constexpr auto bmcStateIntf = "xyz.openbmc_project.State.BMC";
static constexpr auto reqTransition = "RequestedBMCTransition";
static constexpr auto match = "bmc0";
using namespace phosphor::logging;
using BMC = sdbusplus::xyz::openbmc_project::State::server::BMC;
void register_netfn_global_functions() __attribute__((constructor));
void resetBMC()
{
sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()};
auto bmcStateObj = ipmi::getDbusObject(bus, bmcStateIntf, bmcStateRoot,
match);
auto service = ipmi::getService(bus, bmcStateIntf, bmcStateObj.first);
ipmi::setDbusProperty(bus, service, bmcStateObj.first, bmcStateIntf,
reqTransition, convertForMessage(BMC::Transition::Reboot));
}
ipmi_ret_t ipmi_global_reset(ipmi_netfn_t netfn, ipmi_cmd_t cmd,
ipmi_request_t request, ipmi_response_t response,
ipmi_data_len_t data_len, ipmi_context_t context)
{
try
{
resetBMC();
}
catch (std::exception& e)
{
log<level::ERR>(e.what());
return IPMI_CC_UNSPECIFIED_ERROR;
}
// Status code.
ipmi_ret_t rc = IPMI_CC_OK;
*data_len = 0;
return rc;
}
void register_netfn_global_functions()
{
// Cold Reset
ipmi_register_callback(NETFUN_APP, IPMI_CMD_COLD_RESET, NULL,
ipmi_global_reset, PRIVILEGE_ADMIN);
// <Warm Reset>
ipmi_register_callback(NETFUN_APP, IPMI_CMD_WARM_RESET, NULL,
ipmi_global_reset, PRIVILEGE_ADMIN);
return;
}
|
Remove use of legacy bmc control interface
|
Remove use of legacy bmc control interface
Tested:
Tested using below given command for cold/warm resets
>ipmitool mc reset [ warm | cold ] -I dbus
Resolves openbmc/openbmc#2919
Change-Id: I15fc5ab53b7d8b2b17bc9fa8f3f2030e93bd0483
Signed-off-by: Nagaraju Goruganti <[email protected]>
|
C++
|
apache-2.0
|
openbmc/phosphor-host-ipmid,openbmc/phosphor-host-ipmid,openbmc/phosphor-host-ipmid
|
1def9aa0ccbf034a9edd516376a0b84a180864cd
|
lib/wd/sm.cpp
|
lib/wd/sm.cpp
|
#include <QApplication>
#include "wd.h"
#include "cmd.h"
#include "../base/bedit.h"
#include "../base/note.h"
#include "../base/state.h"
#include "../base/tedit.h"
#include "../base/term.h"
extern int rc;
string smerror(string);
string smfocus(string);
string smget(string);
string smgetactive();
string smgetwin(string);
string smgetwin1(Bedit *);
string smgetxywh();
string smgetxywh1(QWidget *);
string smset(string);
string smsetselect(Bedit *,QStringList);
string smsettext(Bedit *,QStringList);
string smsetxywh(QWidget *,QStringList);
// ---------------------------------------------------------------------
// c is type, p is parameter
string sm(string c,string p)
{
rc=0;
if (c=="focus")
return smfocus(p);
if (c=="get")
return smget(p);
if (c=="set")
return smset(p);
if (c=="act")
term->smact();
else if (c=="prompt")
term->smprompt(s2q(p));
else
return smerror("unrecognized sm command: " + c);
return "";
}
// ---------------------------------------------------------------------
string smerror(string p)
{
rc=1;
return p;
}
// ---------------------------------------------------------------------
string smfocus(string p)
{
if (p.size()==0)
return smerror("sm focus needs additional parameters");
if (p=="term")
term->smact();
else if (p=="edit") {
if (note==0 || note->editIndex()==-1)
return smerror("No active edit window");
note->activateWindow();
note->raise();
note->repaint();
} else
return smerror("unrecognized sm command: focus " + p);
return "";
}
// ---------------------------------------------------------------------
string smget(string p)
{
if (p.size()==0)
return smerror("sm get needs additional parameters");
if (p=="active")
return smgetactive();
if (p=="term" || p=="edit" || p=="edit2")
return smgetwin(p);
if (p=="xywh")
return smgetxywh();
return smerror("unrecognized sm command: get " + p);
}
// ---------------------------------------------------------------------
string smgetactive()
{
rc=-1;
return (note && ActiveWindows.indexOf(note)<ActiveWindows.indexOf(term))
? "edit" : "term";
}
// ---------------------------------------------------------------------
string smgetwin(string p)
{
rc=-2;
if (p=="term")
return smgetwin1(tedit);
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
if (note->editIndex()==-1)
return smgetwin1((Bedit *)0);
return smgetwin1((Bedit *)note->editPage());
}
if (note2==0)
return smerror("No active edit2 window");
if (note2->editIndex()==-1)
return smgetwin1((Bedit *)0);
return smgetwin1((Bedit *)note2->editPage());
}
// ---------------------------------------------------------------------
string smgetwin1(Bedit *t)
{
string r;
if (t==0) {
r+=spair("text",(string)"");
r+=spair("select",(string)"");
} else {
QTextCursor c=t->textCursor();
int b=c.selectionStart();
int e=c.selectionEnd();
r+=spair("text",t->toPlainText());
r+=spair("select",QString::number(b)+" "+QString::number(e));
}
return r;
}
// ---------------------------------------------------------------------
string smgetxywh()
{
rc=-2;
string r;
r+=spair("text",smgetxywh1(term));
if (note)
r+=spair("edit",smgetxywh1(note));
if (note2)
r+=spair("edit2",smgetxywh1(note2));
return r;
}
// ---------------------------------------------------------------------
string smgetxywh1(QWidget *w)
{
QPoint p=w->pos();
QSize z=w->size();
return q2s(QString::number(p.rx())+" "+QString::number(p.ry())+
" "+QString::number(z.width())+" "+QString::number(z.height()));
}
// ---------------------------------------------------------------------
string smset(string arg)
{
QStringList opt=qsplit(arg);
QString p,q;
Bedit *e;
QWidget *w;
if (opt.size()==0)
return smerror("sm set parameters not given");
if (opt.size()==1)
return smerror ("sm set " + q2s(opt[0]) + " parameters not given");
p=opt[0];
q=opt[1];
opt=opt.mid(2);
if (p=="term") {
e=tedit;
w=term;
} else if (p=="edit") {
if (note==0)
return smerror("No active edit window");
e=(Bedit *)note->editPage();
w=note;
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
e=(Bedit *)note2->editPage();
w=note2;
} else
return smerror("unrecognized sm command: set " + q2s(p));
if (e==0 && (q=="select" || q=="text"))
return smerror("no edit window for sm command: set " + q2s(q));
if (q=="select")
return smsetselect(e,opt);
if (q=="text")
return smsettext(e,opt);
if (q=="xywh")
return smsetxywh(w,opt);
return smerror("unrecognized sm command: set " + q2s(p) + " " + q2s(q));
}
// ---------------------------------------------------------------------
string smsetselect(Bedit *e,QStringList opt)
{
QList<int> s=qsl2intlist(opt);
if (s.size()!= 2)
return smerror ("sm set select should have begin and end parameters");
int m=e->toPlainText().size();
if (s[1]==-1) s[1]=m;
s[1]=qMin(m,s[1]);
s[0]=qMin(s[0],s[1]);
e->setselect(s[0],s[1]-s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsettext(Bedit *e,QStringList opt)
{
e->setPlainText(opt[0]);
return"";
}
// ---------------------------------------------------------------------
string smsetxywh(QWidget *w,QStringList opt)
{
QList<int> s=qsl2intlist(opt);
QPoint p=w->pos();
QSize z=w->size();
if (s[0]==-1) s[0]=p.rx();
if (s[1]==-1) s[1]=p.ry();
if (s[2]==-1) s[2]=z.width();
if (s[3]==-1) s[3]=z.height();
w->move(s[0],s[1]);
w->resize(s[2],s[3]);
return"";
}
|
#include <QApplication>
#include "wd.h"
#include "cmd.h"
#include "../base/bedit.h"
#include "../base/note.h"
#include "../base/state.h"
#include "../base/tedit.h"
#include "../base/term.h"
extern int rc;
string smerror(string);
string smfocus(string);
string smget(string);
string smgetactive();
string smgetwin(string);
string smgetwin1(Bedit *);
string smgetxywh();
string smgetxywh1(QWidget *);
string smset(string);
string smsetselect(Bedit *,QStringList);
string smsettext(Bedit *,QStringList);
string smsetxywh(QWidget *,QStringList);
// ---------------------------------------------------------------------
// c is type, p is parameter
string sm(string c,string p)
{
rc=0;
if (c=="focus")
return smfocus(p);
if (c=="get")
return smget(p);
if (c=="set")
return smset(p);
if (c=="act")
term->smact();
else if (c=="prompt")
term->smprompt(s2q(p));
else
return smerror("unrecognized sm command: " + c);
return "";
}
// ---------------------------------------------------------------------
string smerror(string p)
{
rc=1;
return p;
}
// ---------------------------------------------------------------------
string smfocus(string p)
{
if (p.size()==0)
return smerror("sm focus needs additional parameters");
if (p=="term")
term->smact();
else if (p=="edit") {
if (note==0 || note->editIndex()==-1)
return smerror("No active edit window");
note->activateWindow();
note->raise();
note->repaint();
} else
return smerror("unrecognized sm command: focus " + p);
return "";
}
// ---------------------------------------------------------------------
string smget(string p)
{
if (p.size()==0)
return smerror("sm get needs additional parameters");
if (p=="active")
return smgetactive();
if (p=="term" || p=="edit" || p=="edit2")
return smgetwin(p);
if (p=="xywh")
return smgetxywh();
return smerror("unrecognized sm command: get " + p);
}
// ---------------------------------------------------------------------
string smgetactive()
{
rc=-1;
return (note && ActiveWindows.indexOf(note)<ActiveWindows.indexOf(term))
? "edit" : "term";
}
// ---------------------------------------------------------------------
string smgetwin(string p)
{
rc=-2;
if (p=="term")
return smgetwin1(tedit);
if (p=="edit") {
if (note==0)
return smerror("No active edit window");
if (note->editIndex()==-1)
return smgetwin1((Bedit *)0);
string r=smgetwin1((Bedit *)note->editPage());
r+=spair("file",note->editFile());
return r;
}
if (note2==0)
return smerror("No active edit2 window");
if (note2->editIndex()==-1)
return smgetwin1((Bedit *)0);
return smgetwin1((Bedit *)note2->editPage());
}
// ---------------------------------------------------------------------
string smgetwin1(Bedit *t)
{
string r;
if (t==0) {
r+=spair("text",(string)"");
r+=spair("select",(string)"");
} else {
QTextCursor c=t->textCursor();
int b=c.selectionStart();
int e=c.selectionEnd();
r+=spair("text",t->toPlainText());
r+=spair("select",QString::number(b)+" "+QString::number(e));
}
return r;
}
// ---------------------------------------------------------------------
string smgetxywh()
{
rc=-2;
string r;
r+=spair("text",smgetxywh1(term));
if (note)
r+=spair("edit",smgetxywh1(note));
if (note2)
r+=spair("edit2",smgetxywh1(note2));
return r;
}
// ---------------------------------------------------------------------
string smgetxywh1(QWidget *w)
{
QPoint p=w->pos();
QSize z=w->size();
return q2s(QString::number(p.rx())+" "+QString::number(p.ry())+
" "+QString::number(z.width())+" "+QString::number(z.height()));
}
// ---------------------------------------------------------------------
string smset(string arg)
{
QStringList opt=qsplit(arg);
QString p,q;
Bedit *e;
QWidget *w;
if (opt.size()==0)
return smerror("sm set parameters not given");
if (opt.size()==1)
return smerror ("sm set " + q2s(opt[0]) + " parameters not given");
p=opt[0];
q=opt[1];
opt=opt.mid(2);
if (p=="term") {
e=tedit;
w=term;
} else if (p=="edit") {
if (note==0)
return smerror("No active edit window");
e=(Bedit *)note->editPage();
w=note;
} else if (p=="edit2") {
if (note2==0)
return smerror("No active edit2 window");
e=(Bedit *)note2->editPage();
w=note2;
} else
return smerror("unrecognized sm command: set " + q2s(p));
if (e==0 && (q=="select" || q=="text"))
return smerror("no edit window for sm command: set " + q2s(q));
if (q=="select")
return smsetselect(e,opt);
if (q=="text")
return smsettext(e,opt);
if (q=="xywh")
return smsetxywh(w,opt);
return smerror("unrecognized sm command: set " + q2s(p) + " " + q2s(q));
}
// ---------------------------------------------------------------------
string smsetselect(Bedit *e,QStringList opt)
{
QList<int> s=qsl2intlist(opt);
if (s.size()!= 2)
return smerror ("sm set select should have begin and end parameters");
int m=e->toPlainText().size();
if (s[1]==-1) s[1]=m;
s[1]=qMin(m,s[1]);
s[0]=qMin(s[0],s[1]);
e->setselect(s[0],s[1]-s[0]);
return"";
}
// ---------------------------------------------------------------------
string smsettext(Bedit *e,QStringList opt)
{
e->setPlainText(opt[0]);
return"";
}
// ---------------------------------------------------------------------
string smsetxywh(QWidget *w,QStringList opt)
{
QList<int> s=qsl2intlist(opt);
QPoint p=w->pos();
QSize z=w->size();
if (s[0]==-1) s[0]=p.rx();
if (s[1]==-1) s[1]=p.ry();
if (s[2]==-1) s[2]=z.width();
if (s[3]==-1) s[3]=z.height();
w->move(s[0],s[1]);
w->resize(s[2],s[3]);
return"";
}
|
add file name to wd 'sm get edit'
|
add file name to wd 'sm get edit'
|
C++
|
lgpl-2.1
|
0branch/qtide,0branch/qtide,0branch/qtide
|
70adf628f1575d23efffe67b5a065cb682b8bf25
|
src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
|
src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cmakerunconfiguration.h"
#include "cmakeproject.h"
#include "cmakebuildconfiguration.h"
#include "cmakeprojectconstants.h"
#include <projectexplorer/environment.h>
#include <projectexplorer/debugginghelper.h>
#include <utils/qtcassert.h>
#include <QtGui/QFormLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QGroupBox>
#include <QtGui/QLabel>
#include <QtGui/QComboBox>
#include <QtGui/QToolButton>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
CMakeRunConfiguration::CMakeRunConfiguration(CMakeProject *pro, const QString &target, const QString &workingDirectory, const QString &title)
: ProjectExplorer::LocalApplicationRunConfiguration(pro)
, m_runMode(Gui)
, m_target(target)
, m_workingDirectory(workingDirectory)
, m_title(title)
, m_baseEnvironmentBase(CMakeRunConfiguration::BuildEnvironmentBase)
{
setName(title);
connect(pro, SIGNAL(activeBuildConfigurationChanged()),
this, SIGNAL(baseEnvironmentChanged()));
// TODO
// connect(pro, SIGNAL(environmentChanged(ProjectExplorer::BuildConfiguration *)),
// this, SIGNAL(baseEnvironmentChanged()));
}
CMakeRunConfiguration::~CMakeRunConfiguration()
{
}
CMakeProject *CMakeRunConfiguration::cmakeProject() const
{
return static_cast<CMakeProject *>(project());
}
QString CMakeRunConfiguration::type() const
{
return Constants::CMAKERUNCONFIGURATION;
}
QString CMakeRunConfiguration::executable() const
{
return m_target;
}
ProjectExplorer::LocalApplicationRunConfiguration::RunMode CMakeRunConfiguration::runMode() const
{
return m_runMode;
}
QString CMakeRunConfiguration::workingDirectory() const
{
if (!m_userWorkingDirectory.isEmpty())
return m_userWorkingDirectory;
return m_workingDirectory;
}
QStringList CMakeRunConfiguration::commandLineArguments() const
{
return ProjectExplorer::Environment::parseCombinedArgString(m_arguments);
}
QString CMakeRunConfiguration::title() const
{
return m_title;
}
void CMakeRunConfiguration::setExecutable(const QString &executable)
{
m_target = executable;
}
void CMakeRunConfiguration::setWorkingDirectory(const QString &wd)
{
const QString & oldWorkingDirectory = workingDirectory();
m_workingDirectory = wd;
const QString &newWorkingDirectory = workingDirectory();
if (oldWorkingDirectory != newWorkingDirectory)
emit workingDirectoryChanged(newWorkingDirectory);
}
void CMakeRunConfiguration::setUserWorkingDirectory(const QString &wd)
{
const QString & oldWorkingDirectory = workingDirectory();
m_userWorkingDirectory = wd;
const QString &newWorkingDirectory = workingDirectory();
if (oldWorkingDirectory != newWorkingDirectory)
emit workingDirectoryChanged(newWorkingDirectory);
}
void CMakeRunConfiguration::save(ProjectExplorer::PersistentSettingsWriter &writer) const
{
ProjectExplorer::LocalApplicationRunConfiguration::save(writer);
writer.saveValue("CMakeRunConfiguration.Target", m_target);
writer.saveValue("CMakeRunConfiguration.WorkingDirectory", m_workingDirectory);
writer.saveValue("CMakeRunConfiguration.UserWorkingDirectory", m_userWorkingDirectory);
writer.saveValue("CMakeRunConfiguration.UseTerminal", m_runMode == Console);
writer.saveValue("CMakeRunConfiguation.Title", m_title);
writer.saveValue("CMakeRunConfiguration.Arguments", m_arguments);
writer.saveValue("CMakeRunConfiguration.UserEnvironmentChanges", ProjectExplorer::EnvironmentItem::toStringList(m_userEnvironmentChanges));
writer.saveValue("BaseEnvironmentBase", m_baseEnvironmentBase);
}
void CMakeRunConfiguration::restore(const ProjectExplorer::PersistentSettingsReader &reader)
{
ProjectExplorer::LocalApplicationRunConfiguration::restore(reader);
m_target = reader.restoreValue("CMakeRunConfiguration.Target").toString();
m_workingDirectory = reader.restoreValue("CMakeRunConfiguration.WorkingDirectory").toString();
m_userWorkingDirectory = reader.restoreValue("CMakeRunConfiguration.UserWorkingDirectory").toString();
m_runMode = reader.restoreValue("CMakeRunConfiguration.UseTerminal").toBool() ? Console : Gui;
m_title = reader.restoreValue("CMakeRunConfiguation.Title").toString();
m_arguments = reader.restoreValue("CMakeRunConfiguration.Arguments").toString();
m_userEnvironmentChanges = ProjectExplorer::EnvironmentItem::fromStringList(reader.restoreValue("CMakeRunConfiguration.UserEnvironmentChanges").toStringList());
QVariant tmp = reader.restoreValue("BaseEnvironmentBase");
m_baseEnvironmentBase = tmp.isValid() ? BaseEnvironmentBase(tmp.toInt()) : CMakeRunConfiguration::BuildEnvironmentBase;
}
QWidget *CMakeRunConfiguration::configurationWidget()
{
return new CMakeRunConfigurationWidget(this);
}
void CMakeRunConfiguration::setArguments(const QString &newText)
{
m_arguments = newText;
}
QString CMakeRunConfiguration::dumperLibrary() const
{
QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt(environment());
QString qtInstallData = ProjectExplorer::DebuggingHelperLibrary::qtInstallDataDir(qmakePath);
QString dhl = ProjectExplorer::DebuggingHelperLibrary::debuggingHelperLibraryByInstallData(qtInstallData);
return dhl;
}
QStringList CMakeRunConfiguration::dumperLibraryLocations() const
{
QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt(environment());
QString qtInstallData = ProjectExplorer::DebuggingHelperLibrary::qtInstallDataDir(qmakePath);
return ProjectExplorer::DebuggingHelperLibrary::debuggingHelperLibraryLocationsByInstallData(qtInstallData);
}
ProjectExplorer::Environment CMakeRunConfiguration::baseEnvironment() const
{
ProjectExplorer::Environment env;
if (m_baseEnvironmentBase == CMakeRunConfiguration::CleanEnvironmentBase) {
// Nothing
} else if (m_baseEnvironmentBase == CMakeRunConfiguration::SystemEnvironmentBase) {
env = ProjectExplorer::Environment::systemEnvironment();
} else if (m_baseEnvironmentBase == CMakeRunConfiguration::BuildEnvironmentBase) {
env = environment();
}
return env;
}
void CMakeRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env)
{
if (m_baseEnvironmentBase == env)
return;
m_baseEnvironmentBase = env;
emit baseEnvironmentChanged();
}
CMakeRunConfiguration::BaseEnvironmentBase CMakeRunConfiguration::baseEnvironmentBase() const
{
return m_baseEnvironmentBase;
}
ProjectExplorer::Environment CMakeRunConfiguration::environment() const
{
ProjectExplorer::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
QList<ProjectExplorer::EnvironmentItem> CMakeRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void CMakeRunConfiguration::setUserEnvironmentChanges(const QList<ProjectExplorer::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
emit userEnvironmentChangesChanged(diff);
}
}
ProjectExplorer::ToolChain::ToolChainType CMakeRunConfiguration::toolChainType() const
{
CMakeBuildConfiguration *bc = cmakeProject()->activeCMakeBuildConfiguration();
return bc->toolChainType();
}
// Configuration widget
CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *cmakeRunConfiguration, QWidget *parent)
: QWidget(parent), m_ignoreChange(false), m_cmakeRunConfiguration(cmakeRunConfiguration)
{
QFormLayout *fl = new QFormLayout();
fl->setMargin(0);
fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
QLineEdit *argumentsLineEdit = new QLineEdit();
argumentsLineEdit->setText(ProjectExplorer::Environment::joinArgumentList(cmakeRunConfiguration->commandLineArguments()));
connect(argumentsLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(setArguments(QString)));
fl->addRow(tr("Arguments:"), argumentsLineEdit);
m_workingDirectoryEdit = new Utils::PathChooser();
m_workingDirectoryEdit->setPath(m_cmakeRunConfiguration->workingDirectory());
m_workingDirectoryEdit->setExpectedKind(Utils::PathChooser::Directory);
m_workingDirectoryEdit->setPromptDialogTitle(tr("Select the working directory"));
QToolButton *resetButton = new QToolButton();
resetButton->setToolTip(tr("Reset to default"));
resetButton->setIcon(QIcon(":/core/images/reset.png"));
QHBoxLayout *boxlayout = new QHBoxLayout();
boxlayout->addWidget(m_workingDirectoryEdit);
boxlayout->addWidget(resetButton);
fl->addRow(tr("Working Directory:"), boxlayout);
m_detailsContainer = new Utils::DetailsWidget(this);
QWidget *m_details = new QWidget(m_detailsContainer);
m_detailsContainer->setWidget(m_details);
m_details->setLayout(fl);
QVBoxLayout *vbx = new QVBoxLayout(this);
vbx->setMargin(0);;
vbx->addWidget(m_detailsContainer);
QLabel *environmentLabel = new QLabel(this);
environmentLabel->setText(tr("Run Environment"));
QFont f = environmentLabel->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() *1.2);
environmentLabel->setFont(f);
vbx->addWidget(environmentLabel);
QWidget *baseEnvironmentWidget = new QWidget;
QHBoxLayout *baseEnvironmentLayout = new QHBoxLayout(baseEnvironmentWidget);
baseEnvironmentLayout->setMargin(0);
QLabel *label = new QLabel(tr("Base environment for this runconfiguration:"), this);
baseEnvironmentLayout->addWidget(label);
m_baseEnvironmentComboBox = new QComboBox(this);
m_baseEnvironmentComboBox->addItems(QStringList()
<< tr("Clean Environment")
<< tr("System Environment")
<< tr("Build Environment"));
m_baseEnvironmentComboBox->setCurrentIndex(m_cmakeRunConfiguration->baseEnvironmentBase());
connect(m_baseEnvironmentComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(baseEnvironmentComboBoxChanged(int)));
baseEnvironmentLayout->addWidget(m_baseEnvironmentComboBox);
baseEnvironmentLayout->addStretch(10);
m_environmentWidget = new ProjectExplorer::EnvironmentWidget(this, baseEnvironmentWidget);
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
m_environmentWidget->setUserChanges(m_cmakeRunConfiguration->userEnvironmentChanges());
vbx->addWidget(m_environmentWidget);
updateSummary();
connect(m_workingDirectoryEdit, SIGNAL(changed(QString)),
this, SLOT(setWorkingDirectory()));
connect(resetButton, SIGNAL(clicked()),
this, SLOT(resetWorkingDirectory()));
connect(m_environmentWidget, SIGNAL(userChangesUpdated()),
this, SLOT(userChangesUpdated()));
connect(m_cmakeRunConfiguration, SIGNAL(workingDirectoryChanged(QString)),
this, SLOT(workingDirectoryChanged(QString)));
connect(m_cmakeRunConfiguration, SIGNAL(baseEnvironmentChanged()),
this, SLOT(baseEnvironmentChanged()));
connect(m_cmakeRunConfiguration, SIGNAL(userEnvironmentChangesChanged(QList<ProjectExplorer::EnvironmentItem>)),
this, SLOT(userEnvironmentChangesChanged()));
}
void CMakeRunConfigurationWidget::setWorkingDirectory()
{
if (m_ignoreChange)
return;
m_ignoreChange = true;
m_cmakeRunConfiguration->setUserWorkingDirectory(m_workingDirectoryEdit->path());
m_ignoreChange = false;
}
void CMakeRunConfigurationWidget::workingDirectoryChanged(const QString &workingDirectory)
{
if (!m_ignoreChange)
m_workingDirectoryEdit->setPath(workingDirectory);
}
void CMakeRunConfigurationWidget::resetWorkingDirectory()
{
// This emits a signal connected to workingDirectoryChanged()
// that sets the m_workingDirectoryEdit
m_cmakeRunConfiguration->setUserWorkingDirectory("");
}
void CMakeRunConfigurationWidget::userChangesUpdated()
{
m_cmakeRunConfiguration->setUserEnvironmentChanges(m_environmentWidget->userChanges());
}
void CMakeRunConfigurationWidget::baseEnvironmentComboBoxChanged(int index)
{
m_ignoreChange = true;
m_cmakeRunConfiguration->setBaseEnvironmentBase(CMakeRunConfiguration::BaseEnvironmentBase(index));
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
m_ignoreChange = false;
}
void CMakeRunConfigurationWidget::baseEnvironmentChanged()
{
if (m_ignoreChange)
return;
m_baseEnvironmentComboBox->setCurrentIndex(m_cmakeRunConfiguration->baseEnvironmentBase());
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
}
void CMakeRunConfigurationWidget::userEnvironmentChangesChanged()
{
m_environmentWidget->setUserChanges(m_cmakeRunConfiguration->userEnvironmentChanges());
}
void CMakeRunConfigurationWidget::setArguments(const QString &args)
{
m_cmakeRunConfiguration->setArguments(args);
updateSummary();
}
void CMakeRunConfigurationWidget::updateSummary()
{
QString text = tr("Running executable: <b>%1</b> %2")
.arg(QFileInfo(m_cmakeRunConfiguration->executable()).fileName(),
ProjectExplorer::Environment::joinArgumentList(m_cmakeRunConfiguration->commandLineArguments()));
m_detailsContainer->setSummaryText(text);
}
// Factory
CMakeRunConfigurationFactory::CMakeRunConfigurationFactory()
{
}
CMakeRunConfigurationFactory::~CMakeRunConfigurationFactory()
{
}
// used to recreate the runConfigurations when restoring settings
bool CMakeRunConfigurationFactory::canRestore(const QString &type) const
{
if (type.startsWith(Constants::CMAKERUNCONFIGURATION))
return true;
return false;
}
// used to show the list of possible additons to a project, returns a list of types
QStringList CMakeRunConfigurationFactory::availableCreationTypes(ProjectExplorer::Project *project) const
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
if (!pro)
return QStringList();
QStringList allTargets = pro->targets();
for (int i=0; i<allTargets.size(); ++i) {
allTargets[i] = Constants::CMAKERUNCONFIGURATION + allTargets[i];
}
return allTargets;
}
// used to translate the types to names to display to the user
QString CMakeRunConfigurationFactory::displayNameForType(const QString &type) const
{
Q_ASSERT(type.startsWith(Constants::CMAKERUNCONFIGURATION));
if (type == Constants::CMAKERUNCONFIGURATION)
return "CMake"; // Doesn't happen
else
return type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
}
ProjectExplorer::RunConfiguration* CMakeRunConfigurationFactory::create(ProjectExplorer::Project *project, const QString &type)
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
Q_ASSERT(pro);
if (type == Constants::CMAKERUNCONFIGURATION) {
// Restoring, filename will be added by restoreSettings
ProjectExplorer::RunConfiguration* rc = new CMakeRunConfiguration(pro, QString::null, QString::null, QString::null);
return rc;
} else {
// Adding new
const QString title = type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
const CMakeTarget &ct = pro->targetForTitle(title);
ProjectExplorer::RunConfiguration * rc = new CMakeRunConfiguration(pro, ct.executable, ct.workingDirectory, ct.title);
return rc;
}
}
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cmakerunconfiguration.h"
#include "cmakeproject.h"
#include "cmakebuildconfiguration.h"
#include "cmakeprojectconstants.h"
#include <projectexplorer/environment.h>
#include <projectexplorer/debugginghelper.h>
#include <utils/qtcassert.h>
#include <QtGui/QFormLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QGroupBox>
#include <QtGui/QLabel>
#include <QtGui/QComboBox>
#include <QtGui/QToolButton>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
CMakeRunConfiguration::CMakeRunConfiguration(CMakeProject *pro, const QString &target, const QString &workingDirectory, const QString &title)
: ProjectExplorer::LocalApplicationRunConfiguration(pro)
, m_runMode(Gui)
, m_target(target)
, m_workingDirectory(workingDirectory)
, m_title(title)
, m_baseEnvironmentBase(CMakeRunConfiguration::BuildEnvironmentBase)
{
setName(title);
connect(pro, SIGNAL(activeBuildConfigurationChanged()),
this, SIGNAL(baseEnvironmentChanged()));
// TODO
// connect(pro, SIGNAL(environmentChanged(ProjectExplorer::BuildConfiguration *)),
// this, SIGNAL(baseEnvironmentChanged()));
}
CMakeRunConfiguration::~CMakeRunConfiguration()
{
}
CMakeProject *CMakeRunConfiguration::cmakeProject() const
{
return static_cast<CMakeProject *>(project());
}
QString CMakeRunConfiguration::type() const
{
return Constants::CMAKERUNCONFIGURATION;
}
QString CMakeRunConfiguration::executable() const
{
return m_target;
}
ProjectExplorer::LocalApplicationRunConfiguration::RunMode CMakeRunConfiguration::runMode() const
{
return m_runMode;
}
QString CMakeRunConfiguration::workingDirectory() const
{
if (!m_userWorkingDirectory.isEmpty())
return m_userWorkingDirectory;
return m_workingDirectory;
}
QStringList CMakeRunConfiguration::commandLineArguments() const
{
return ProjectExplorer::Environment::parseCombinedArgString(m_arguments);
}
QString CMakeRunConfiguration::title() const
{
return m_title;
}
void CMakeRunConfiguration::setExecutable(const QString &executable)
{
m_target = executable;
}
void CMakeRunConfiguration::setWorkingDirectory(const QString &wd)
{
const QString & oldWorkingDirectory = workingDirectory();
m_workingDirectory = wd;
const QString &newWorkingDirectory = workingDirectory();
if (oldWorkingDirectory != newWorkingDirectory)
emit workingDirectoryChanged(newWorkingDirectory);
}
void CMakeRunConfiguration::setUserWorkingDirectory(const QString &wd)
{
const QString & oldWorkingDirectory = workingDirectory();
m_userWorkingDirectory = wd;
const QString &newWorkingDirectory = workingDirectory();
if (oldWorkingDirectory != newWorkingDirectory)
emit workingDirectoryChanged(newWorkingDirectory);
}
void CMakeRunConfiguration::save(ProjectExplorer::PersistentSettingsWriter &writer) const
{
ProjectExplorer::LocalApplicationRunConfiguration::save(writer);
writer.saveValue("CMakeRunConfiguration.Target", m_target);
writer.saveValue("CMakeRunConfiguration.WorkingDirectory", m_workingDirectory);
writer.saveValue("CMakeRunConfiguration.UserWorkingDirectory", m_userWorkingDirectory);
writer.saveValue("CMakeRunConfiguration.UseTerminal", m_runMode == Console);
writer.saveValue("CMakeRunConfiguation.Title", m_title);
writer.saveValue("CMakeRunConfiguration.Arguments", m_arguments);
writer.saveValue("CMakeRunConfiguration.UserEnvironmentChanges", ProjectExplorer::EnvironmentItem::toStringList(m_userEnvironmentChanges));
writer.saveValue("BaseEnvironmentBase", m_baseEnvironmentBase);
}
void CMakeRunConfiguration::restore(const ProjectExplorer::PersistentSettingsReader &reader)
{
ProjectExplorer::LocalApplicationRunConfiguration::restore(reader);
m_target = reader.restoreValue("CMakeRunConfiguration.Target").toString();
m_workingDirectory = reader.restoreValue("CMakeRunConfiguration.WorkingDirectory").toString();
m_userWorkingDirectory = reader.restoreValue("CMakeRunConfiguration.UserWorkingDirectory").toString();
m_runMode = reader.restoreValue("CMakeRunConfiguration.UseTerminal").toBool() ? Console : Gui;
m_title = reader.restoreValue("CMakeRunConfiguation.Title").toString();
m_arguments = reader.restoreValue("CMakeRunConfiguration.Arguments").toString();
m_userEnvironmentChanges = ProjectExplorer::EnvironmentItem::fromStringList(reader.restoreValue("CMakeRunConfiguration.UserEnvironmentChanges").toStringList());
QVariant tmp = reader.restoreValue("BaseEnvironmentBase");
m_baseEnvironmentBase = tmp.isValid() ? BaseEnvironmentBase(tmp.toInt()) : CMakeRunConfiguration::BuildEnvironmentBase;
}
QWidget *CMakeRunConfiguration::configurationWidget()
{
return new CMakeRunConfigurationWidget(this);
}
void CMakeRunConfiguration::setArguments(const QString &newText)
{
m_arguments = newText;
}
QString CMakeRunConfiguration::dumperLibrary() const
{
QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt(environment());
QString qtInstallData = ProjectExplorer::DebuggingHelperLibrary::qtInstallDataDir(qmakePath);
QString dhl = ProjectExplorer::DebuggingHelperLibrary::debuggingHelperLibraryByInstallData(qtInstallData);
return dhl;
}
QStringList CMakeRunConfiguration::dumperLibraryLocations() const
{
QString qmakePath = ProjectExplorer::DebuggingHelperLibrary::findSystemQt(environment());
QString qtInstallData = ProjectExplorer::DebuggingHelperLibrary::qtInstallDataDir(qmakePath);
return ProjectExplorer::DebuggingHelperLibrary::debuggingHelperLibraryLocationsByInstallData(qtInstallData);
}
ProjectExplorer::Environment CMakeRunConfiguration::baseEnvironment() const
{
ProjectExplorer::Environment env;
if (m_baseEnvironmentBase == CMakeRunConfiguration::CleanEnvironmentBase) {
// Nothing
} else if (m_baseEnvironmentBase == CMakeRunConfiguration::SystemEnvironmentBase) {
env = ProjectExplorer::Environment::systemEnvironment();
} else if (m_baseEnvironmentBase == CMakeRunConfiguration::BuildEnvironmentBase) {
env = project()->activeBuildConfiguration()->environment();
}
return env;
}
void CMakeRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env)
{
if (m_baseEnvironmentBase == env)
return;
m_baseEnvironmentBase = env;
emit baseEnvironmentChanged();
}
CMakeRunConfiguration::BaseEnvironmentBase CMakeRunConfiguration::baseEnvironmentBase() const
{
return m_baseEnvironmentBase;
}
ProjectExplorer::Environment CMakeRunConfiguration::environment() const
{
ProjectExplorer::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
QList<ProjectExplorer::EnvironmentItem> CMakeRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void CMakeRunConfiguration::setUserEnvironmentChanges(const QList<ProjectExplorer::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
emit userEnvironmentChangesChanged(diff);
}
}
ProjectExplorer::ToolChain::ToolChainType CMakeRunConfiguration::toolChainType() const
{
CMakeBuildConfiguration *bc = cmakeProject()->activeCMakeBuildConfiguration();
return bc->toolChainType();
}
// Configuration widget
CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *cmakeRunConfiguration, QWidget *parent)
: QWidget(parent), m_ignoreChange(false), m_cmakeRunConfiguration(cmakeRunConfiguration)
{
QFormLayout *fl = new QFormLayout();
fl->setMargin(0);
fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
QLineEdit *argumentsLineEdit = new QLineEdit();
argumentsLineEdit->setText(ProjectExplorer::Environment::joinArgumentList(cmakeRunConfiguration->commandLineArguments()));
connect(argumentsLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(setArguments(QString)));
fl->addRow(tr("Arguments:"), argumentsLineEdit);
m_workingDirectoryEdit = new Utils::PathChooser();
m_workingDirectoryEdit->setPath(m_cmakeRunConfiguration->workingDirectory());
m_workingDirectoryEdit->setExpectedKind(Utils::PathChooser::Directory);
m_workingDirectoryEdit->setPromptDialogTitle(tr("Select the working directory"));
QToolButton *resetButton = new QToolButton();
resetButton->setToolTip(tr("Reset to default"));
resetButton->setIcon(QIcon(":/core/images/reset.png"));
QHBoxLayout *boxlayout = new QHBoxLayout();
boxlayout->addWidget(m_workingDirectoryEdit);
boxlayout->addWidget(resetButton);
fl->addRow(tr("Working Directory:"), boxlayout);
m_detailsContainer = new Utils::DetailsWidget(this);
QWidget *m_details = new QWidget(m_detailsContainer);
m_detailsContainer->setWidget(m_details);
m_details->setLayout(fl);
QVBoxLayout *vbx = new QVBoxLayout(this);
vbx->setMargin(0);;
vbx->addWidget(m_detailsContainer);
QLabel *environmentLabel = new QLabel(this);
environmentLabel->setText(tr("Run Environment"));
QFont f = environmentLabel->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() *1.2);
environmentLabel->setFont(f);
vbx->addWidget(environmentLabel);
QWidget *baseEnvironmentWidget = new QWidget;
QHBoxLayout *baseEnvironmentLayout = new QHBoxLayout(baseEnvironmentWidget);
baseEnvironmentLayout->setMargin(0);
QLabel *label = new QLabel(tr("Base environment for this runconfiguration:"), this);
baseEnvironmentLayout->addWidget(label);
m_baseEnvironmentComboBox = new QComboBox(this);
m_baseEnvironmentComboBox->addItems(QStringList()
<< tr("Clean Environment")
<< tr("System Environment")
<< tr("Build Environment"));
m_baseEnvironmentComboBox->setCurrentIndex(m_cmakeRunConfiguration->baseEnvironmentBase());
connect(m_baseEnvironmentComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(baseEnvironmentComboBoxChanged(int)));
baseEnvironmentLayout->addWidget(m_baseEnvironmentComboBox);
baseEnvironmentLayout->addStretch(10);
m_environmentWidget = new ProjectExplorer::EnvironmentWidget(this, baseEnvironmentWidget);
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
m_environmentWidget->setUserChanges(m_cmakeRunConfiguration->userEnvironmentChanges());
vbx->addWidget(m_environmentWidget);
updateSummary();
connect(m_workingDirectoryEdit, SIGNAL(changed(QString)),
this, SLOT(setWorkingDirectory()));
connect(resetButton, SIGNAL(clicked()),
this, SLOT(resetWorkingDirectory()));
connect(m_environmentWidget, SIGNAL(userChangesUpdated()),
this, SLOT(userChangesUpdated()));
connect(m_cmakeRunConfiguration, SIGNAL(workingDirectoryChanged(QString)),
this, SLOT(workingDirectoryChanged(QString)));
connect(m_cmakeRunConfiguration, SIGNAL(baseEnvironmentChanged()),
this, SLOT(baseEnvironmentChanged()));
connect(m_cmakeRunConfiguration, SIGNAL(userEnvironmentChangesChanged(QList<ProjectExplorer::EnvironmentItem>)),
this, SLOT(userEnvironmentChangesChanged()));
}
void CMakeRunConfigurationWidget::setWorkingDirectory()
{
if (m_ignoreChange)
return;
m_ignoreChange = true;
m_cmakeRunConfiguration->setUserWorkingDirectory(m_workingDirectoryEdit->path());
m_ignoreChange = false;
}
void CMakeRunConfigurationWidget::workingDirectoryChanged(const QString &workingDirectory)
{
if (!m_ignoreChange)
m_workingDirectoryEdit->setPath(workingDirectory);
}
void CMakeRunConfigurationWidget::resetWorkingDirectory()
{
// This emits a signal connected to workingDirectoryChanged()
// that sets the m_workingDirectoryEdit
m_cmakeRunConfiguration->setUserWorkingDirectory("");
}
void CMakeRunConfigurationWidget::userChangesUpdated()
{
m_cmakeRunConfiguration->setUserEnvironmentChanges(m_environmentWidget->userChanges());
}
void CMakeRunConfigurationWidget::baseEnvironmentComboBoxChanged(int index)
{
m_ignoreChange = true;
m_cmakeRunConfiguration->setBaseEnvironmentBase(CMakeRunConfiguration::BaseEnvironmentBase(index));
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
m_ignoreChange = false;
}
void CMakeRunConfigurationWidget::baseEnvironmentChanged()
{
if (m_ignoreChange)
return;
m_baseEnvironmentComboBox->setCurrentIndex(m_cmakeRunConfiguration->baseEnvironmentBase());
m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
}
void CMakeRunConfigurationWidget::userEnvironmentChangesChanged()
{
m_environmentWidget->setUserChanges(m_cmakeRunConfiguration->userEnvironmentChanges());
}
void CMakeRunConfigurationWidget::setArguments(const QString &args)
{
m_cmakeRunConfiguration->setArguments(args);
updateSummary();
}
void CMakeRunConfigurationWidget::updateSummary()
{
QString text = tr("Running executable: <b>%1</b> %2")
.arg(QFileInfo(m_cmakeRunConfiguration->executable()).fileName(),
ProjectExplorer::Environment::joinArgumentList(m_cmakeRunConfiguration->commandLineArguments()));
m_detailsContainer->setSummaryText(text);
}
// Factory
CMakeRunConfigurationFactory::CMakeRunConfigurationFactory()
{
}
CMakeRunConfigurationFactory::~CMakeRunConfigurationFactory()
{
}
// used to recreate the runConfigurations when restoring settings
bool CMakeRunConfigurationFactory::canRestore(const QString &type) const
{
if (type.startsWith(Constants::CMAKERUNCONFIGURATION))
return true;
return false;
}
// used to show the list of possible additons to a project, returns a list of types
QStringList CMakeRunConfigurationFactory::availableCreationTypes(ProjectExplorer::Project *project) const
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
if (!pro)
return QStringList();
QStringList allTargets = pro->targets();
for (int i=0; i<allTargets.size(); ++i) {
allTargets[i] = Constants::CMAKERUNCONFIGURATION + allTargets[i];
}
return allTargets;
}
// used to translate the types to names to display to the user
QString CMakeRunConfigurationFactory::displayNameForType(const QString &type) const
{
Q_ASSERT(type.startsWith(Constants::CMAKERUNCONFIGURATION));
if (type == Constants::CMAKERUNCONFIGURATION)
return "CMake"; // Doesn't happen
else
return type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
}
ProjectExplorer::RunConfiguration* CMakeRunConfigurationFactory::create(ProjectExplorer::Project *project, const QString &type)
{
CMakeProject *pro = qobject_cast<CMakeProject *>(project);
Q_ASSERT(pro);
if (type == Constants::CMAKERUNCONFIGURATION) {
// Restoring, filename will be added by restoreSettings
ProjectExplorer::RunConfiguration* rc = new CMakeRunConfiguration(pro, QString::null, QString::null, QString::null);
return rc;
} else {
// Adding new
const QString title = type.mid(QString(Constants::CMAKERUNCONFIGURATION).length());
const CMakeTarget &ct = pro->targetForTitle(title);
ProjectExplorer::RunConfiguration * rc = new CMakeRunConfiguration(pro, ct.executable, ct.workingDirectory, ct.title);
return rc;
}
}
|
Fix endless recursion, broken somewhere in the buildconfiguration port
|
Fix endless recursion, broken somewhere in the buildconfiguration port
|
C++
|
lgpl-2.1
|
hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,AltarBeastiful/qt-creator,hdweiss/qt-creator-visualizer,jonnor/qt-creator,ostash/qt-creator-i18n-uk,richardmg/qtcreator,amyvmiwei/qt-creator,bakaiadam/collaborative_qt_creator,azat/qtcreator,martyone/sailfish-qtcreator,azat/qtcreator,Distrotech/qtcreator,colede/qtcreator,malikcjm/qtcreator,ostash/qt-creator-i18n-uk,pcacjr/qt-creator,KDE/android-qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,sandsmark/qtcreator-minimap,jonnor/qt-creator,xianian/qt-creator,darksylinc/qt-creator,syntheticpp/qt-creator,syntheticpp/qt-creator,jonnor/qt-creator,enricoros/k-qt-creator-inspector,xianian/qt-creator,danimo/qt-creator,hdweiss/qt-creator-visualizer,farseerri/git_code,xianian/qt-creator,kuba1/qtcreator,duythanhphan/qt-creator,danimo/qt-creator,azat/qtcreator,danimo/qt-creator,xianian/qt-creator,sandsmark/qtcreator-minimap,maui-packages/qt-creator,azat/qtcreator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,jonnor/qt-creator,danimo/qt-creator,kuba1/qtcreator,enricoros/k-qt-creator-inspector,KDAB/KDAB-Creator,farseerri/git_code,duythanhphan/qt-creator,KDE/android-qt-creator,farseerri/git_code,azat/qtcreator,renatofilho/QtCreator,danimo/qt-creator,kuba1/qtcreator,dmik/qt-creator-os2,pcacjr/qt-creator,richardmg/qtcreator,maui-packages/qt-creator,danimo/qt-creator,omniacreator/qtcreator,syntheticpp/qt-creator,danimo/qt-creator,KDAB/KDAB-Creator,pcacjr/qt-creator,KDAB/KDAB-Creator,renatofilho/QtCreator,KDE/android-qt-creator,darksylinc/qt-creator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,malikcjm/qtcreator,sandsmark/qtcreator-minimap,hdweiss/qt-creator-visualizer,farseerri/git_code,maui-packages/qt-creator,AltarBeastiful/qt-creator,richardmg/qtcreator,xianian/qt-creator,duythanhphan/qt-creator,darksylinc/qt-creator,dmik/qt-creator-os2,KDE/android-qt-creator,KDE/android-qt-creator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,darksylinc/qt-creator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,dmik/qt-creator-os2,danimo/qt-creator,syntheticpp/qt-creator,omniacreator/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,colede/qtcreator,danimo/qt-creator,Distrotech/qtcreator,sandsmark/qtcreator-minimap,amyvmiwei/qt-creator,bakaiadam/collaborative_qt_creator,richardmg/qtcreator,xianian/qt-creator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,enricoros/k-qt-creator-inspector,omniacreator/qtcreator,jonnor/qt-creator,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,kuba1/qtcreator,bakaiadam/collaborative_qt_creator,AltarBeastiful/qt-creator,duythanhphan/qt-creator,AltarBeastiful/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,KDAB/KDAB-Creator,kuba1/qtcreator,maui-packages/qt-creator,yinyunqiao/qtcreator,enricoros/k-qt-creator-inspector,kuba1/qtcreator,dmik/qt-creator-os2,pcacjr/qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,darksylinc/qt-creator,colede/qtcreator,amyvmiwei/qt-creator,azat/qtcreator,duythanhphan/qt-creator,amyvmiwei/qt-creator,pcacjr/qt-creator,yinyunqiao/qtcreator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,duythanhphan/qt-creator,Distrotech/qtcreator,darksylinc/qt-creator,enricoros/k-qt-creator-inspector,omniacreator/qtcreator,yinyunqiao/qtcreator,Distrotech/qtcreator,yinyunqiao/qtcreator,Distrotech/qtcreator,omniacreator/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,maui-packages/qt-creator,omniacreator/qtcreator,sandsmark/qtcreator-minimap,dmik/qt-creator-os2,yinyunqiao/qtcreator,pcacjr/qt-creator,renatofilho/QtCreator,pcacjr/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,KDE/android-qt-creator,yinyunqiao/qtcreator,KDE/android-qt-creator,syntheticpp/qt-creator,ostash/qt-creator-i18n-uk,farseerri/git_code,colede/qtcreator,hdweiss/qt-creator-visualizer,colede/qtcreator,ostash/qt-creator-i18n-uk,enricoros/k-qt-creator-inspector,richardmg/qtcreator,enricoros/k-qt-creator-inspector,duythanhphan/qt-creator,malikcjm/qtcreator,farseerri/git_code,renatofilho/QtCreator,richardmg/qtcreator,darksylinc/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,kuba1/qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,darksylinc/qt-creator,renatofilho/QtCreator,amyvmiwei/qt-creator,colede/qtcreator,colede/qtcreator,yinyunqiao/qtcreator,sandsmark/qtcreator-minimap,xianian/qt-creator,jonnor/qt-creator,renatofilho/QtCreator,kuba1/qtcreator,maui-packages/qt-creator,farseerri/git_code,omniacreator/qtcreator
|
e18d0496876407d3a0e511e273815d16a3a36b4b
|
src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
|
src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "targetsetuppage.h"
#include "ui_targetsetuppage.h"
#include "buildconfigurationinfo.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4target.h"
#include "qtversionmanager.h"
#include "qt4basetargetfactory.h"
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
using namespace Qt4ProjectManager;
TargetSetupPage::TargetSetupPage(QWidget *parent) :
QWizardPage(parent),
m_preferMobile(false),
m_importSearch(false),
m_spacer(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)),
m_ui(new Internal::Ui::TargetSetupPage)
{
m_ui->setupUi(this);
QWidget *centralWidget = new QWidget(this);
m_ui->scrollArea->setWidget(centralWidget);
m_layout = new QVBoxLayout;
centralWidget->setLayout(m_layout);
m_layout->addSpacerItem(m_spacer);
setTitle(tr("Target setup"));
}
void TargetSetupPage::initializePage()
{
cleanupImportInfos();
deleteWidgets();
setupImportInfos();
setupWidgets();
}
TargetSetupPage::~TargetSetupPage()
{
deleteWidgets();
delete m_ui;
cleanupImportInfos();
}
bool TargetSetupPage::isTargetSelected(const QString &id) const
{
Qt4TargetSetupWidget *widget = m_widgets.value(id);
return widget && widget->isTargetSelected();
}
bool TargetSetupPage::isComplete() const
{
foreach (Qt4TargetSetupWidget *widget, m_widgets)
if (widget->isTargetSelected())
return true;
return false;
}
void TargetSetupPage::setPreferMobile(bool mobile)
{
m_preferMobile = mobile;
}
void TargetSetupPage::setMinimumQtVersion(const QtVersionNumber &number)
{
m_minimumQtVersionNumber = number;
}
void TargetSetupPage::setImportSearch(bool b)
{
m_importSearch = b;
}
void TargetSetupPage::setupWidgets()
{
QList<Qt4BaseTargetFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<Qt4BaseTargetFactory>();
foreach (Qt4BaseTargetFactory *factory, factories) {
QStringList ids = factory->supportedTargetIds(0);
foreach (const QString &id, ids) {
QList<BuildConfigurationInfo> infos = BuildConfigurationInfo::filterBuildConfigurationInfos(m_importInfos, id);
Qt4TargetSetupWidget *widget =
factory->createTargetSetupWidget(id, m_proFilePath, m_minimumQtVersionNumber, m_importSearch, infos);
if (widget) {
widget->setTargetSelected( (m_preferMobile == factory->isMobileTarget(id) && m_importInfos.isEmpty())
|| !infos.isEmpty());
m_widgets.insert(id, widget);
m_factories.insert(widget, factory);
m_layout->addWidget(widget);
connect(widget, SIGNAL(selectedToggled()),
this, SIGNAL(completeChanged()));
connect(widget, SIGNAL(newImportBuildConfiguration(BuildConfigurationInfo)),
this, SLOT(newImportBuildConfiguration(BuildConfigurationInfo)));
}
}
}
m_layout->addSpacerItem(m_spacer);
if (m_widgets.isEmpty()) {
// Oh no one can create any targets
m_ui->scrollArea->setVisible(false);
m_ui->descriptionLabel->setVisible(false);
m_ui->noValidQtVersionsLabel->setVisible(true);
} else {
m_ui->scrollArea->setVisible(true);
m_ui->descriptionLabel->setVisible(true);
m_ui->noValidQtVersionsLabel->setVisible(false);
}
}
void TargetSetupPage::deleteWidgets()
{
foreach (Qt4TargetSetupWidget *widget, m_widgets)
delete widget;
m_widgets.clear();
m_factories.clear();
m_layout->removeItem(m_spacer);
}
void TargetSetupPage::setProFilePath(const QString &path)
{
m_proFilePath = path;
if (!m_proFilePath.isEmpty()) {
m_ui->descriptionLabel->setText(tr("Qt Creator can set up the following targets for project <b>%1</b>:",
"%1: Project name").arg(QFileInfo(m_proFilePath).baseName()));
}
deleteWidgets();
setupWidgets();
}
void TargetSetupPage::setupImportInfos()
{
if (m_importSearch)
m_importInfos = BuildConfigurationInfo::importBuildConfigurations(m_proFilePath);
}
void TargetSetupPage::cleanupImportInfos()
{
foreach (const BuildConfigurationInfo &info, m_importInfos) {
if (info.temporaryQtVersion)
delete info.version;
}
}
void TargetSetupPage::newImportBuildConfiguration(const BuildConfigurationInfo &info)
{
m_importInfos.append(info);
}
bool TargetSetupPage::setupProject(Qt4ProjectManager::Qt4Project *project)
{
QMap<QString, Qt4TargetSetupWidget *>::const_iterator it, end;
end = m_widgets.constEnd();
it = m_widgets.constBegin();
for ( ; it != end; ++it) {
Qt4BaseTargetFactory *factory = m_factories.value(it.value());
foreach (const BuildConfigurationInfo &info, it.value()->usedImportInfos()) {
QtVersion *version = info.version;
for (int i=0; i < m_importInfos.size(); ++i) {
if (m_importInfos.at(i).version == version) {
if (m_importInfos[i].temporaryQtVersion) {
QtVersionManager::instance()->addVersion(m_importInfos[i].version);
m_importInfos[i].temporaryQtVersion = false;
}
}
}
}
if (ProjectExplorer::Target *target = factory->create(project, it.key(), it.value()))
project->addTarget(target);
}
// Create a desktop target if nothing else was set up:
if (project->targets().isEmpty()) {
if (Qt4BaseTargetFactory *tf = Qt4BaseTargetFactory::qt4BaseTargetFactoryForId(Constants::DESKTOP_TARGET_ID))
if (ProjectExplorer::Target *target = tf->create(project, Constants::DESKTOP_TARGET_ID))
project->addTarget(target);
}
// Select active target
// a) Simulator target
// b) Desktop target
// c) the first target
ProjectExplorer::Target *activeTarget = 0;
QList<ProjectExplorer::Target *> targets = project->targets();
foreach (ProjectExplorer::Target *t, targets) {
if (t->id() == Constants::QT_SIMULATOR_TARGET_ID)
activeTarget = t;
else if (!activeTarget && t->id() == Constants::DESKTOP_TARGET_ID)
activeTarget = t;
}
if (!activeTarget && !targets.isEmpty())
activeTarget = targets.first();
if (activeTarget)
project->setActiveTarget(activeTarget);
return !project->targets().isEmpty();
}
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "targetsetuppage.h"
#include "ui_targetsetuppage.h"
#include "buildconfigurationinfo.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4target.h"
#include "qtversionmanager.h"
#include "qt4basetargetfactory.h"
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
using namespace Qt4ProjectManager;
TargetSetupPage::TargetSetupPage(QWidget *parent) :
QWizardPage(parent),
m_preferMobile(false),
m_importSearch(false),
m_spacer(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)),
m_ui(new Internal::Ui::TargetSetupPage)
{
m_ui->setupUi(this);
QWidget *centralWidget = new QWidget(this);
m_ui->scrollArea->setWidget(centralWidget);
m_layout = new QVBoxLayout;
centralWidget->setLayout(m_layout);
m_layout->addSpacerItem(m_spacer);
setTitle(tr("Target setup"));
}
void TargetSetupPage::initializePage()
{
cleanupImportInfos();
deleteWidgets();
setupImportInfos();
setupWidgets();
}
TargetSetupPage::~TargetSetupPage()
{
deleteWidgets();
delete m_ui;
cleanupImportInfos();
}
bool TargetSetupPage::isTargetSelected(const QString &id) const
{
Qt4TargetSetupWidget *widget = m_widgets.value(id);
return widget && widget->isTargetSelected();
}
bool TargetSetupPage::isComplete() const
{
foreach (Qt4TargetSetupWidget *widget, m_widgets)
if (widget->isTargetSelected())
return true;
return false;
}
void TargetSetupPage::setPreferMobile(bool mobile)
{
m_preferMobile = mobile;
}
void TargetSetupPage::setMinimumQtVersion(const QtVersionNumber &number)
{
m_minimumQtVersionNumber = number;
}
void TargetSetupPage::setImportSearch(bool b)
{
m_importSearch = b;
}
void TargetSetupPage::setupWidgets()
{
QList<Qt4BaseTargetFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<Qt4BaseTargetFactory>();
foreach (Qt4BaseTargetFactory *factory, factories) {
QStringList ids = factory->supportedTargetIds(0);
bool atLeastOneTargetSelected = false;
foreach (const QString &id, ids) {
QList<BuildConfigurationInfo> infos = BuildConfigurationInfo::filterBuildConfigurationInfos(m_importInfos, id);
Qt4TargetSetupWidget *widget =
factory->createTargetSetupWidget(id, m_proFilePath, m_minimumQtVersionNumber, m_importSearch, infos);
if (widget) {
bool selectTarget = (m_preferMobile == factory->isMobileTarget(id) && m_importInfos.isEmpty())
|| !infos.isEmpty();
widget->setTargetSelected(selectTarget) ;
atLeastOneTargetSelected |= selectTarget;
m_widgets.insert(id, widget);
m_factories.insert(widget, factory);
m_layout->addWidget(widget);
connect(widget, SIGNAL(selectedToggled()),
this, SIGNAL(completeChanged()));
connect(widget, SIGNAL(newImportBuildConfiguration(BuildConfigurationInfo)),
this, SLOT(newImportBuildConfiguration(BuildConfigurationInfo)));
}
}
if (!atLeastOneTargetSelected) {
Qt4TargetSetupWidget *widget = m_widgets.value(Constants::DESKTOP_TARGET_ID);
if (widget)
widget->setTargetSelected(true);
}
}
m_layout->addSpacerItem(m_spacer);
if (m_widgets.isEmpty()) {
// Oh no one can create any targets
m_ui->scrollArea->setVisible(false);
m_ui->descriptionLabel->setVisible(false);
m_ui->noValidQtVersionsLabel->setVisible(true);
} else {
m_ui->scrollArea->setVisible(true);
m_ui->descriptionLabel->setVisible(true);
m_ui->noValidQtVersionsLabel->setVisible(false);
}
}
void TargetSetupPage::deleteWidgets()
{
foreach (Qt4TargetSetupWidget *widget, m_widgets)
delete widget;
m_widgets.clear();
m_factories.clear();
m_layout->removeItem(m_spacer);
}
void TargetSetupPage::setProFilePath(const QString &path)
{
m_proFilePath = path;
if (!m_proFilePath.isEmpty()) {
m_ui->descriptionLabel->setText(tr("Qt Creator can set up the following targets for project <b>%1</b>:",
"%1: Project name").arg(QFileInfo(m_proFilePath).baseName()));
}
deleteWidgets();
setupWidgets();
}
void TargetSetupPage::setupImportInfos()
{
if (m_importSearch)
m_importInfos = BuildConfigurationInfo::importBuildConfigurations(m_proFilePath);
}
void TargetSetupPage::cleanupImportInfos()
{
foreach (const BuildConfigurationInfo &info, m_importInfos) {
if (info.temporaryQtVersion)
delete info.version;
}
}
void TargetSetupPage::newImportBuildConfiguration(const BuildConfigurationInfo &info)
{
m_importInfos.append(info);
}
bool TargetSetupPage::setupProject(Qt4ProjectManager::Qt4Project *project)
{
QMap<QString, Qt4TargetSetupWidget *>::const_iterator it, end;
end = m_widgets.constEnd();
it = m_widgets.constBegin();
for ( ; it != end; ++it) {
Qt4BaseTargetFactory *factory = m_factories.value(it.value());
foreach (const BuildConfigurationInfo &info, it.value()->usedImportInfos()) {
QtVersion *version = info.version;
for (int i=0; i < m_importInfos.size(); ++i) {
if (m_importInfos.at(i).version == version) {
if (m_importInfos[i].temporaryQtVersion) {
QtVersionManager::instance()->addVersion(m_importInfos[i].version);
m_importInfos[i].temporaryQtVersion = false;
}
}
}
}
if (ProjectExplorer::Target *target = factory->create(project, it.key(), it.value()))
project->addTarget(target);
}
// Create a desktop target if nothing else was set up:
if (project->targets().isEmpty()) {
if (Qt4BaseTargetFactory *tf = Qt4BaseTargetFactory::qt4BaseTargetFactoryForId(Constants::DESKTOP_TARGET_ID))
if (ProjectExplorer::Target *target = tf->create(project, Constants::DESKTOP_TARGET_ID))
project->addTarget(target);
}
// Select active target
// a) Simulator target
// b) Desktop target
// c) the first target
ProjectExplorer::Target *activeTarget = 0;
QList<ProjectExplorer::Target *> targets = project->targets();
foreach (ProjectExplorer::Target *t, targets) {
if (t->id() == Constants::QT_SIMULATOR_TARGET_ID)
activeTarget = t;
else if (!activeTarget && t->id() == Constants::DESKTOP_TARGET_ID)
activeTarget = t;
}
if (!activeTarget && !targets.isEmpty())
activeTarget = targets.first();
if (activeTarget)
project->setActiveTarget(activeTarget);
return !project->targets().isEmpty();
}
|
Select Desktop target if no other target is there
|
TargetSetupPage: Select Desktop target if no other target is there
Task-Nr: QTCREATORBUG-4100
|
C++
|
lgpl-2.1
|
farseerri/git_code,jonnor/qt-creator,omniacreator/qtcreator,jonnor/qt-creator,darksylinc/qt-creator,azat/qtcreator,dmik/qt-creator-os2,duythanhphan/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,KDE/android-qt-creator,pcacjr/qt-creator,duythanhphan/qt-creator,azat/qtcreator,AltarBeastiful/qt-creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,renatofilho/QtCreator,kuba1/qtcreator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,martyone/sailfish-qtcreator,omniacreator/qtcreator,pcacjr/qt-creator,xianian/qt-creator,AltarBeastiful/qt-creator,duythanhphan/qt-creator,maui-packages/qt-creator,maui-packages/qt-creator,kuba1/qtcreator,xianian/qt-creator,syntheticpp/qt-creator,farseerri/git_code,duythanhphan/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,jonnor/qt-creator,omniacreator/qtcreator,darksylinc/qt-creator,Distrotech/qtcreator,jonnor/qt-creator,colede/qtcreator,danimo/qt-creator,pcacjr/qt-creator,dmik/qt-creator-os2,dmik/qt-creator-os2,maui-packages/qt-creator,farseerri/git_code,Distrotech/qtcreator,KDE/android-qt-creator,KDE/android-qt-creator,KDE/android-qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,xianian/qt-creator,dmik/qt-creator-os2,danimo/qt-creator,KDAB/KDAB-Creator,Distrotech/qtcreator,bakaiadam/collaborative_qt_creator,omniacreator/qtcreator,KDAB/KDAB-Creator,danimo/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,xianian/qt-creator,syntheticpp/qt-creator,darksylinc/qt-creator,bakaiadam/collaborative_qt_creator,renatofilho/QtCreator,amyvmiwei/qt-creator,darksylinc/qt-creator,kuba1/qtcreator,KDAB/KDAB-Creator,dmik/qt-creator-os2,amyvmiwei/qt-creator,KDAB/KDAB-Creator,dmik/qt-creator-os2,ostash/qt-creator-i18n-uk,azat/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,pcacjr/qt-creator,colede/qtcreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,KDAB/KDAB-Creator,darksylinc/qt-creator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,ostash/qt-creator-i18n-uk,kuba1/qtcreator,colede/qtcreator,ostash/qt-creator-i18n-uk,jonnor/qt-creator,ostash/qt-creator-i18n-uk,martyone/sailfish-qtcreator,richardmg/qtcreator,danimo/qt-creator,danimo/qt-creator,duythanhphan/qt-creator,farseerri/git_code,malikcjm/qtcreator,darksylinc/qt-creator,xianian/qt-creator,syntheticpp/qt-creator,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,Distrotech/qtcreator,KDE/android-qt-creator,renatofilho/QtCreator,azat/qtcreator,amyvmiwei/qt-creator,duythanhphan/qt-creator,renatofilho/QtCreator,AltarBeastiful/qt-creator,pcacjr/qt-creator,KDAB/KDAB-Creator,farseerri/git_code,ostash/qt-creator-i18n-uk,amyvmiwei/qt-creator,colede/qtcreator,richardmg/qtcreator,farseerri/git_code,maui-packages/qt-creator,KDE/android-qt-creator,omniacreator/qtcreator,ostash/qt-creator-i18n-uk,renatofilho/QtCreator,xianian/qt-creator,maui-packages/qt-creator,malikcjm/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,renatofilho/QtCreator,farseerri/git_code,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,maui-packages/qt-creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,syntheticpp/qt-creator,danimo/qt-creator,dmik/qt-creator-os2,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,richardmg/qtcreator,malikcjm/qtcreator,richardmg/qtcreator,omniacreator/qtcreator,pcacjr/qt-creator,colede/qtcreator,richardmg/qtcreator,azat/qtcreator,kuba1/qtcreator,colede/qtcreator,KDE/android-qt-creator,omniacreator/qtcreator,azat/qtcreator,xianian/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,hdweiss/qt-creator-visualizer,AltarBeastiful/qt-creator,danimo/qt-creator,KDE/android-qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,martyone/sailfish-qtcreator,hdweiss/qt-creator-visualizer,amyvmiwei/qt-creator,hdweiss/qt-creator-visualizer,duythanhphan/qt-creator,pcacjr/qt-creator,Distrotech/qtcreator
|
cf3d36e6ba24b0fca5608dcc26dc8f4a8b4f34a7
|
src/plugins/support/COMBINESupport/src/combinearchive.cpp
|
src/plugins/support/COMBINESupport/src/combinearchive.cpp
|
/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// COMBINE archive class
//==============================================================================
#include "combinearchive.h"
#include "corecliutils.h"
//==============================================================================
#include <QFile>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTextStream>
//==============================================================================
#include <QZipWriter>
//==============================================================================
namespace OpenCOR {
namespace COMBINESupport {
//==============================================================================
CombineArchiveFile::CombineArchiveFile(const QString &pFileName,
const QString &pLocation,
const Format &pFormat,
const bool &pMaster) :
mFileName(pFileName),
mLocation(pLocation),
mFormat(pFormat),
mMaster(pMaster)
{
}
//==============================================================================
QString CombineArchiveFile::fileName() const
{
// Return our file name
return mFileName;
}
//==============================================================================
QString CombineArchiveFile::location() const
{
// Return our location
return mLocation;
}
//==============================================================================
CombineArchiveFile::Format CombineArchiveFile::format() const
{
// Return our format
return mFormat;
}
//==============================================================================
bool CombineArchiveFile::isMaster() const
{
// Return whether we are a master file
return mMaster;
}
//==============================================================================
CombineArchive::CombineArchive(const QString &pFileName) :
StandardSupport::StandardFile(pFileName),
mDirName(Core::temporaryDirName()),
mCombineArchiveFiles(CombineArchiveFiles())
{
}
//==============================================================================
CombineArchive::~CombineArchive()
{
// Delete our temporary directory
QDir(mDirName).removeRecursively();
}
//==============================================================================
bool CombineArchive::load()
{
// Consider the file not loaded
return false;
}
//==============================================================================
static const auto CellmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/cellml");
static const auto Cellml_1_0_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.0");
static const auto Cellml_1_1_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.1");
static const auto SedmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/sed-ml");
//==============================================================================
bool CombineArchive::save(const QString &pNewFileName)
{
// Keep track of our current directory
QString origPath = QDir::currentPath();
// Create and go to a sub-directory where we are effecitvely going to put
// ourselves
QDir dir;
QString fileName = pNewFileName.isEmpty()?mFileName:pNewFileName;
QString baseDirName = QFileInfo(fileName).baseName();
QString dirName = mDirName+QDir::separator()+baseDirName;
dir.mkpath(dirName);
QDir::setCurrent(dirName);
// Create our manifest file
static const QString ManifestFileName = "manifest.xml";
QString fileList = QString();
QString fileFormat;
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
switch (combineArchiveFile.format()) {
case CombineArchiveFile::Cellml:
fileFormat = CellmlFormat;
break;
case CombineArchiveFile::Cellml_1_0:
fileFormat = Cellml_1_0_Format;
break;
case CombineArchiveFile::Cellml_1_1:
fileFormat = Cellml_1_1_Format;
break;
case CombineArchiveFile::Sedml:
fileFormat = SedmlFormat;
break;
default: // CombineArchiveFile::Unknown
return false;
}
fileList += " <content location=\""+combineArchiveFile.location()+"\" format=\""+fileFormat+"\"";
if (combineArchiveFile.isMaster())
fileList += " master=\"true\"";
fileList += "/>\n";
}
QByteArray manifestFileContents = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<omexManifest xmlns=\"http://identifiers.org/combine.specifications/omex-manifest\">\n"
" <content location=\".\" format=\"http://identifiers.org/combine.specifications/omex\"/>\n"
+fileList.toUtf8()
+"</omexManifest>\n";
if (!Core::writeTextToFile(ManifestFileName, manifestFileContents))
return false;
// Get a copy of our various files, if any, after creating the sub-folder(s)
// in which they are
#if defined(Q_OS_WIN)
static const QRegularExpression FileNameRegEx = QRegularExpression("\\\\[^\\\\]*$");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
static const QRegularExpression FileNameRegEx = QRegularExpression("/[^/]*$");
#else
#error Unsupported platform
#endif
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString destFileName = Core::nativeCanonicalFileName(dirName+QDir::separator()+combineArchiveFile.location());
QString destDirName = QString(destFileName).remove(FileNameRegEx);
if (!QDir(destDirName).exists()) {
if (!dir.mkpath(destDirName))
return false;
}
if (!QFile::copy(combineArchiveFile.fileName(), destFileName))
return false;
}
// Go back to our original path
QDir::setCurrent(origPath);
// Save ourselves to either the given file, which name is given, or to our
// current file
OpenCOR::ZIPSupport::QZipWriter zipWriter(fileName);
zipWriter.addFile(ManifestFileName, manifestFileContents);
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString combineArchiveFileContents;
if (!Core::readTextFromFile(dirName+QDir::separator()+combineArchiveFile.location(), combineArchiveFileContents))
return false;
zipWriter.addFile(combineArchiveFile.location(),
combineArchiveFileContents.toUtf8());
}
zipWriter.close();
return true;
}
//==============================================================================
bool CombineArchive::addFile(const QString &pFileName, const QString &pLocation,
const CombineArchiveFile::Format &pFormat,
const bool &pMaster)
{
// Make sure the format is known
if (pFormat == CombineArchiveFile::Unknown)
return false;
// Add the given file to our list
mCombineArchiveFiles << CombineArchiveFile(pFileName, pLocation, pFormat, pMaster);
return true;
}
//==============================================================================
} // namespace COMBINESupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
|
/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// COMBINE archive class
//==============================================================================
#include "combinearchive.h"
#include "corecliutils.h"
//==============================================================================
#include <QFile>
#include <QRegularExpression>
#include <QTemporaryDir>
#include <QTextStream>
//==============================================================================
#include <QZipWriter>
//==============================================================================
namespace OpenCOR {
namespace COMBINESupport {
//==============================================================================
CombineArchiveFile::CombineArchiveFile(const QString &pFileName,
const QString &pLocation,
const Format &pFormat,
const bool &pMaster) :
mFileName(pFileName),
mLocation(pLocation),
mFormat(pFormat),
mMaster(pMaster)
{
}
//==============================================================================
QString CombineArchiveFile::fileName() const
{
// Return our file name
return mFileName;
}
//==============================================================================
QString CombineArchiveFile::location() const
{
// Return our location
return mLocation;
}
//==============================================================================
CombineArchiveFile::Format CombineArchiveFile::format() const
{
// Return our format
return mFormat;
}
//==============================================================================
bool CombineArchiveFile::isMaster() const
{
// Return whether we are a master file
return mMaster;
}
//==============================================================================
CombineArchive::CombineArchive(const QString &pFileName) :
StandardSupport::StandardFile(pFileName),
mDirName(Core::temporaryDirName()),
mCombineArchiveFiles(CombineArchiveFiles())
{
}
//==============================================================================
CombineArchive::~CombineArchive()
{
// Delete our temporary directory
QDir(mDirName).removeRecursively();
}
//==============================================================================
bool CombineArchive::load()
{
// Consider the file not loaded
return false;
}
//==============================================================================
static const auto CellmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/cellml");
static const auto Cellml_1_0_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.0");
static const auto Cellml_1_1_Format = QStringLiteral("http://identifiers.org/combine.specifications/cellml.1.1");
static const auto SedmlFormat = QStringLiteral("http://identifiers.org/combine.specifications/sed-ml");
//==============================================================================
bool CombineArchive::save(const QString &pNewFileName)
{
// Keep track of our current directory
QString origPath = QDir::currentPath();
// Create and go to a sub-directory where we are effecitvely going to put
// ourselves
QDir dir;
QString fileName = pNewFileName.isEmpty()?mFileName:pNewFileName;
QString dirName = mDirName+QDir::separator()+QFileInfo(fileName).baseName();
dir.mkpath(dirName);
QDir::setCurrent(dirName);
// Create our manifest file
static const QString ManifestFileName = "manifest.xml";
QString fileList = QString();
QString fileFormat;
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
switch (combineArchiveFile.format()) {
case CombineArchiveFile::Cellml:
fileFormat = CellmlFormat;
break;
case CombineArchiveFile::Cellml_1_0:
fileFormat = Cellml_1_0_Format;
break;
case CombineArchiveFile::Cellml_1_1:
fileFormat = Cellml_1_1_Format;
break;
case CombineArchiveFile::Sedml:
fileFormat = SedmlFormat;
break;
default: // CombineArchiveFile::Unknown
return false;
}
fileList += " <content location=\""+combineArchiveFile.location()+"\" format=\""+fileFormat+"\"";
if (combineArchiveFile.isMaster())
fileList += " master=\"true\"";
fileList += "/>\n";
}
QByteArray manifestFileContents = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
"<omexManifest xmlns=\"http://identifiers.org/combine.specifications/omex-manifest\">\n"
" <content location=\".\" format=\"http://identifiers.org/combine.specifications/omex\"/>\n"
+fileList.toUtf8()
+"</omexManifest>\n";
if (!Core::writeTextToFile(ManifestFileName, manifestFileContents))
return false;
// Get a copy of our various files, if any, after creating the sub-folder(s)
// in which they are
#if defined(Q_OS_WIN)
static const QRegularExpression FileNameRegEx = QRegularExpression("\\\\[^\\\\]*$");
#elif defined(Q_OS_LINUX) || defined(Q_OS_MAC)
static const QRegularExpression FileNameRegEx = QRegularExpression("/[^/]*$");
#else
#error Unsupported platform
#endif
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString destFileName = Core::nativeCanonicalFileName(dirName+QDir::separator()+combineArchiveFile.location());
QString destDirName = QString(destFileName).remove(FileNameRegEx);
if (!QDir(destDirName).exists()) {
if (!dir.mkpath(destDirName))
return false;
}
if (!QFile::copy(combineArchiveFile.fileName(), destFileName))
return false;
}
// Go back to our original path
QDir::setCurrent(origPath);
// Save ourselves to either the given file, which name is given, or to our
// current file
OpenCOR::ZIPSupport::QZipWriter zipWriter(fileName);
zipWriter.addFile(ManifestFileName, manifestFileContents);
foreach (const CombineArchiveFile &combineArchiveFile, mCombineArchiveFiles) {
QString combineArchiveFileContents;
if (!Core::readTextFromFile(dirName+QDir::separator()+combineArchiveFile.location(), combineArchiveFileContents))
return false;
zipWriter.addFile(combineArchiveFile.location(),
combineArchiveFileContents.toUtf8());
}
zipWriter.close();
return true;
}
//==============================================================================
bool CombineArchive::addFile(const QString &pFileName, const QString &pLocation,
const CombineArchiveFile::Format &pFormat,
const bool &pMaster)
{
// Make sure the format is known
if (pFormat == CombineArchiveFile::Unknown)
return false;
// Add the given file to our list
mCombineArchiveFiles << CombineArchiveFile(pFileName, pLocation, pFormat, pMaster);
return true;
}
//==============================================================================
} // namespace COMBINESupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
|
COMBINE archive: some work on loading/saving a COMBINE archive [ci skip].
|
COMBINE archive: some work on loading/saving a COMBINE archive [ci skip].
|
C++
|
apache-2.0
|
mirams/opencor,mirams/opencor,mirams/opencor,mirams/opencor,mirams/opencor
|
6348024c2b67b65be0d7945b2e8f3c79a6e673c0
|
hector_quadrotor_teleop/src/quadrotor_teleop.cpp
|
hector_quadrotor_teleop/src/quadrotor_teleop.cpp
|
//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Flight Systems and Automatic Control group,
// TU Darmstadt, 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 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 <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include <hector_uav_msgs/YawrateCommand.h>
#include <hector_uav_msgs/ThrustCommand.h>
#include <hector_uav_msgs/AttitudeCommand.h>
namespace hector_quadrotor
{
class Teleop
{
private:
ros::NodeHandle node_handle_;
ros::Subscriber joy_subscriber_;
ros::Publisher velocity_publisher_, attitude_publisher_, yawrate_publisher_, thrust_publisher_;
geometry_msgs::Twist velocity_;
hector_uav_msgs::AttitudeCommand attitude_;
hector_uav_msgs::ThrustCommand thrust_;
hector_uav_msgs::YawrateCommand yawrate_;
struct Axis
{
int axis;
double max;
};
struct Button
{
int button;
};
struct
{
Axis x;
Axis y;
Axis z;
Axis yaw;
} axes_;
struct
{
Button slow;
} buttons_;
double slow_factor_;
public:
Teleop()
{
ros::NodeHandle params("~");
params.param<int>("x_axis", axes_.x.axis, 4);
params.param<int>("y_axis", axes_.y.axis, 3);
params.param<int>("z_axis", axes_.z.axis, 2);
params.param<int>("yaw_axis", axes_.yaw.axis, 1);
params.param<double>("yaw_velocity_max", axes_.yaw.max, 90.0 * M_PI / 180.0);
params.param<int>("slow_button", buttons_.slow.button, 1);
params.param<double>("slow_factor", slow_factor_, 0.2);
std::string control_mode_str;
params.param<std::string>("control_mode", control_mode_str, "twist");
if (control_mode_str == "twist")
{
params.param<double>("x_velocity_max", axes_.x.max, 2.0);
params.param<double>("y_velocity_max", axes_.y.max, 2.0);
params.param<double>("z_velocity_max", axes_.z.max, 2.0);
joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));
velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
}
else if (control_mode_str == "attitude")
{
params.param<double>("x_roll_max", axes_.x.max, 0.35);
params.param<double>("y_pitch_max", axes_.y.max, 0.35);
params.param<double>("z_thrust_max", axes_.z.max, 25.0);
joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyAttitudeCallback, this, _1));
attitude_publisher_ = node_handle_.advertise<hector_uav_msgs::AttitudeCommand>("command/attitude", 10);
yawrate_publisher_ = node_handle_.advertise<hector_uav_msgs::YawrateCommand>("command/yawrate", 10);
thrust_publisher_ = node_handle_.advertise<hector_uav_msgs::ThrustCommand>("command/thrust", 10);
}
}
~Teleop()
{
stop();
}
void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)
{
velocity_.linear.x = getAxis(joy, axes_.x);
velocity_.linear.y = getAxis(joy, axes_.y);
velocity_.linear.z = getAxis(joy, axes_.z);
velocity_.angular.z = getAxis(joy, axes_.yaw);
if (getButton(joy, buttons_.slow.button))
{
velocity_.linear.x *= slow_factor_;
velocity_.linear.y *= slow_factor_;
velocity_.linear.z *= slow_factor_;
velocity_.angular.z *= slow_factor_;
}
velocity_publisher_.publish(velocity_);
}
void joyAttitudeCallback(const sensor_msgs::JoyConstPtr &joy)
{
attitude_.roll = getAxis(joy, axes_.x);
attitude_.pitch = getAxis(joy, axes_.y);
attitude_publisher_.publish(attitude_);
thrust_.thrust = getAxis(joy, axes_.z);
thrust_publisher_.publish(thrust_);
yawrate_.turnrate = getAxis(joy, axes_.yaw);
if (getButton(joy, buttons_.slow.button))
{
yawrate_.turnrate *= slow_factor_;
}
yawrate_publisher_.publish(yawrate_);
}
sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)
{
if (axis.axis == 0)
{return 0;}
sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
if (axis.axis < 0)
{
sign = -1.0;
axis.axis = -axis.axis;
}
if ((size_t) axis.axis > joy->axes.size())
{return 0;}
return sign * joy->axes[axis.axis - 1] * axis.max;
}
sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)
{
if (button <= 0)
{return 0;}
if ((size_t) button > joy->axes.size())
{return 0;}
return joy->buttons[button - 1];
}
void stop()
{
if(velocity_publisher_.getNumSubscribers() > 0)
{
velocity_ = geometry_msgs::Twist();
velocity_publisher_.publish(velocity_);
}
if(attitude_publisher_.getNumSubscribers() > 0)
{
attitude_ = hector_uav_msgs::AttitudeCommand();
attitude_publisher_.publish(attitude_);
}
if(thrust_publisher_.getNumSubscribers() > 0)
{
thrust_ = hector_uav_msgs::ThrustCommand();
thrust_publisher_.publish(thrust_);
}
if(yawrate_publisher_.getNumSubscribers() > 0)
{
yawrate_ = hector_uav_msgs::YawrateCommand();
yawrate_publisher_.publish(yawrate_);
}
}
};
} // namespace hector_quadrotor
int main(int argc, char **argv)
{
ros::init(argc, argv, "quadrotor_teleop");
hector_quadrotor::Teleop teleop;
ros::spin();
return 0;
}
|
//=================================================================================================
// Copyright (c) 2012, Johannes Meyer, TU Darmstadt
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Flight Systems and Automatic Control group,
// TU Darmstadt, 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 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 <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/Twist.h>
#include <hector_uav_msgs/YawrateCommand.h>
#include <hector_uav_msgs/ThrustCommand.h>
#include <hector_uav_msgs/AttitudeCommand.h>
namespace hector_quadrotor
{
class Teleop
{
private:
ros::NodeHandle node_handle_;
ros::Subscriber joy_subscriber_;
ros::Publisher velocity_publisher_, attitude_publisher_, yawrate_publisher_, thrust_publisher_;
geometry_msgs::Twist velocity_;
hector_uav_msgs::AttitudeCommand attitude_;
hector_uav_msgs::ThrustCommand thrust_;
hector_uav_msgs::YawrateCommand yawrate_;
struct Axis
{
int axis;
double max;
};
struct Button
{
int button;
};
struct
{
Axis x;
Axis y;
Axis z;
Axis yaw;
} axes_;
struct
{
Button slow;
} buttons_;
double slow_factor_;
public:
Teleop()
{
ros::NodeHandle params("~");
params.param<int>("x_axis", axes_.x.axis, 4);
params.param<int>("y_axis", axes_.y.axis, 3);
params.param<int>("z_axis", axes_.z.axis, 2);
params.param<int>("yaw_axis", axes_.yaw.axis, 1);
params.param<double>("yaw_velocity_max", axes_.yaw.max, 90.0 * M_PI / 180.0);
params.param<int>("slow_button", buttons_.slow.button, 1);
params.param<double>("slow_factor", slow_factor_, 0.2);
std::string control_mode_str;
params.param<std::string>("control_mode", control_mode_str, "twist");
if (control_mode_str == "twist")
{
params.param<double>("x_velocity_max", axes_.x.max, 2.0);
params.param<double>("y_velocity_max", axes_.y.max, 2.0);
params.param<double>("z_velocity_max", axes_.z.max, 2.0);
joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));
velocity_publisher_ = node_handle_.advertise<geometry_msgs::Twist>("cmd_vel", 10);
}
else if (control_mode_str == "attitude")
{
params.param<double>("x_roll_max", axes_.x.max, 0.35);
params.param<double>("y_pitch_max", axes_.y.max, 0.35);
params.param<double>("z_thrust_max", axes_.z.max, 25.0);
joy_subscriber_ = node_handle_.subscribe<sensor_msgs::Joy>("joy", 1, boost::bind(&Teleop::joyAttitudeCallback, this, _1));
attitude_publisher_ = node_handle_.advertise<hector_uav_msgs::AttitudeCommand>("command/attitude", 10);
yawrate_publisher_ = node_handle_.advertise<hector_uav_msgs::YawrateCommand>("command/yawrate", 10);
thrust_publisher_ = node_handle_.advertise<hector_uav_msgs::ThrustCommand>("command/thrust", 10);
}
}
~Teleop()
{
stop();
}
void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)
{
velocity_.linear.x = getAxis(joy, axes_.x);
velocity_.linear.y = getAxis(joy, axes_.y);
velocity_.linear.z = getAxis(joy, axes_.z);
velocity_.angular.z = getAxis(joy, axes_.yaw);
if (getButton(joy, buttons_.slow.button))
{
velocity_.linear.x *= slow_factor_;
velocity_.linear.y *= slow_factor_;
velocity_.linear.z *= slow_factor_;
velocity_.angular.z *= slow_factor_;
}
velocity_publisher_.publish(velocity_);
}
void joyAttitudeCallback(const sensor_msgs::JoyConstPtr &joy)
{
attitude_.roll = getAxis(joy, axes_.x);
attitude_.pitch = getAxis(joy, axes_.y);
attitude_publisher_.publish(attitude_);
thrust_.thrust = getAxis(joy, axes_.z);
thrust_publisher_.publish(thrust_);
yawrate_.turnrate = getAxis(joy, axes_.yaw);
if (getButton(joy, buttons_.slow.button))
{
yawrate_.turnrate *= slow_factor_;
}
yawrate_publisher_.publish(yawrate_);
}
sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)
{
if (axis.axis == 0)
{return 0;}
sensor_msgs::Joy::_axes_type::value_type sign = 1.0;
if (axis.axis < 0)
{
sign = -1.0;
axis.axis = -axis.axis;
}
if ((size_t) axis.axis > joy->axes.size())
{return 0;}
return sign * joy->axes[axis.axis - 1] * axis.max;
}
sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)
{
if (button <= 0)
{return 0;}
if ((size_t) button > joy->buttons.size())
{return 0;}
return joy->buttons[button - 1];
}
void stop()
{
if(velocity_publisher_.getNumSubscribers() > 0)
{
velocity_ = geometry_msgs::Twist();
velocity_publisher_.publish(velocity_);
}
if(attitude_publisher_.getNumSubscribers() > 0)
{
attitude_ = hector_uav_msgs::AttitudeCommand();
attitude_publisher_.publish(attitude_);
}
if(thrust_publisher_.getNumSubscribers() > 0)
{
thrust_ = hector_uav_msgs::ThrustCommand();
thrust_publisher_.publish(thrust_);
}
if(yawrate_publisher_.getNumSubscribers() > 0)
{
yawrate_ = hector_uav_msgs::YawrateCommand();
yawrate_publisher_.publish(yawrate_);
}
}
};
} // namespace hector_quadrotor
int main(int argc, char **argv)
{
ros::init(argc, argv, "quadrotor_teleop");
hector_quadrotor::Teleop teleop;
ros::spin();
return 0;
}
|
Fix array index out of bounds access
|
Fix array index out of bounds access
The existing code was checking the number of axes not buttons
Signed-off-by: Nicolae Rosia <[email protected]>
|
C++
|
bsd-3-clause
|
UTS-CAS/hector_quadrotor,UTS-CAS/hector_quadrotor,UTS-CAS/hector_quadrotor
|
28ce98e310ba7c59b350508f40ab38cf3b08763e
|
app/src/main/cpp/native-lib.cpp
|
app/src/main/cpp/native-lib.cpp
|
#include <jni.h>
#include <string>
#include <netdb.h>
#include <arpa/inet.h>
#include <android/log.h>
#include "elfhook/elfhook.h"
void print_gethostbyname() {
gethostbyname("www.mingyuans.me");
}
struct hostent *my_gethostbyname(const char * domain) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","my_gethostbyname called! %s",domain);
return NULL;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_doElfHookByLinkView(JNIEnv *env, jobject instance) {
struct hostent *(*system_gethostbyname)(const char *) = NULL;
uint result = elfhook_s("native-lib", "gethostbyname", (void *) my_gethostbyname,
(void **) &system_gethostbyname);
print_gethostbyname();
struct hostent * hostent_ptr = system_gethostbyname("www.baidu.com");
if (hostent_ptr != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "domain ips: %s",
inet_ntoa(*((struct in_addr *) hostent_ptr->h_addr)));
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "%s", "domain ips: null");
}
if (result != 0) {
elfhook_stop("native-lib", result, (void **) &system_gethostbyname);
}
print_gethostbyname();
return result;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_doElfHookByExecutableView(JNIEnv *env, jobject instance) {
struct hostent *(*system_gethostbyname)(const char *) = NULL;
size_t result = elfhook_p("native-lib", "gethostbyname", (void *) my_gethostbyname,
(void **) &system_gethostbyname);
print_gethostbyname();
if (system_gethostbyname != NULL) {
struct hostent * hostent_ptr = system_gethostbyname("www.baidu.com");
if (hostent_ptr != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "domain ips: %s",
inet_ntoa(*((struct in_addr *) hostent_ptr->h_addr)));
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "%s", "domain ips: null");
}
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","system gethostbyname is null!");
}
return result;
}
int (*global_system_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = NULL;
int my_getaddrinfo(const char *hostname, const char *service, const struct addrinfo * hints, struct addrinfo **result) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","hostname:%s",hostname);
if (global_system_getaddrinfo != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","do system_getaddrinfo");
return global_system_getaddrinfo(hostname,service,hints,result);
}
return 0;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_hookWebViewDns(JNIEnv *env, jobject instance) {
int (*system_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = NULL;
int hookResultCode = elfhook_p("WebViewGoogle.apk","getaddrinfo", (void *) my_getaddrinfo,
(void **) &system_getaddrinfo);
global_system_getaddrinfo = system_getaddrinfo;
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","system_getaddirinfo: 0x%x",system_getaddrinfo);
return hookResultCode;
}
|
#include <jni.h>
#include <string>
#include <netdb.h>
#include <arpa/inet.h>
#include <android/log.h>
#include "elfhook/elfhook.h"
void print_gethostbyname() {
gethostbyname("www.mingyuans.me");
}
struct hostent *my_gethostbyname(const char * domain) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","my_gethostbyname called! %s",domain);
return NULL;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_doElfHookByLinkView(JNIEnv *env, jobject instance) {
struct hostent *(*system_gethostbyname)(const char *) = NULL;
uint result = elfhook_s("native-lib", "gethostbyname", (void *) my_gethostbyname,
(void **) &system_gethostbyname);
print_gethostbyname();
struct hostent * hostent_ptr = system_gethostbyname("www.baidu.com");
if (hostent_ptr != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "domain ips: %s",
inet_ntoa(*((struct in_addr *) hostent_ptr->h_addr)));
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "%s", "domain ips: null");
}
if (result != 0) {
elfhook_stop(result, (void **) &system_gethostbyname);
}
print_gethostbyname();
return result;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_doElfHookByExecutableView(JNIEnv *env, jobject instance) {
struct hostent *(*system_gethostbyname)(const char *) = NULL;
size_t result = elfhook_p("native-lib", "gethostbyname", (void *) my_gethostbyname,
(void **) &system_gethostbyname);
print_gethostbyname();
if (system_gethostbyname != NULL) {
struct hostent * hostent_ptr = system_gethostbyname("www.baidu.com");
if (hostent_ptr != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "domain ips: %s",
inet_ntoa(*((struct in_addr *) hostent_ptr->h_addr)));
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO, "androidHook", "%s", "domain ips: null");
}
} else {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","system gethostbyname is null!");
}
return result;
}
int (*global_system_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = NULL;
int my_getaddrinfo(const char *hostname, const char *service, const struct addrinfo * hints, struct addrinfo **result) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","hostname:%s",hostname);
if (global_system_getaddrinfo != NULL) {
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","do system_getaddrinfo");
return global_system_getaddrinfo(hostname,service,hints,result);
}
return 0;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_mingyuans_hook_MainActivity_hookWebViewDns(JNIEnv *env, jobject instance) {
int (*system_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = NULL;
int hookResultCode = elfhook_p("WebViewGoogle.apk","getaddrinfo", (void *) my_getaddrinfo,
(void **) &system_getaddrinfo);
global_system_getaddrinfo = system_getaddrinfo;
__android_log_print(android_LogPriority::ANDROID_LOG_INFO,"androidHook","system_getaddirinfo: 0x%x",system_getaddrinfo);
return hookResultCode;
}
|
Fix stop_hook
|
Fix stop_hook
|
C++
|
mit
|
mingyuans/AndroidHook,mingyuans/AndroidHook,mingyuans/AndroidHook
|
1ba4514574cfafe827624e826ee4063f3fe31788
|
interface/generator.cc
|
interface/generator.cc
|
/*
* Copyright 2011,2015 Sven Verdoolaege. 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 SVEN VERDOOLAEGE ''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 SVEN VERDOOLAEGE 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.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as
* representing official policies, either expressed or implied, of
* Sven Verdoolaege.
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <clang/AST/Attr.h>
#include <clang/Basic/SourceManager.h>
#include "isl_config.h"
#include "extract_interface.h"
#include "generator.h"
/* Compare the prefix of "s" to "prefix" up to the length of "prefix".
*/
static int prefixcmp(const char *s, const char *prefix)
{
return strncmp(s, prefix, strlen(prefix));
}
/* Should "method" be considered to be a static method?
* That is, is the first argument something other than
* an instance of the class?
*/
bool generator::is_static(const isl_class &clazz, FunctionDecl *method)
{
ParmVarDecl *param = method->getParamDecl(0);
QualType type = param->getOriginalType();
if (!is_isl_type(type))
return true;
return extract_type(type) != clazz.name;
}
/* Find the FunctionDecl with name "name",
* returning NULL if there is no such FunctionDecl.
* If "required" is set, then error out if no FunctionDecl can be found.
*/
FunctionDecl *generator::find_by_name(const string &name, bool required)
{
map<string, FunctionDecl *>::iterator i;
i = functions_by_name.find(name);
if (i != functions_by_name.end())
return i->second;
if (required)
die("No " + name + " function found");
return NULL;
}
/* Collect all functions that belong to a certain type, separating
* constructors from regular methods and keeping track of the _to_str,
* _copy and _free functions, if any, separately. If there are any overloaded
* functions, then they are grouped based on their name after removing the
* argument type suffix.
*/
generator::generator(SourceManager &SM, set<RecordDecl *> &exported_types,
set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions) :
SM(SM)
{
map<string, isl_class>::iterator ci;
set<FunctionDecl *>::iterator in;
for (in = functions.begin(); in != functions.end(); ++in) {
FunctionDecl *decl = *in;
functions_by_name[decl->getName()] = decl;
}
set<RecordDecl *>::iterator it;
for (it = exported_types.begin(); it != exported_types.end(); ++it) {
RecordDecl *decl = *it;
string name = decl->getName();
classes[name].name = name;
classes[name].type = decl;
classes[name].fn_to_str = find_by_name(name + "_to_str", false);
classes[name].fn_copy = find_by_name(name + "_copy", true);
classes[name].fn_free = find_by_name(name + "_free", true);
}
for (in = exported_functions.begin(); in != exported_functions.end();
++in) {
FunctionDecl *method = *in;
isl_class *c = method2class(method);
if (!c)
continue;
if (is_constructor(method)) {
c->constructors.insert(method);
} else {
string fullname = c->name_without_type_suffix(method);
c->methods[fullname].insert(method);
}
}
}
/* Print error message "msg" and abort.
*/
void generator::die(const char *msg)
{
fprintf(stderr, "%s\n", msg);
abort();
}
/* Print error message "msg" and abort.
*/
void generator::die(string msg)
{
die(msg.c_str());
}
/* Return a sequence of the types of which the given type declaration is
* marked as being a subtype.
* The order of the types is the opposite of the order in which they
* appear in the source. In particular, the first annotation
* is the one that is closest to the annotated type and the corresponding
* type is then also the first that will appear in the sequence of types.
*/
std::vector<string> generator::find_superclasses(RecordDecl *decl)
{
vector<string> super;
if (!decl->hasAttrs())
return super;
string sub = "isl_subclass";
size_t len = sub.length();
AttrVec attrs = decl->getAttrs();
for (AttrVec::const_iterator i = attrs.begin(); i != attrs.end(); ++i) {
const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
if (!ann)
continue;
string s = ann->getAnnotation().str();
if (s.substr(0, len) == sub) {
s = s.substr(len + 1, s.length() - len - 2);
super.push_back(s);
}
}
return super;
}
/* Is decl marked as being part of an overloaded method?
*/
bool generator::is_overload(Decl *decl)
{
return has_annotation(decl, "isl_overload");
}
/* Is decl marked as a constructor?
*/
bool generator::is_constructor(Decl *decl)
{
return has_annotation(decl, "isl_constructor");
}
/* Is decl marked as consuming a reference?
*/
bool generator::takes(Decl *decl)
{
return has_annotation(decl, "isl_take");
}
/* Is decl marked as preserving a reference?
*/
bool generator::keeps(Decl *decl)
{
return has_annotation(decl, "isl_keep");
}
/* Is decl marked as returning a reference that is required to be freed.
*/
bool generator::gives(Decl *decl)
{
return has_annotation(decl, "isl_give");
}
/* Return the class that has a name that matches the initial part
* of the name of function "fd" or NULL if no such class could be found.
*/
isl_class *generator::method2class(FunctionDecl *fd)
{
string best;
map<string, isl_class>::iterator ci;
string name = fd->getNameAsString();
for (ci = classes.begin(); ci != classes.end(); ++ci) {
if (name.substr(0, ci->first.length()) == ci->first)
best = ci->first;
}
if (classes.find(best) == classes.end()) {
cerr << "Unable to find class of " << name << endl;
return NULL;
}
return &classes[best];
}
/* Is "type" the type "isl_ctx *"?
*/
bool generator::is_isl_ctx(QualType type)
{
if (!type->isPointerType())
return 0;
type = type->getPointeeType();
if (type.getAsString() != "isl_ctx")
return false;
return true;
}
/* Is the first argument of "fd" of type "isl_ctx *"?
*/
bool generator::first_arg_is_isl_ctx(FunctionDecl *fd)
{
ParmVarDecl *param;
if (fd->getNumParams() < 1)
return false;
param = fd->getParamDecl(0);
return is_isl_ctx(param->getOriginalType());
}
namespace {
struct ClangAPI {
/* Return the first location in the range returned by
* clang::SourceManager::getImmediateExpansionRange.
* Older versions of clang return a pair of SourceLocation objects.
* More recent versions return a CharSourceRange.
*/
static SourceLocation range_begin(
const std::pair<SourceLocation,SourceLocation> &p) {
return p.first;
}
static SourceLocation range_begin(const CharSourceRange &range) {
return range.getBegin();
}
};
}
/* Does the callback argument "param" take its argument at position "pos"?
*
* The memory management annotations of arguments to function pointers
* are not recorded by clang, so the information cannot be extracted
* from the type of "param".
* Instead, go to the location in the source where the callback argument
* is declared, look for the right argument of the callback itself and
* then check if it has an "__isl_take" memory management annotation.
*
* If the return value of the function has a memory management annotation,
* then the spelling of "param" will point to the spelling
* of this memory management annotation. Since the macro is defined
* on the command line (in main), this location does not have a file entry.
* In this case, move up one level in the macro expansion to the location
* where the memory management annotation is used.
*/
bool generator::callback_takes_argument(ParmVarDecl *param,
int pos)
{
SourceLocation loc;
const char *s, *end, *next;
bool takes, keeps;
loc = param->getSourceRange().getBegin();
if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(loc))))
loc = ClangAPI::range_begin(SM.getImmediateExpansionRange(loc));
s = SM.getCharacterData(loc);
if (!s)
die("No character data");
s = strchr(s, '(');
if (!s)
die("Cannot find function pointer");
s = strchr(s + 1, '(');
if (!s)
die("Cannot find function pointer arguments");
end = strchr(s + 1, ')');
if (!end)
die("Cannot find end of function pointer arguments");
while (pos-- > 0) {
s = strchr(s + 1, ',');
if (!s || s > end)
die("Cannot find function pointer argument");
}
next = strchr(s + 1, ',');
if (next && next < end)
end = next;
s = strchr(s + 1, '_');
if (!s || s > end)
die("Cannot find function pointer argument annotation");
takes = prefixcmp(s, "__isl_take") == 0;
keeps = prefixcmp(s, "__isl_keep") == 0;
if (!takes && !keeps)
die("Cannot find function pointer argument annotation");
return takes;
}
/* Is "type" that of a pointer to an isl_* structure?
*/
bool generator::is_isl_type(QualType type)
{
if (type->isPointerType()) {
string s;
type = type->getPointeeType();
if (type->isFunctionType())
return false;
s = type.getAsString();
return s.substr(0, 4) == "isl_";
}
return false;
}
/* Is "type" one of the integral types with a negative value
* indicating an error condition?
*/
bool generator::is_isl_neg_error(QualType type)
{
return is_isl_bool(type) || is_isl_stat(type) || is_isl_size(type);
}
/* Is "type" the primitive type with the given name?
*/
static bool is_isl_primitive(QualType type, const char *name)
{
string s;
if (type->isPointerType())
return false;
s = type.getAsString();
return s == name;
}
/* Is "type" the type isl_bool?
*/
bool generator::is_isl_bool(QualType type)
{
return is_isl_primitive(type, "isl_bool");
}
/* Is "type" the type isl_stat?
*/
bool generator::is_isl_stat(QualType type)
{
return is_isl_primitive(type, "isl_stat");
}
/* Is "type" the type isl_size?
*/
bool generator::is_isl_size(QualType type)
{
return is_isl_primitive(type, "isl_size");
}
/* Is "type" that of a pointer to a function?
*/
bool generator::is_callback(QualType type)
{
if (!type->isPointerType())
return false;
type = type->getPointeeType();
return type->isFunctionType();
}
/* Is "type" that of "char *" of "const char *"?
*/
bool generator::is_string(QualType type)
{
if (type->isPointerType()) {
string s = type->getPointeeType().getAsString();
return s == "const char" || s == "char";
}
return false;
}
/* Is "type" that of "long"?
*/
bool generator::is_long(QualType type)
{
const BuiltinType *builtin = type->getAs<BuiltinType>();
return builtin && builtin->getKind() == BuiltinType::Long;
}
/* Return the name of the type that "type" points to.
* The input "type" is assumed to be a pointer type.
*/
string generator::extract_type(QualType type)
{
if (type->isPointerType())
return type->getPointeeType().getAsString();
die("Cannot extract type from non-pointer type");
}
/* Given the type of a function pointer, return the corresponding
* function prototype.
*/
const FunctionProtoType *generator::extract_prototype(QualType type)
{
return type->getPointeeType()->getAs<FunctionProtoType>();
}
/* If "method" is overloaded, then return its name with the suffix
* corresponding to the type of the final argument removed.
* Otherwise, simply return the name of the function.
*/
string isl_class::name_without_type_suffix(FunctionDecl *method)
{
int num_params;
ParmVarDecl *param;
string name, type;
size_t name_len, type_len;
name = method->getName();
if (!generator::is_overload(method))
return name;
num_params = method->getNumParams();
param = method->getParamDecl(num_params - 1);
type = generator::extract_type(param->getOriginalType());
type = type.substr(4);
name_len = name.length();
type_len = type.length();
if (name_len > type_len && name.substr(name_len - type_len) == type)
name = name.substr(0, name_len - type_len - 1);
return name;
}
|
/*
* Copyright 2011,2015 Sven Verdoolaege. 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 SVEN VERDOOLAEGE ''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 SVEN VERDOOLAEGE 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.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as
* representing official policies, either expressed or implied, of
* Sven Verdoolaege.
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <clang/AST/Attr.h>
#include <clang/Basic/SourceManager.h>
#include "isl_config.h"
#include "extract_interface.h"
#include "generator.h"
/* Compare the prefix of "s" to "prefix" up to the length of "prefix".
*/
static int prefixcmp(const char *s, const char *prefix)
{
return strncmp(s, prefix, strlen(prefix));
}
/* Should "method" be considered to be a static method?
* That is, is the first argument something other than
* an instance of the class?
*/
bool generator::is_static(const isl_class &clazz, FunctionDecl *method)
{
ParmVarDecl *param = method->getParamDecl(0);
QualType type = param->getOriginalType();
if (!is_isl_type(type))
return true;
return extract_type(type) != clazz.name;
}
/* Find the FunctionDecl with name "name",
* returning NULL if there is no such FunctionDecl.
* If "required" is set, then error out if no FunctionDecl can be found.
*/
FunctionDecl *generator::find_by_name(const string &name, bool required)
{
map<string, FunctionDecl *>::iterator i;
i = functions_by_name.find(name);
if (i != functions_by_name.end())
return i->second;
if (required)
die("No " + name + " function found");
return NULL;
}
/* Collect all functions that belong to a certain type, separating
* constructors from regular methods and keeping track of the _to_str,
* _copy and _free functions, if any, separately. If there are any overloaded
* functions, then they are grouped based on their name after removing the
* argument type suffix.
*/
generator::generator(SourceManager &SM, set<RecordDecl *> &exported_types,
set<FunctionDecl *> exported_functions, set<FunctionDecl *> functions) :
SM(SM)
{
set<FunctionDecl *>::iterator in;
for (in = functions.begin(); in != functions.end(); ++in) {
FunctionDecl *decl = *in;
functions_by_name[decl->getName()] = decl;
}
set<RecordDecl *>::iterator it;
for (it = exported_types.begin(); it != exported_types.end(); ++it) {
RecordDecl *decl = *it;
string name = decl->getName();
classes[name].name = name;
classes[name].type = decl;
classes[name].fn_to_str = find_by_name(name + "_to_str", false);
classes[name].fn_copy = find_by_name(name + "_copy", true);
classes[name].fn_free = find_by_name(name + "_free", true);
}
for (in = exported_functions.begin(); in != exported_functions.end();
++in) {
FunctionDecl *method = *in;
isl_class *c = method2class(method);
if (!c)
continue;
if (is_constructor(method)) {
c->constructors.insert(method);
} else {
string fullname = c->name_without_type_suffix(method);
c->methods[fullname].insert(method);
}
}
}
/* Print error message "msg" and abort.
*/
void generator::die(const char *msg)
{
fprintf(stderr, "%s\n", msg);
abort();
}
/* Print error message "msg" and abort.
*/
void generator::die(string msg)
{
die(msg.c_str());
}
/* Return a sequence of the types of which the given type declaration is
* marked as being a subtype.
* The order of the types is the opposite of the order in which they
* appear in the source. In particular, the first annotation
* is the one that is closest to the annotated type and the corresponding
* type is then also the first that will appear in the sequence of types.
*/
std::vector<string> generator::find_superclasses(RecordDecl *decl)
{
vector<string> super;
if (!decl->hasAttrs())
return super;
string sub = "isl_subclass";
size_t len = sub.length();
AttrVec attrs = decl->getAttrs();
for (AttrVec::const_iterator i = attrs.begin(); i != attrs.end(); ++i) {
const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
if (!ann)
continue;
string s = ann->getAnnotation().str();
if (s.substr(0, len) == sub) {
s = s.substr(len + 1, s.length() - len - 2);
super.push_back(s);
}
}
return super;
}
/* Is decl marked as being part of an overloaded method?
*/
bool generator::is_overload(Decl *decl)
{
return has_annotation(decl, "isl_overload");
}
/* Is decl marked as a constructor?
*/
bool generator::is_constructor(Decl *decl)
{
return has_annotation(decl, "isl_constructor");
}
/* Is decl marked as consuming a reference?
*/
bool generator::takes(Decl *decl)
{
return has_annotation(decl, "isl_take");
}
/* Is decl marked as preserving a reference?
*/
bool generator::keeps(Decl *decl)
{
return has_annotation(decl, "isl_keep");
}
/* Is decl marked as returning a reference that is required to be freed.
*/
bool generator::gives(Decl *decl)
{
return has_annotation(decl, "isl_give");
}
/* Return the class that has a name that matches the initial part
* of the name of function "fd" or NULL if no such class could be found.
*/
isl_class *generator::method2class(FunctionDecl *fd)
{
string best;
map<string, isl_class>::iterator ci;
string name = fd->getNameAsString();
for (ci = classes.begin(); ci != classes.end(); ++ci) {
if (name.substr(0, ci->first.length()) == ci->first)
best = ci->first;
}
if (classes.find(best) == classes.end()) {
cerr << "Unable to find class of " << name << endl;
return NULL;
}
return &classes[best];
}
/* Is "type" the type "isl_ctx *"?
*/
bool generator::is_isl_ctx(QualType type)
{
if (!type->isPointerType())
return 0;
type = type->getPointeeType();
if (type.getAsString() != "isl_ctx")
return false;
return true;
}
/* Is the first argument of "fd" of type "isl_ctx *"?
*/
bool generator::first_arg_is_isl_ctx(FunctionDecl *fd)
{
ParmVarDecl *param;
if (fd->getNumParams() < 1)
return false;
param = fd->getParamDecl(0);
return is_isl_ctx(param->getOriginalType());
}
namespace {
struct ClangAPI {
/* Return the first location in the range returned by
* clang::SourceManager::getImmediateExpansionRange.
* Older versions of clang return a pair of SourceLocation objects.
* More recent versions return a CharSourceRange.
*/
static SourceLocation range_begin(
const std::pair<SourceLocation,SourceLocation> &p) {
return p.first;
}
static SourceLocation range_begin(const CharSourceRange &range) {
return range.getBegin();
}
};
}
/* Does the callback argument "param" take its argument at position "pos"?
*
* The memory management annotations of arguments to function pointers
* are not recorded by clang, so the information cannot be extracted
* from the type of "param".
* Instead, go to the location in the source where the callback argument
* is declared, look for the right argument of the callback itself and
* then check if it has an "__isl_take" memory management annotation.
*
* If the return value of the function has a memory management annotation,
* then the spelling of "param" will point to the spelling
* of this memory management annotation. Since the macro is defined
* on the command line (in main), this location does not have a file entry.
* In this case, move up one level in the macro expansion to the location
* where the memory management annotation is used.
*/
bool generator::callback_takes_argument(ParmVarDecl *param,
int pos)
{
SourceLocation loc;
const char *s, *end, *next;
bool takes, keeps;
loc = param->getSourceRange().getBegin();
if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(loc))))
loc = ClangAPI::range_begin(SM.getImmediateExpansionRange(loc));
s = SM.getCharacterData(loc);
if (!s)
die("No character data");
s = strchr(s, '(');
if (!s)
die("Cannot find function pointer");
s = strchr(s + 1, '(');
if (!s)
die("Cannot find function pointer arguments");
end = strchr(s + 1, ')');
if (!end)
die("Cannot find end of function pointer arguments");
while (pos-- > 0) {
s = strchr(s + 1, ',');
if (!s || s > end)
die("Cannot find function pointer argument");
}
next = strchr(s + 1, ',');
if (next && next < end)
end = next;
s = strchr(s + 1, '_');
if (!s || s > end)
die("Cannot find function pointer argument annotation");
takes = prefixcmp(s, "__isl_take") == 0;
keeps = prefixcmp(s, "__isl_keep") == 0;
if (!takes && !keeps)
die("Cannot find function pointer argument annotation");
return takes;
}
/* Is "type" that of a pointer to an isl_* structure?
*/
bool generator::is_isl_type(QualType type)
{
if (type->isPointerType()) {
string s;
type = type->getPointeeType();
if (type->isFunctionType())
return false;
s = type.getAsString();
return s.substr(0, 4) == "isl_";
}
return false;
}
/* Is "type" one of the integral types with a negative value
* indicating an error condition?
*/
bool generator::is_isl_neg_error(QualType type)
{
return is_isl_bool(type) || is_isl_stat(type) || is_isl_size(type);
}
/* Is "type" the primitive type with the given name?
*/
static bool is_isl_primitive(QualType type, const char *name)
{
string s;
if (type->isPointerType())
return false;
s = type.getAsString();
return s == name;
}
/* Is "type" the type isl_bool?
*/
bool generator::is_isl_bool(QualType type)
{
return is_isl_primitive(type, "isl_bool");
}
/* Is "type" the type isl_stat?
*/
bool generator::is_isl_stat(QualType type)
{
return is_isl_primitive(type, "isl_stat");
}
/* Is "type" the type isl_size?
*/
bool generator::is_isl_size(QualType type)
{
return is_isl_primitive(type, "isl_size");
}
/* Is "type" that of a pointer to a function?
*/
bool generator::is_callback(QualType type)
{
if (!type->isPointerType())
return false;
type = type->getPointeeType();
return type->isFunctionType();
}
/* Is "type" that of "char *" of "const char *"?
*/
bool generator::is_string(QualType type)
{
if (type->isPointerType()) {
string s = type->getPointeeType().getAsString();
return s == "const char" || s == "char";
}
return false;
}
/* Is "type" that of "long"?
*/
bool generator::is_long(QualType type)
{
const BuiltinType *builtin = type->getAs<BuiltinType>();
return builtin && builtin->getKind() == BuiltinType::Long;
}
/* Return the name of the type that "type" points to.
* The input "type" is assumed to be a pointer type.
*/
string generator::extract_type(QualType type)
{
if (type->isPointerType())
return type->getPointeeType().getAsString();
die("Cannot extract type from non-pointer type");
}
/* Given the type of a function pointer, return the corresponding
* function prototype.
*/
const FunctionProtoType *generator::extract_prototype(QualType type)
{
return type->getPointeeType()->getAs<FunctionProtoType>();
}
/* If "method" is overloaded, then return its name with the suffix
* corresponding to the type of the final argument removed.
* Otherwise, simply return the name of the function.
*/
string isl_class::name_without_type_suffix(FunctionDecl *method)
{
int num_params;
ParmVarDecl *param;
string name, type;
size_t name_len, type_len;
name = method->getName();
if (!generator::is_overload(method))
return name;
num_params = method->getNumParams();
param = method->getParamDecl(num_params - 1);
type = generator::extract_type(param->getOriginalType());
type = type.substr(4);
name_len = name.length();
type_len = type.length();
if (name_len > type_len && name.substr(name_len - type_len) == type)
name = name.substr(0, name_len - type_len - 1);
return name;
}
|
drop spurious declaration
|
generator::generator.cc: drop spurious declaration
The declaration was introduced by isl-0.18-595-gdab674e14c (Turn python
generator into a subclass of generator, Sat Apr 8 05:12:47 2017 +0200).
Signed-off-by: Sven Verdoolaege <[email protected]>
|
C++
|
mit
|
Meinersbur/isl,Meinersbur/isl,Meinersbur/isl,Meinersbur/isl
|
3f765c81d8e708797db25618797289052ec418b3
|
include/ros_type_introspection/builtin_types.hpp
|
include/ros_type_introspection/builtin_types.hpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2016-2017 Davide Faconti
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* *******************************************************************/
#ifndef ROS_BUILTIN_TYPES_HPP
#define ROS_BUILTIN_TYPES_HPP
#include <stdint.h>
#include <string>
#include <ros/ros.h>
#include <unordered_map>
namespace RosIntrospection{
enum BuiltinType {
BOOL , BYTE, CHAR,
UINT8, UINT16, UINT32, UINT64,
INT8, INT16, INT32, INT64,
FLOAT32, FLOAT64,
TIME, DURATION,
STRING, OTHER
};
//---------------------------------------------------------
inline int builtinSize(const BuiltinType c) {
switch (c) {
case BOOL:
case BYTE:
case INT8:
case CHAR:
case UINT8: return 1;
case UINT16:
case INT16: return 2;
case UINT32:
case INT32:
case FLOAT32: return 4;
case UINT64:
case INT64:
case FLOAT64:
case TIME:
case DURATION: return 8;
case STRING:
case OTHER: return -1;
}
throw std::runtime_error( "unsupported builtin type value");
}
inline const char* toStr(const BuiltinType& c)
{
switch (c) {
case BOOL: return "BOOL";
case BYTE: return "BYTE";
case INT8: return "INT8";
case CHAR: return "CHAR";
case UINT8: return "UINT8";
case UINT16: return "UINT16";
case UINT32: return "UINT32";
case UINT64: return "UINT64";
case INT16: return "INT16";
case INT32: return "INT32";
case INT64: return "INT64";
case FLOAT32: return "FLOAT32";
case FLOAT64: return "FLOAT64";
case TIME: return "TIME";
case DURATION: return "DURATION";
case STRING: return "STRING";
case OTHER: return "OTHER";
}
throw std::runtime_error( "unsupported builtin type value");
}
inline std::ostream& operator<<(std::ostream& os, const BuiltinType& c)
{
os << toStr(c);
return os;
}
template <typename T> BuiltinType getType()
{
return OTHER;
}
template <> inline BuiltinType getType<bool>() { return BOOL; }
template <> inline BuiltinType getType<int8_t>() { return INT8; }
template <> inline BuiltinType getType<int16_t>() { return INT16; }
template <> inline BuiltinType getType<int32_t>() { return INT32; }
template <> inline BuiltinType getType<int64_t>() { return INT64; }
template <> inline BuiltinType getType<uint8_t>() { return UINT8; }
template <> inline BuiltinType getType<uint16_t>() { return UINT16; }
template <> inline BuiltinType getType<uint32_t>() { return UINT32; }
template <> inline BuiltinType getType<uint64_t>() { return UINT64; }
template <> inline BuiltinType getType<float>() { return FLOAT32; }
template <> inline BuiltinType getType<double>() { return FLOAT64; }
template <> inline BuiltinType getType<std::string>() { return STRING; }
template <> inline BuiltinType getType<ros::Time>() { return TIME; }
template <> inline BuiltinType getType<ros::Duration>() { return DURATION; }
}
#endif // ROS_BUILTIN_TYPES_HPP
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2016-2017 Davide Faconti
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* *******************************************************************/
#ifndef ROS_BUILTIN_TYPES_HPP
#define ROS_BUILTIN_TYPES_HPP
#include <stdint.h>
#include <string>
#include <ros/ros.h>
#include <unordered_map>
namespace RosIntrospection{
enum BuiltinType {
BOOL , BYTE, CHAR,
UINT8, UINT16, UINT32, UINT64,
INT8, INT16, INT32, INT64,
FLOAT32, FLOAT64,
TIME, DURATION,
STRING, OTHER
};
//---------------------------------------------------------
inline int builtinSize(const BuiltinType c) {
switch (c) {
case BOOL:
case BYTE:
case INT8:
case CHAR:
case UINT8: return 1;
case UINT16:
case INT16: return 2;
case UINT32:
case INT32:
case FLOAT32: return 4;
case UINT64:
case INT64:
case FLOAT64:
case TIME:
case DURATION: return 8;
case STRING:
case OTHER: return -1;
}
throw std::runtime_error( "unsupported builtin type value");
}
inline const char* toStr(const BuiltinType& c)
{
switch (c) {
case BOOL: return "BOOL";
case BYTE: return "BYTE";
case INT8: return "INT8";
case CHAR: return "CHAR";
case UINT8: return "UINT8";
case UINT16: return "UINT16";
case UINT32: return "UINT32";
case UINT64: return "UINT64";
case INT16: return "INT16";
case INT32: return "INT32";
case INT64: return "INT64";
case FLOAT32: return "FLOAT32";
case FLOAT64: return "FLOAT64";
case TIME: return "TIME";
case DURATION: return "DURATION";
case STRING: return "STRING";
case OTHER: return "OTHER";
}
throw std::runtime_error( "unsupported builtin type value");
}
inline std::ostream& operator<<(std::ostream& os, const BuiltinType& c)
{
os << toStr(c);
return os;
}
template <typename T> BuiltinType getType()
{
return OTHER;
}
template <> inline BuiltinType getType<bool>() { return BOOL; }
template <> inline BuiltinType getType<unsigned char>() { return BYTE; }
template <> inline BuiltinType getType<char>() { return CHAR; }
template <> inline BuiltinType getType<int8_t>() { return INT8; }
template <> inline BuiltinType getType<int16_t>() { return INT16; }
template <> inline BuiltinType getType<int32_t>() { return INT32; }
template <> inline BuiltinType getType<int64_t>() { return INT64; }
template <> inline BuiltinType getType<uint8_t>() { return UINT8; }
template <> inline BuiltinType getType<uint16_t>() { return UINT16; }
template <> inline BuiltinType getType<uint32_t>() { return UINT32; }
template <> inline BuiltinType getType<uint64_t>() { return UINT64; }
template <> inline BuiltinType getType<float>() { return FLOAT32; }
template <> inline BuiltinType getType<double>() { return FLOAT64; }
template <> inline BuiltinType getType<std::string>() { return STRING; }
template <> inline BuiltinType getType<ros::Time>() { return TIME; }
template <> inline BuiltinType getType<ros::Duration>() { return DURATION; }
}
#endif // ROS_BUILTIN_TYPES_HPP
|
Add missing BuiltinType::getType() overloads
|
Add missing BuiltinType::getType() overloads
|
C++
|
mit
|
facontidavide/ros-type-introspection
|
fb45d029968cf407753dc823709576e6b4f242e4
|
include/cppcoro/detail/when_all_task.hpp
|
include/cppcoro/detail/when_all_task.hpp
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_DETAIL_WHEN_ALL_TASK_HPP_INCLUDED
#define CPPCORO_DETAIL_WHEN_ALL_TASK_HPP_INCLUDED
#include <cppcoro/awaitable_traits.hpp>
#include <cppcoro/detail/when_all_counter.hpp>
#include <cppcoro/detail/void_value.hpp>
#include <experimental/coroutine>
#include <cassert>
namespace cppcoro
{
namespace detail
{
template<typename RESULT>
class when_all_task;
template<typename RESULT>
class when_all_task_promise
{
public:
using reference = RESULT&&;
using coroutine_handle_t = std::experimental::coroutine_handle<when_all_task_promise<RESULT>>;
when_all_task_promise() noexcept
{}
auto get_return_object() noexcept
{
return coroutine_handle_t::from_promise(*this);
}
std::experimental::suspend_always initial_suspend() noexcept
{
return{};
}
auto final_suspend() noexcept
{
class completion_notifier
{
public:
bool await_ready() const noexcept { return false; }
void await_suspend(coroutine_handle_t coro) const noexcept
{
coro.promise().m_counter->notify_awaitable_completed();
}
void await_resume() const noexcept {}
};
return completion_notifier{};
}
void unhandled_exception() noexcept
{
m_exception = std::current_exception();
}
void return_void() noexcept
{
// We should have either suspended at co_yield point or
// an exception was thrown before running off the end of
// the coroutine.
assert(false);
}
auto yield_value(reference result) noexcept
{
m_result = std::addressof(result);
return final_suspend();
}
void start(when_all_awaitable_counter& counter) noexcept
{
m_counter = &counter;
coroutine_handle_t::from_promise(*this).resume();
}
reference result()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
return static_cast<reference>(*m_result);
}
private:
when_all_awaitable_counter* m_counter;
std::exception_ptr m_exception;
std::remove_reference_t<RESULT>* m_result;
};
template<>
class when_all_task_promise<void>
{
using reference = void_value;
using coroutine_handle_t = std::experimental::coroutine_handle<when_all_task_promise<void>>;
when_all_task_promise() noexcept
{}
auto get_return_object() noexcept
{
return coroutine_handle_t::from_promise(*this);
}
std::experimental::suspend_always initial_suspend() noexcept
{
return{};
}
auto final_suspend() noexcept
{
class completion_notifier
{
public:
bool await_ready() const noexcept { return false; }
void await_suspend(coroutine_handle_t coro) const noexcept
{
coro.promise().m_counter->notify_awaitable_completed();
}
void await_resume() const noexcept {}
};
return completion_notifier{};
}
void unhandled_exception() noexcept
{
m_exception = std::current_exception();
}
void return_void() noexcept
{
}
void start(when_all_awaitable_counter& counter) noexcept
{
m_counter = &counter;
coroutine_handle_t::from_promise(*this).resume();
}
reference result()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
return void_value{};
}
private:
when_all_awaitable_counter* m_counter;
std::exception_ptr m_exception;
};
template<typename RESULT>
class when_all_task final
{
public:
using promise_type = when_all_task_promise<RESULT>;
using coroutine_handle_t = typename promise_type::coroutine_handle_t;
when_all_task(coroutine_handle_t coroutine) noexcept
: m_coroutine(coroutine)
{}
when_all_task(when_all_task&& other) noexcept
: m_coroutine(std::exchange(other.m_coroutine, coroutine_handle_t{}))
{}
~when_all_task()
{
if (m_coroutine) m_coroutine.destroy();
}
when_all_task(const when_all_task&) = delete;
when_all_task& operator=(const when_all_task&) = delete;
void start(when_all_awaitable_counter& counter) noexcept
{
m_coroutine.promise().start(counter);
}
decltype(auto) result()
{
return m_coroutine.promise().result();
}
private:
coroutine_handle_t m_coroutine;
};
template<
typename AWAITABLE,
typename RESULT = typename cppcoro::awaitable_traits<AWAITABLE&&>::await_result_t,
std::enable_if_t<!std::is_void_v<RESULT>, int> = 0>
when_all_task<RESULT> make_when_all_task(AWAITABLE awaitable)
{
co_yield co_await static_cast<AWAITABLE&&>(awaitable);
}
template<
typename AWAITABLE,
typename RESULT = typename cppcoro::awaitable_traits<AWAITABLE&&>::await_result_t,
std::enable_if_t<std::is_void_v<RESULT>, int> = 0>
when_all_task<void> make_when_all_task(AWAITABLE awaitable)
{
co_await static_cast<AWAITABLE&&>(awaitable);
}
}
}
#endif
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_DETAIL_WHEN_ALL_TASK_HPP_INCLUDED
#define CPPCORO_DETAIL_WHEN_ALL_TASK_HPP_INCLUDED
#include <cppcoro/awaitable_traits.hpp>
#include <cppcoro/detail/when_all_counter.hpp>
#include <cppcoro/detail/void_value.hpp>
#include <experimental/coroutine>
#include <cassert>
namespace cppcoro
{
namespace detail
{
template<typename RESULT>
class when_all_task;
template<typename RESULT>
class when_all_task_promise
{
public:
using reference = RESULT&&;
using coroutine_handle_t = std::experimental::coroutine_handle<when_all_task_promise<RESULT>>;
when_all_task_promise() noexcept
{}
auto get_return_object() noexcept
{
return coroutine_handle_t::from_promise(*this);
}
std::experimental::suspend_always initial_suspend() noexcept
{
return{};
}
auto final_suspend() noexcept
{
class completion_notifier
{
public:
bool await_ready() const noexcept { return false; }
void await_suspend(coroutine_handle_t coro) const noexcept
{
coro.promise().m_counter->notify_awaitable_completed();
}
void await_resume() const noexcept {}
};
return completion_notifier{};
}
void unhandled_exception() noexcept
{
m_exception = std::current_exception();
}
void return_void() noexcept
{
// We should have either suspended at co_yield point or
// an exception was thrown before running off the end of
// the coroutine.
assert(false);
}
auto yield_value(reference result) noexcept
{
m_result = std::addressof(result);
return final_suspend();
}
void start(when_all_awaitable_counter& counter) noexcept
{
m_counter = &counter;
coroutine_handle_t::from_promise(*this).resume();
}
reference result()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
return static_cast<reference>(*m_result);
}
private:
when_all_awaitable_counter* m_counter;
std::exception_ptr m_exception;
std::remove_reference_t<RESULT>* m_result;
};
template<>
class when_all_task_promise<void>
{
public:
using reference = void_value;
using coroutine_handle_t = std::experimental::coroutine_handle<when_all_task_promise<void>>;
when_all_task_promise() noexcept
{}
auto get_return_object() noexcept
{
return coroutine_handle_t::from_promise(*this);
}
std::experimental::suspend_always initial_suspend() noexcept
{
return{};
}
auto final_suspend() noexcept
{
class completion_notifier
{
public:
bool await_ready() const noexcept { return false; }
void await_suspend(coroutine_handle_t coro) const noexcept
{
coro.promise().m_counter->notify_awaitable_completed();
}
void await_resume() const noexcept {}
};
return completion_notifier{};
}
void unhandled_exception() noexcept
{
m_exception = std::current_exception();
}
void return_void() noexcept
{
}
void start(when_all_awaitable_counter& counter) noexcept
{
m_counter = &counter;
coroutine_handle_t::from_promise(*this).resume();
}
reference result()
{
if (m_exception)
{
std::rethrow_exception(m_exception);
}
return void_value{};
}
private:
when_all_awaitable_counter* m_counter;
std::exception_ptr m_exception;
};
template<typename RESULT>
class when_all_task final
{
public:
using promise_type = when_all_task_promise<RESULT>;
using coroutine_handle_t = typename promise_type::coroutine_handle_t;
when_all_task(coroutine_handle_t coroutine) noexcept
: m_coroutine(coroutine)
{}
when_all_task(when_all_task&& other) noexcept
: m_coroutine(std::exchange(other.m_coroutine, coroutine_handle_t{}))
{}
~when_all_task()
{
if (m_coroutine) m_coroutine.destroy();
}
when_all_task(const when_all_task&) = delete;
when_all_task& operator=(const when_all_task&) = delete;
void start(when_all_awaitable_counter& counter) noexcept
{
m_coroutine.promise().start(counter);
}
decltype(auto) result()
{
return m_coroutine.promise().result();
}
private:
coroutine_handle_t m_coroutine;
};
template<
typename AWAITABLE,
typename RESULT = typename cppcoro::awaitable_traits<AWAITABLE&&>::await_result_t,
std::enable_if_t<!std::is_void_v<RESULT>, int> = 0>
when_all_task<RESULT> make_when_all_task(AWAITABLE awaitable)
{
co_yield co_await static_cast<AWAITABLE&&>(awaitable);
}
template<
typename AWAITABLE,
typename RESULT = typename cppcoro::awaitable_traits<AWAITABLE&&>::await_result_t,
std::enable_if_t<std::is_void_v<RESULT>, int> = 0>
when_all_task<void> make_when_all_task(AWAITABLE awaitable)
{
co_await static_cast<AWAITABLE&&>(awaitable);
}
}
}
#endif
|
Fix member accessibility in when_all_task_promise<void>.
|
Fix member accessibility in when_all_task_promise<void>.
|
C++
|
mit
|
lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro
|
64bb16af8a9bd7e37fc088a67ff3eee988f2e6eb
|
db/view/view_update_generator.hh
|
db/view/view_update_generator.hh
|
/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "database.hh"
#include "sstables/shared_sstable.hh"
#include <seastar/core/abort_source.hh>
#include <seastar/core/condition-variable.hh>
#include <seastar/core/semaphore.hh>
namespace db::view {
class view_update_generator {
public:
static constexpr size_t registration_queue_size = 5;
private:
database& _db;
seastar::abort_source _as;
future<> _started = make_ready_future<>();
seastar::condition_variable _pending_sstables;
named_semaphore _registration_sem{registration_queue_size, named_semaphore_exception_factory{"view update generator"}};
struct sstable_with_table {
sstables::shared_sstable sst;
lw_shared_ptr<table> t;
sstable_with_table(sstables::shared_sstable sst, lw_shared_ptr<table> t) : sst(std::move(sst)), t(std::move(t)) { }
};
std::unordered_map<lw_shared_ptr<table>, std::vector<sstables::shared_sstable>> _sstables_with_tables;
std::unordered_map<lw_shared_ptr<table>, std::vector<sstables::shared_sstable>> _sstables_to_move;
metrics::metric_groups _metrics;
public:
view_update_generator(database& db) : _db(db) {
setup_metrics();
}
future<> start();
future<> stop();
future<> register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<table> table);
ssize_t available_register_units() const { return _registration_sem.available_units(); }
private:
bool should_throttle() const;
void setup_metrics();
};
}
|
/*
* Copyright (C) 2018-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "database.hh"
#include "sstables/shared_sstable.hh"
#include <seastar/core/abort_source.hh>
#include <seastar/core/condition-variable.hh>
#include <seastar/core/semaphore.hh>
namespace db::view {
class view_update_generator {
public:
static constexpr size_t registration_queue_size = 5;
private:
database& _db;
seastar::abort_source _as;
future<> _started = make_ready_future<>();
seastar::condition_variable _pending_sstables;
named_semaphore _registration_sem{registration_queue_size, named_semaphore_exception_factory{"view update generator"}};
std::unordered_map<lw_shared_ptr<table>, std::vector<sstables::shared_sstable>> _sstables_with_tables;
std::unordered_map<lw_shared_ptr<table>, std::vector<sstables::shared_sstable>> _sstables_to_move;
metrics::metric_groups _metrics;
public:
view_update_generator(database& db) : _db(db) {
setup_metrics();
}
future<> start();
future<> stop();
future<> register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<table> table);
ssize_t available_register_units() const { return _registration_sem.available_units(); }
private:
bool should_throttle() const;
void setup_metrics();
};
}
|
Remove unused struct sstable_with_table
|
view_update_generator: Remove unused struct sstable_with_table
Signed-off-by: Pavel Emelyanov <[email protected]>
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
|
7be0b08f5aa269bfdd40a0d66a3cb2f2675b00ca
|
include/libtorrent/kademlia/observer.hpp
|
include/libtorrent/kademlia/observer.hpp
|
/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OBSERVER_HPP
#define OBSERVER_HPP
#include <boost/pool/pool.hpp>
#include <boost/detail/atomic_count.hpp>
#include <boost/intrusive_ptr.hpp>
namespace libtorrent {
namespace dht {
struct observer;
struct msg;
// defined in rpc_manager.cpp
TORRENT_EXPORT void intrusive_ptr_add_ref(observer const*);
TORRENT_EXPORT void intrusive_ptr_release(observer const*);
struct observer : boost::noncopyable
{
friend TORRENT_EXPORT void intrusive_ptr_add_ref(observer const*);
friend TORRENT_EXPORT void intrusive_ptr_release(observer const*);
observer(boost::pool<>& p)
: sent(time_now())
, pool_allocator(p)
, m_refs(0)
{
#ifdef TORRENT_DEBUG
m_in_constructor = true;
#endif
}
virtual ~observer()
{
TORRENT_ASSERT(!m_in_constructor);
}
// these two callbacks lets the observer add
// information to the message before it's sent
virtual void send(msg& m) = 0;
// this is called when a reply is received
virtual void reply(msg const& m) = 0;
// this is called when no reply has been received within
// some timeout
virtual void timeout() = 0;
// if this is called the destructor should
// not invoke any new messages, and should
// only clean up. It means the rpc-manager
// is being destructed
virtual void abort() = 0;
#if TORRENT_USE_IPV6
address target_addr;
#else
address_v4 target_addr;
#endif
uint16_t port;
udp::endpoint target_ep() const { return udp::endpoint(target_addr, port); }
ptime sent;
#ifdef TORRENT_DEBUG
bool m_in_constructor;
#endif
private:
boost::pool<>& pool_allocator;
// reference counter for intrusive_ptr
mutable boost::detail::atomic_count m_refs;
};
typedef boost::intrusive_ptr<observer> observer_ptr;
} }
#endif
|
/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OBSERVER_HPP
#define OBSERVER_HPP
#include <boost/pool/pool.hpp>
#include <boost/detail/atomic_count.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/cstdint.hpp>
namespace libtorrent {
namespace dht {
struct observer;
struct msg;
// defined in rpc_manager.cpp
TORRENT_EXPORT void intrusive_ptr_add_ref(observer const*);
TORRENT_EXPORT void intrusive_ptr_release(observer const*);
struct observer : boost::noncopyable
{
friend TORRENT_EXPORT void intrusive_ptr_add_ref(observer const*);
friend TORRENT_EXPORT void intrusive_ptr_release(observer const*);
observer(boost::pool<>& p)
: sent(time_now())
, pool_allocator(p)
, m_refs(0)
{
#ifdef TORRENT_DEBUG
m_in_constructor = true;
#endif
}
virtual ~observer()
{
TORRENT_ASSERT(!m_in_constructor);
}
// these two callbacks lets the observer add
// information to the message before it's sent
virtual void send(msg& m) = 0;
// this is called when a reply is received
virtual void reply(msg const& m) = 0;
// this is called when no reply has been received within
// some timeout
virtual void timeout() = 0;
// if this is called the destructor should
// not invoke any new messages, and should
// only clean up. It means the rpc-manager
// is being destructed
virtual void abort() = 0;
#if TORRENT_USE_IPV6
address target_addr;
#else
address_v4 target_addr;
#endif
boost::uint16_t port;
udp::endpoint target_ep() const { return udp::endpoint(target_addr, port); }
ptime sent;
#ifdef TORRENT_DEBUG
bool m_in_constructor;
#endif
private:
boost::pool<>& pool_allocator;
// reference counter for intrusive_ptr
mutable boost::detail::atomic_count m_refs;
};
typedef boost::intrusive_ptr<observer> observer_ptr;
} }
#endif
|
fix missing boost:: qualifier
|
fix missing boost:: qualifier
|
C++
|
bsd-3-clause
|
mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent,mildred/rasterbar-libtorrent,mrmichalis/libtorrent-code,mrmichalis/libtorrent-code,mildred/rasterbar-libtorrent
|
382b437b47bbb1307c143e40a7e6d4adadd50099
|
Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx
|
Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#define __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#include "itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h"
namespace itk
{
template< class TDomainPartitioner, class TImageToImageMetric, class TMeanSquaresMetric >
bool
MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMeanSquaresMetric >
::ProcessPoint( const VirtualIndexType &,
const VirtualPointType & virtualPoint,
const FixedImagePointType &,
const FixedImagePixelType & fixedImageValue,
const FixedImageGradientType &,
const MovingImagePointType & ,
const MovingImagePixelType & movingImageValue,
const MovingImageGradientType & movingImageGradient,
MeasureType & metricValueReturn,
DerivativeType & localDerivativeReturn,
const ThreadIdType threadID) const
{
/** Only the voxelwise contribution given the point pairs. */
FixedImagePixelType diff = fixedImageValue - movingImageValue;
const unsigned int nComponents = NumericTraits<FixedImagePixelType>::GetLength( diff );
metricValueReturn = NumericTraits<MeasureType>::ZeroValue();
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffC = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc, diff);
metricValueReturn += diffC*diffC;
}
if( ! this->GetComputeDerivative() )
{
return true;
}
/* Use a pre-allocated jacobian object for efficiency */
typedef typename TImageToImageMetric::JacobianType & JacobianReferenceType;
JacobianReferenceType jacobian = this->m_MovingTransformJacobianPerThread[threadID];
/** For dense transforms, this returns identity */
this->m_Associate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian );
for ( unsigned int par = 0; par < this->GetCachedNumberOfLocalParameters(); par++ )
{
localDerivativeReturn[par] = NumericTraits<DerivativeValueType>::Zero;
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffValue = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc,diff);
for ( SizeValueType dim = 0; dim < ImageToImageMetricv4Type::MovingImageDimension; dim++ )
{
localDerivativeReturn[par] += 2.0 * diffValue * jacobian(dim, par) *
DefaultConvertPixelTraits<MovingImageGradientType>::GetNthComponent(
ImageToImageMetricv4Type::FixedImageDimension * nc + dim, movingImageGradient );
}
}
}
return true;
}
} // end namespace itk
#endif
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#define __itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader_hxx
#include "itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h"
#include "itkDefaultConvertPixelTraits.h"
namespace itk
{
template< class TDomainPartitioner, class TImageToImageMetric, class TMeanSquaresMetric >
bool
MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMeanSquaresMetric >
::ProcessPoint( const VirtualIndexType &,
const VirtualPointType & virtualPoint,
const FixedImagePointType &,
const FixedImagePixelType & fixedImageValue,
const FixedImageGradientType &,
const MovingImagePointType & ,
const MovingImagePixelType & movingImageValue,
const MovingImageGradientType & movingImageGradient,
MeasureType & metricValueReturn,
DerivativeType & localDerivativeReturn,
const ThreadIdType threadID) const
{
/** Only the voxelwise contribution given the point pairs. */
FixedImagePixelType diff = fixedImageValue - movingImageValue;
const unsigned int nComponents = NumericTraits<FixedImagePixelType>::GetLength( diff );
metricValueReturn = NumericTraits<MeasureType>::ZeroValue();
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffC = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc, diff);
metricValueReturn += diffC*diffC;
}
if( ! this->GetComputeDerivative() )
{
return true;
}
/* Use a pre-allocated jacobian object for efficiency */
typedef typename TImageToImageMetric::JacobianType & JacobianReferenceType;
JacobianReferenceType jacobian = this->m_MovingTransformJacobianPerThread[threadID];
/** For dense transforms, this returns identity */
this->m_Associate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian );
for ( unsigned int par = 0; par < this->GetCachedNumberOfLocalParameters(); par++ )
{
localDerivativeReturn[par] = NumericTraits<DerivativeValueType>::Zero;
for ( unsigned int nc = 0; nc < nComponents; nc++ )
{
MeasureType diffValue = DefaultConvertPixelTraits<FixedImagePixelType>::GetNthComponent(nc,diff);
for ( SizeValueType dim = 0; dim < ImageToImageMetricv4Type::MovingImageDimension; dim++ )
{
localDerivativeReturn[par] += 2.0 * diffValue * jacobian(dim, par) *
DefaultConvertPixelTraits<MovingImageGradientType>::GetNthComponent(
ImageToImageMetricv4Type::FixedImageDimension * nc + dim, movingImageGradient );
}
}
}
return true;
}
} // end namespace itk
#endif
|
Fix compilation error (missing include).
|
COMP: Fix compilation error (missing include).
Change-Id: I72d8e7ba771af7dfa6bb1e3359f45b6fa2f8ee0c
|
C++
|
apache-2.0
|
fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,richardbeare/ITK,blowekamp/ITK,LucHermitte/ITK,LucasGandel/ITK,msmolens/ITK,BRAINSia/ITK,hinerm/ITK,malaterre/ITK,LucHermitte/ITK,biotrump/ITK,fedral/ITK,LucHermitte/ITK,LucasGandel/ITK,atsnyder/ITK,ajjl/ITK,jcfr/ITK,blowekamp/ITK,hendradarwin/ITK,LucasGandel/ITK,hendradarwin/ITK,fedral/ITK,eile/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,BlueBrain/ITK,BRAINSia/ITK,atsnyder/ITK,eile/ITK,jcfr/ITK,malaterre/ITK,stnava/ITK,ajjl/ITK,Kitware/ITK,vfonov/ITK,biotrump/ITK,LucasGandel/ITK,jmerkow/ITK,zachary-williamson/ITK,fbudin69500/ITK,eile/ITK,GEHC-Surgery/ITK,hjmjohnson/ITK,fbudin69500/ITK,LucasGandel/ITK,ajjl/ITK,GEHC-Surgery/ITK,biotrump/ITK,stnava/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,malaterre/ITK,jmerkow/ITK,GEHC-Surgery/ITK,hinerm/ITK,ajjl/ITK,spinicist/ITK,PlutoniumHeart/ITK,stnava/ITK,heimdali/ITK,stnava/ITK,PlutoniumHeart/ITK,thewtex/ITK,jcfr/ITK,fedral/ITK,hendradarwin/ITK,malaterre/ITK,spinicist/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,malaterre/ITK,biotrump/ITK,fedral/ITK,BlueBrain/ITK,vfonov/ITK,hjmjohnson/ITK,ajjl/ITK,zachary-williamson/ITK,stnava/ITK,Kitware/ITK,biotrump/ITK,LucHermitte/ITK,InsightSoftwareConsortium/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,malaterre/ITK,fbudin69500/ITK,atsnyder/ITK,richardbeare/ITK,PlutoniumHeart/ITK,jcfr/ITK,jcfr/ITK,heimdali/ITK,fedral/ITK,eile/ITK,jcfr/ITK,hinerm/ITK,blowekamp/ITK,hinerm/ITK,atsnyder/ITK,spinicist/ITK,BRAINSia/ITK,malaterre/ITK,atsnyder/ITK,stnava/ITK,ajjl/ITK,fbudin69500/ITK,eile/ITK,Kitware/ITK,jcfr/ITK,InsightSoftwareConsortium/ITK,hendradarwin/ITK,LucHermitte/ITK,thewtex/ITK,fbudin69500/ITK,jmerkow/ITK,vfonov/ITK,hjmjohnson/ITK,fuentesdt/InsightToolkit-dev,BlueBrain/ITK,fuentesdt/InsightToolkit-dev,msmolens/ITK,eile/ITK,GEHC-Surgery/ITK,zachary-williamson/ITK,richardbeare/ITK,BlueBrain/ITK,LucasGandel/ITK,biotrump/ITK,Kitware/ITK,eile/ITK,GEHC-Surgery/ITK,PlutoniumHeart/ITK,ajjl/ITK,eile/ITK,PlutoniumHeart/ITK,blowekamp/ITK,biotrump/ITK,thewtex/ITK,malaterre/ITK,Kitware/ITK,eile/ITK,richardbeare/ITK,hjmjohnson/ITK,thewtex/ITK,hinerm/ITK,hjmjohnson/ITK,vfonov/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,thewtex/ITK,LucHermitte/ITK,hinerm/ITK,BlueBrain/ITK,BRAINSia/ITK,BlueBrain/ITK,richardbeare/ITK,atsnyder/ITK,fbudin69500/ITK,fuentesdt/InsightToolkit-dev,spinicist/ITK,BlueBrain/ITK,atsnyder/ITK,atsnyder/ITK,spinicist/ITK,thewtex/ITK,richardbeare/ITK,zachary-williamson/ITK,thewtex/ITK,heimdali/ITK,GEHC-Surgery/ITK,hendradarwin/ITK,Kitware/ITK,jmerkow/ITK,PlutoniumHeart/ITK,fuentesdt/InsightToolkit-dev,heimdali/ITK,hjmjohnson/ITK,spinicist/ITK,LucasGandel/ITK,heimdali/ITK,biotrump/ITK,GEHC-Surgery/ITK,spinicist/ITK,heimdali/ITK,msmolens/ITK,InsightSoftwareConsortium/ITK,LucHermitte/ITK,stnava/ITK,vfonov/ITK,msmolens/ITK,heimdali/ITK,heimdali/ITK,vfonov/ITK,fedral/ITK,msmolens/ITK,fedral/ITK,BRAINSia/ITK,jcfr/ITK,hinerm/ITK,InsightSoftwareConsortium/ITK,msmolens/ITK,jmerkow/ITK,fbudin69500/ITK,ajjl/ITK,blowekamp/ITK,hendradarwin/ITK,jmerkow/ITK,LucHermitte/ITK,BRAINSia/ITK,spinicist/ITK,hjmjohnson/ITK,jmerkow/ITK,zachary-williamson/ITK,vfonov/ITK,stnava/ITK,malaterre/ITK,hendradarwin/ITK,msmolens/ITK,spinicist/ITK,blowekamp/ITK,stnava/ITK,fuentesdt/InsightToolkit-dev,PlutoniumHeart/ITK,blowekamp/ITK,hinerm/ITK,jmerkow/ITK,msmolens/ITK,fuentesdt/InsightToolkit-dev,fbudin69500/ITK,BlueBrain/ITK,fedral/ITK,hinerm/ITK,blowekamp/ITK,GEHC-Surgery/ITK,vfonov/ITK
|
2e483138a71d08b981415cd677987a0f617e9f88
|
indra/newview/llviewerwindowlistener.cpp
|
indra/newview/llviewerwindowlistener.cpp
|
/**
* @file llviewerwindowlistener.cpp
* @author Nat Goodspeed
* @date 2009-06-30
* @brief Implementation for llviewerwindowlistener.
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
* Copyright (c) 2009, Linden Research, Inc.
* $/LicenseInfo$
*/
// Precompiled header
#include "llviewerprecompiledheaders.h"
// associated header
#include "llviewerwindowlistener.h"
// STL headers
#include <map>
// std headers
// external library headers
// other Linden headers
#include "llviewerwindow.h"
LLViewerWindowListener::LLViewerWindowListener(const std::string& pumpname, LLViewerWindow* llviewerwindow):
LLDispatchListener(pumpname, "op"),
mViewerWindow(llviewerwindow)
{
// add() every method we want to be able to invoke via this event API.
LLSD saveSnapshotArgs;
saveSnapshotArgs["filename"] = LLSD::String();
saveSnapshotArgs["reply"] = LLSD::String();
// The following are optional, so don't build them into required prototype.
// saveSnapshotArgs["width"] = LLSD::Integer();
// saveSnapshotArgs["height"] = LLSD::Integer();
// saveSnapshotArgs["showui"] = LLSD::Boolean();
// saveSnapshotArgs["rebuild"] = LLSD::Boolean();
// saveSnapshotArgs["type"] = LLSD::String();
add("saveSnapshot", &LLViewerWindowListener::saveSnapshot, saveSnapshotArgs);
add("requestReshape", &LLViewerWindowListener::requestReshape);
}
void LLViewerWindowListener::saveSnapshot(const LLSD& event) const
{
LLReqID reqid(event);
typedef std::map<LLSD::String, LLViewerWindow::ESnapshotType> TypeMap;
TypeMap types;
#define tp(name) types[#name] = LLViewerWindow::SNAPSHOT_TYPE_##name
tp(COLOR);
tp(DEPTH);
tp(OBJECT_ID);
#undef tp
// Our add() call should ensure that the incoming LLSD does in fact
// contain our required arguments. Deal with the optional ones.
S32 width (mViewerWindow->getWindowDisplayWidth());
S32 height(mViewerWindow->getWindowDisplayHeight());
if (event.has("width"))
width = event["width"].asInteger();
if (event.has("height"))
height = event["height"].asInteger();
// showui defaults to true, requiring special treatment
bool showui = true;
if (event.has("showui"))
showui = event["showui"].asBoolean();
bool rebuild(event["rebuild"]); // defaults to false
LLViewerWindow::ESnapshotType type(LLViewerWindow::SNAPSHOT_TYPE_COLOR);
if (event.has("type"))
{
TypeMap::const_iterator found = types.find(event["type"]);
if (found == types.end())
{
LL_ERRS("LLViewerWindowListener") << "LLViewerWindowListener::saveSnapshot(): "
<< "unrecognized type " << event["type"] << LL_ENDL;
}
type = found->second;
}
bool ok = mViewerWindow->saveSnapshot(event["filename"], width, height, showui, rebuild, type);
LLSD response(reqid.makeResponse());
response["ok"] = ok;
LLEventPumps::instance().obtain(event["reply"]).post(response);
}
void LLViewerWindowListener::requestReshape(LLSD const & event_data) const
{
if(event_data.has("w") && event_data.has("h"))
{
mViewerWindow->reshape(event_data["w"].asInteger(), event_data["h"].asInteger());
}
}
|
/**
* @file llviewerwindowlistener.cpp
* @author Nat Goodspeed
* @date 2009-06-30
* @brief Implementation for llviewerwindowlistener.
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
* Copyright (c) 2009, Linden Research, Inc.
* $/LicenseInfo$
*/
// Precompiled header
#include "llviewerprecompiledheaders.h"
// associated header
#include "llviewerwindowlistener.h"
// STL headers
#include <map>
// std headers
// external library headers
// other Linden headers
#include "llviewerwindow.h"
LLViewerWindowListener::LLViewerWindowListener(const std::string& pumpname, LLViewerWindow* llviewerwindow):
LLDispatchListener(pumpname, "op"),
mViewerWindow(llviewerwindow)
{
// add() every method we want to be able to invoke via this event API.
LLSD saveSnapshotArgs;
saveSnapshotArgs["filename"] = LLSD::String();
saveSnapshotArgs["reply"] = LLSD::String();
// The following are optional, so don't build them into required prototype.
// saveSnapshotArgs["width"] = LLSD::Integer();
// saveSnapshotArgs["height"] = LLSD::Integer();
// saveSnapshotArgs["showui"] = LLSD::Boolean();
// saveSnapshotArgs["rebuild"] = LLSD::Boolean();
// saveSnapshotArgs["type"] = LLSD::String();
add("saveSnapshot", &LLViewerWindowListener::saveSnapshot, saveSnapshotArgs);
add("requestReshape", &LLViewerWindowListener::requestReshape);
}
void LLViewerWindowListener::saveSnapshot(const LLSD& event) const
{
LLReqID reqid(event);
typedef std::map<LLSD::String, LLViewerWindow::ESnapshotType> TypeMap;
TypeMap types;
#define tp(name) types[#name] = LLViewerWindow::SNAPSHOT_TYPE_##name
tp(COLOR);
tp(DEPTH);
tp(OBJECT_ID);
#undef tp
// Our add() call should ensure that the incoming LLSD does in fact
// contain our required arguments. Deal with the optional ones.
S32 width (mViewerWindow->getWindowDisplayWidth());
S32 height(mViewerWindow->getWindowDisplayHeight());
if (event.has("width"))
width = event["width"].asInteger();
if (event.has("height"))
height = event["height"].asInteger();
// showui defaults to true, requiring special treatment
bool showui = true;
if (event.has("showui"))
showui = event["showui"].asBoolean();
bool rebuild(event["rebuild"]); // defaults to false
LLViewerWindow::ESnapshotType type(LLViewerWindow::SNAPSHOT_TYPE_COLOR);
if (event.has("type"))
{
TypeMap::const_iterator found = types.find(event["type"]);
if (found == types.end())
{
LL_ERRS("LLViewerWindowListener") << "LLViewerWindowListener::saveSnapshot(): "
<< "unrecognized type " << event["type"] << LL_ENDL;
}
type = found->second;
}
bool ok = mViewerWindow->saveSnapshot(event["filename"], width, height, showui, rebuild, type);
LLSD response(reqid.makeResponse());
response["ok"] = ok;
LLEventPumps::instance().obtain(event["reply"]).post(response);
}
void LLViewerWindowListener::requestReshape(LLSD const & event_data) const
{
if(event_data.has("w") && event_data.has("h"))
{
mViewerWindow->reshape(event_data["w"].asInteger(), event_data["h"].asInteger());
}
}
|
Add newline to end of file to placate Linux gcc
|
Add newline to end of file to placate Linux gcc
|
C++
|
lgpl-2.1
|
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
|
683fd6bc22853f831e241cf5acc31264460b7a9d
|
subsystem_base.hxx
|
subsystem_base.hxx
|
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <memory>
#include <unordered_map>
#include <forward_list>
#include <vector>
#include <mutex>
#include <boost/property_tree/ptree.hpp>
#include <boost/optional.hpp>
#ifdef EMSCRIPTEN
namespace
{
static std::mutex emscripten_main_loop_mutex;
}
#endif
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace subsystem
{
struct subsystem_runtime_error_t
: std::runtime_error
{
subsystem_runtime_error_t(const std::string& what)
: std::runtime_error(what)
{ }
};
struct version_t
{
std::uint16_t major, minor, revision;
auto to_string() -> std::string
{
return std::to_string(major) + "."
+ std::to_string(minor) + "."
+ std::to_string(revision)
;
}
};
class subsystem_base_t
: public std::enable_shared_from_this<subsystem_base_t>
{
public:
using initialize_param_key_t
= std::string;
using initialize_param_value_t
= boost::any;
using initialize_params_t
= boost::property_tree::ptree;
using update_functors_t
= std::forward_list
< std::function<void()>
>;
using render_functors_t
= update_functors_t;
using keyboard_states_t
= std::vector<bool>;
protected:
keyboard_states_t _keyboard_states;
bool _to_continue;
public:
update_functors_t update_functors;
render_functors_t render_functors;
subsystem_base_t()
{
_keyboard_states.resize( std::numeric_limits<key_code_t>::max() );
}
virtual ~subsystem_base_t() { }
virtual auto default_initialize_params() const
-> initialize_params_t
{ return initialize_params_t(); }
virtual auto initialize(initialize_params_t&&) -> void { }
virtual auto before_update() -> void { }
virtual auto after_update() -> void { }
virtual auto before_render() -> void { }
virtual auto after_render() -> void { }
virtual auto version() const -> version_t = 0;
virtual auto name() const -> std::string = 0;
virtual auto update() -> void
{
for ( const auto& f : update_functors )
f();
}
virtual auto render() -> void
{
for ( const auto& f : render_functors )
f();
}
virtual auto to_continue() const
-> bool
{ return _to_continue; }
virtual auto to_continue(const bool b)
-> void
{ _to_continue = b; }
template<key_code_t T_keycode>
inline auto keyboard_state() const
-> bool
{
static_assert(T_keycode >= std::numeric_limits<key_code_t>::min(), "T_keycode must: T_keycode >= std::numeric_limits<key_code_t>::min()");
static_assert(T_keycode <= std::numeric_limits<key_code_t>::max(), "T_keycode must: T_keycode <= std::numeric_limits<key_code_t>::max()");
return _keyboard_states[key_code_t(T_keycode)];
}
virtual auto keyboard_state(key_code_t keycode) const
-> bool
{ return _keyboard_states[keycode]; }
virtual auto keyboard_state(key_code_t keycode, bool action)
-> void
{ _keyboard_states[keycode] = action; }
virtual auto keyboard_states() const
-> const keyboard_states_t&
{ return _keyboard_states; }
virtual auto invoke()
-> void
{
_to_continue = true;
#ifdef EMSCRIPTEN
if( not ::emscripten_main_loop_mutex.try_lock() )
throw subsystem_runtime_error_t( "::emscripten_main_loop_mutex cannot lock" );
emscripten_set_main_loop_arg( [](void* arg)
{
auto this_ = reinterpret_cast<subsystem_base_t*>(arg);
this_ -> invoke_step();
if ( not this_ -> to_continue() )
{
emscripten_cancel_main_loop();
::emscripten_main_loop_mutex.unlock();
}
}
, this, 0, 1);
#else
do
invoke_step();
while ( to_continue() );
#endif
}
virtual auto invoke_step() -> void
{
before_update();
update();
after_update();
before_render();
render();
after_render();
}
};
}
}
}
|
#pragma once
#include <cstdint>
#include <stdexcept>
#include <string>
#include <memory>
#include <unordered_map>
#include <forward_list>
#include <vector>
#include <mutex>
#include <boost/property_tree/ptree.hpp>
#ifdef EMSCRIPTEN
namespace
{
static std::mutex emscripten_main_loop_mutex;
}
#endif
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace subsystem
{
struct subsystem_runtime_error_t
: std::runtime_error
{
subsystem_runtime_error_t(const std::string& what)
: std::runtime_error(what)
{ }
};
struct version_t
{
std::uint16_t major, minor, revision;
auto to_string() -> std::string
{
return std::to_string(major) + "."
+ std::to_string(minor) + "."
+ std::to_string(revision)
;
}
};
class subsystem_base_t
: public std::enable_shared_from_this<subsystem_base_t>
{
public:
using initialize_param_key_t
= std::string;
using initialize_param_value_t
= boost::any;
using initialize_params_t
= boost::property_tree::ptree;
using update_functors_t
= std::forward_list
< std::function<void()>
>;
using render_functors_t
= update_functors_t;
using keyboard_states_t
= std::vector<bool>;
protected:
keyboard_states_t _keyboard_states;
bool _to_continue;
public:
update_functors_t update_functors;
render_functors_t render_functors;
subsystem_base_t()
{
_keyboard_states.resize( std::numeric_limits<key_code_t>::max() );
}
virtual ~subsystem_base_t() { }
virtual auto default_initialize_params() const
-> initialize_params_t
{ return initialize_params_t(); }
virtual auto initialize(initialize_params_t&&) -> void { }
virtual auto before_update() -> void { }
virtual auto after_update() -> void { }
virtual auto before_render() -> void { }
virtual auto after_render() -> void { }
virtual auto version() const -> version_t = 0;
virtual auto name() const -> std::string = 0;
virtual auto update() -> void
{
for ( const auto& f : update_functors )
f();
}
virtual auto render() -> void
{
for ( const auto& f : render_functors )
f();
}
virtual auto to_continue() const
-> bool
{ return _to_continue; }
virtual auto to_continue(const bool b)
-> void
{ _to_continue = b; }
template<key_code_t T_keycode>
inline auto keyboard_state() const
-> bool
{
static_assert(T_keycode >= std::numeric_limits<key_code_t>::min(), "T_keycode must: T_keycode >= std::numeric_limits<key_code_t>::min()");
static_assert(T_keycode <= std::numeric_limits<key_code_t>::max(), "T_keycode must: T_keycode <= std::numeric_limits<key_code_t>::max()");
return _keyboard_states[key_code_t(T_keycode)];
}
virtual auto keyboard_state(key_code_t keycode) const
-> bool
{ return _keyboard_states[keycode]; }
virtual auto keyboard_state(key_code_t keycode, bool action)
-> void
{ _keyboard_states[keycode] = action; }
virtual auto keyboard_states() const
-> const keyboard_states_t&
{ return _keyboard_states; }
virtual auto invoke()
-> void
{
_to_continue = true;
#ifdef EMSCRIPTEN
if( not ::emscripten_main_loop_mutex.try_lock() )
throw subsystem_runtime_error_t( "::emscripten_main_loop_mutex cannot lock" );
emscripten_set_main_loop_arg( [](void* arg)
{
auto this_ = reinterpret_cast<subsystem_base_t*>(arg);
this_ -> invoke_step();
if ( not this_ -> to_continue() )
{
emscripten_cancel_main_loop();
::emscripten_main_loop_mutex.unlock();
}
}
, this, 0, 1);
#else
do
invoke_step();
while ( to_continue() );
#endif
}
virtual auto invoke_step() -> void
{
before_update();
update();
after_update();
before_render();
render();
after_render();
}
};
}
}
}
|
remove include (no using)
|
remove include (no using)
|
C++
|
mit
|
usagi/wonderland.subsystem,usagi/wonderland.subsystem
|
eed9d23e5be50727dd1a58a88b84426d5f009061
|
modules/perception/camera/lib/calibration_service/online_calibration_service/online_calibration_service.cc
|
modules/perception/camera/lib/calibration_service/online_calibration_service/online_calibration_service.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/camera/lib/calibration_service/online_calibration_service/online_calibration_service.h"
#include <utility>
#include "modules/perception/common/i_lib/core/i_blas.h"
#include "modules/perception/common/i_lib/core/i_constant.h"
#include "modules/perception/common/i_lib/geometry/i_util.h"
namespace apollo {
namespace perception {
namespace camera {
bool OnlineCalibrationService::Init(
const CalibrationServiceInitOptions &options) {
master_sensor_name_ = options.calibrator_working_sensor_name;
sensor_name_ = options.calibrator_working_sensor_name;
// Init k_matrix
auto &name_intrinsic_map = options.name_intrinsic_map;
CHECK(name_intrinsic_map.find(master_sensor_name_) !=
name_intrinsic_map.end());
CameraStatus camera_status;
name_camera_status_map_.clear();
for (auto iter = name_intrinsic_map.begin(); iter != name_intrinsic_map.end();
++iter) {
camera_status.k_matrix[0] = static_cast<double>(iter->second(0, 0));
camera_status.k_matrix[4] = static_cast<double>(iter->second(1, 1));
camera_status.k_matrix[2] = static_cast<double>(iter->second(0, 2));
camera_status.k_matrix[5] = static_cast<double>(iter->second(1, 2));
camera_status.k_matrix[8] = 1.0;
name_camera_status_map_.insert(
std::pair<std::string, CameraStatus>(iter->first, camera_status));
}
// Only init calibrator on master_sensor
CalibratorInitOptions calibrator_init_options;
calibrator_init_options.image_width = options.image_width;
calibrator_init_options.image_height = options.image_height;
calibrator_init_options.focal_x = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[0]);
calibrator_init_options.focal_y = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[4]);
calibrator_init_options.cx = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[2]);
calibrator_init_options.cy = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[5]);
calibrator_.reset(
BaseCalibratorRegisterer::GetInstanceByName(options.calibrator_method));
CHECK(calibrator_ != nullptr);
CHECK(calibrator_->Init(calibrator_init_options))
<< "Failed to init " << options.calibrator_method;
return true;
}
bool OnlineCalibrationService::BuildIndex() {
is_service_ready_ = HasSetIntrinsics() && HasSetGroundPlane();
return is_service_ready_;
}
bool OnlineCalibrationService::QueryDepthOnGroundPlane(int x, int y,
double *depth) const {
if (!is_service_ready_) {
return false;
}
CHECK(depth != nullptr);
double pixel[2] = {static_cast<double>(x), static_cast<double>(y)};
double point[3] = {0};
auto iter = name_camera_status_map_.find(sensor_name_);
bool success = common::IBackprojectPlaneIntersectionCanonical(
pixel, &(iter->second.k_matrix[0]), &(iter->second.ground_plane[0]),
point);
if (!success) {
*depth = 0.0;
return false;
}
*depth = point[2];
return true;
}
bool OnlineCalibrationService::QueryPoint3dOnGroundPlane(
int x, int y, Eigen::Vector3d *point3d) const {
if (!is_service_ready_) {
return false;
}
CHECK(point3d != nullptr);
double pixel[2] = {static_cast<double>(x), static_cast<double>(y)};
double point[3] = {0};
auto iter = name_camera_status_map_.find(sensor_name_);
bool success = common::IBackprojectPlaneIntersectionCanonical(
pixel, &(iter->second.k_matrix[0]), &(iter->second.ground_plane[0]),
point);
if (!success) {
(*point3d)(0) = (*point3d)(1) = (*point3d)(2) = 0.0;
return false;
}
(*point3d)(0) = point[0];
(*point3d)(1) = point[1];
(*point3d)(2) = point[2];
return true;
}
bool OnlineCalibrationService::QueryGroundPlaneInCameraFrame(
Eigen::Vector4d *plane_param) const {
CHECK(plane_param != nullptr);
if (!is_service_ready_) {
(*plane_param)(0) = (*plane_param)(1) = (*plane_param)(2) =
(*plane_param)(3) = 0.0;
return false;
}
auto iter = name_camera_status_map_.find(sensor_name_);
(*plane_param)(0) = iter->second.ground_plane[0];
(*plane_param)(1) = iter->second.ground_plane[1];
(*plane_param)(2) = iter->second.ground_plane[2];
(*plane_param)(3) = iter->second.ground_plane[3];
return true;
}
bool OnlineCalibrationService::QueryCameraToGroundHeightAndPitchAngle(
float *height, float *pitch) const {
CHECK(height != nullptr);
CHECK(pitch != nullptr);
if (!is_service_ready_) {
*height = *pitch = 0.0;
return false;
}
auto iter = name_camera_status_map_.find(sensor_name_);
*height = iter->second.camera_ground_height;
*pitch = iter->second.pitch_angle;
return true;
}
void OnlineCalibrationService::Update(CameraFrame *frame) {
CHECK(frame != nullptr);
sensor_name_ = frame->data_provider->sensor_name();
if (sensor_name_ == master_sensor_name_) {
CalibratorOptions calibrator_options;
calibrator_options.lane_objects =
std::make_shared<std::vector<base::LaneLine>>(frame->lane_objects);
calibrator_options.camera2world_pose =
std::make_shared<Eigen::Affine3d>(frame->camera2world_pose);
calibrator_options.timestamp = &(frame->timestamp);
float pitch_angle = 0.f;
bool updated = calibrator_->Calibrate(calibrator_options, &pitch_angle);
// rebuild the service when updated
if (updated) {
name_camera_status_map_[master_sensor_name_].pitch_angle = pitch_angle;
for (auto iter = name_camera_status_map_.begin();
iter != name_camera_status_map_.end(); iter++) {
// update pitch angle
iter->second.pitch_angle =
iter->second.pitch_angle_diff + iter->second.pitch_angle;
// update ground plane param
iter->second.ground_plane[1] = cos(iter->second.pitch_angle);
iter->second.ground_plane[2] = -sin(iter->second.pitch_angle);
}
}
}
auto iter = name_camera_status_map_.find(sensor_name_);
AINFO << "camera_ground_height: " << iter->second.camera_ground_height
<< " meter.";
AINFO << "pitch_angle: " << iter->second.pitch_angle * 180.0 / M_PI
<< " degree.";
// CHECK(BuildIndex());
}
void OnlineCalibrationService::SetCameraHeightAndPitch(
const std::map<std::string, float> &name_camera_ground_height_map,
const std::map<std::string, float> &name_camera_pitch_angle_diff_map,
const float &pitch_angle_master_sensor) {
name_camera_status_map_[master_sensor_name_].pitch_angle =
pitch_angle_master_sensor;
for (auto iter = name_camera_status_map_.begin();
iter != name_camera_status_map_.end(); ++iter) {
// get iters
auto iter_ground_height = name_camera_ground_height_map.find(iter->first);
auto iter_pitch_angle = name_camera_pitch_angle_diff_map.find(iter->first);
auto iter_pitch_angle_diff =
name_camera_pitch_angle_diff_map.find(iter->first);
CHECK(iter_ground_height != name_camera_ground_height_map.end());
CHECK(iter_pitch_angle != name_camera_pitch_angle_diff_map.end());
CHECK(iter_pitch_angle_diff != name_camera_pitch_angle_diff_map.end());
// set camera status
name_camera_status_map_[iter->first].camera_ground_height =
iter_ground_height->second;
name_camera_status_map_[iter->first].pitch_angle_diff =
iter_pitch_angle->second;
name_camera_status_map_[iter->first].pitch_angle =
pitch_angle_master_sensor + iter_pitch_angle_diff->second;
name_camera_status_map_[iter->first].ground_plane[1] =
cos(name_camera_status_map_[iter->first].pitch_angle);
name_camera_status_map_[iter->first].ground_plane[2] =
-sin(name_camera_status_map_[iter->first].pitch_angle);
name_camera_status_map_[iter->first].ground_plane[3] =
-name_camera_status_map_[iter->first].camera_ground_height;
}
}
std::string OnlineCalibrationService::Name() const {
return "OnlineCalibrationService";
}
REGISTER_CALIBRATION_SERVICE(OnlineCalibrationService);
} // namespace camera
} // namespace perception
} // namespace apollo
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/camera/lib/calibration_service/online_calibration_service/online_calibration_service.h"
#include <utility>
#include "modules/perception/common/i_lib/core/i_blas.h"
#include "modules/perception/common/i_lib/core/i_constant.h"
#include "modules/perception/common/i_lib/geometry/i_util.h"
namespace apollo {
namespace perception {
namespace camera {
bool OnlineCalibrationService::Init(
const CalibrationServiceInitOptions &options) {
master_sensor_name_ = options.calibrator_working_sensor_name;
sensor_name_ = options.calibrator_working_sensor_name;
// Init k_matrix
auto &name_intrinsic_map = options.name_intrinsic_map;
CHECK(name_intrinsic_map.find(master_sensor_name_) !=
name_intrinsic_map.end());
CameraStatus camera_status;
name_camera_status_map_.clear();
for (auto iter = name_intrinsic_map.begin(); iter != name_intrinsic_map.end();
++iter) {
camera_status.k_matrix[0] = static_cast<double>(iter->second(0, 0));
camera_status.k_matrix[4] = static_cast<double>(iter->second(1, 1));
camera_status.k_matrix[2] = static_cast<double>(iter->second(0, 2));
camera_status.k_matrix[5] = static_cast<double>(iter->second(1, 2));
camera_status.k_matrix[8] = 1.0;
name_camera_status_map_.insert(
std::pair<std::string, CameraStatus>(iter->first, camera_status));
}
// Only init calibrator on master_sensor
CalibratorInitOptions calibrator_init_options;
calibrator_init_options.image_width = options.image_width;
calibrator_init_options.image_height = options.image_height;
calibrator_init_options.focal_x = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[0]);
calibrator_init_options.focal_y = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[4]);
calibrator_init_options.cx = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[2]);
calibrator_init_options.cy = static_cast<float>(
name_camera_status_map_[master_sensor_name_].k_matrix[5]);
calibrator_.reset(
BaseCalibratorRegisterer::GetInstanceByName(options.calibrator_method));
CHECK(calibrator_ != nullptr);
CHECK(calibrator_->Init(calibrator_init_options))
<< "Failed to init " << options.calibrator_method;
return true;
}
bool OnlineCalibrationService::BuildIndex() {
is_service_ready_ = HasSetIntrinsics() && HasSetGroundPlane();
return is_service_ready_;
}
bool OnlineCalibrationService::QueryDepthOnGroundPlane(int x, int y,
double *depth) const {
if (!is_service_ready_) {
return false;
}
CHECK(depth != nullptr);
double pixel[2] = {static_cast<double>(x), static_cast<double>(y)};
double point[3] = {0};
auto iter = name_camera_status_map_.find(sensor_name_);
bool success = common::IBackprojectPlaneIntersectionCanonical(
pixel, &(iter->second.k_matrix[0]), &(iter->second.ground_plane[0]),
point);
if (!success) {
*depth = 0.0;
return false;
}
*depth = point[2];
return true;
}
bool OnlineCalibrationService::QueryPoint3dOnGroundPlane(
int x, int y, Eigen::Vector3d *point3d) const {
if (!is_service_ready_) {
return false;
}
CHECK(point3d != nullptr);
double pixel[2] = {static_cast<double>(x), static_cast<double>(y)};
double point[3] = {0};
auto iter = name_camera_status_map_.find(sensor_name_);
bool success = common::IBackprojectPlaneIntersectionCanonical(
pixel, &(iter->second.k_matrix[0]), &(iter->second.ground_plane[0]),
point);
if (!success) {
(*point3d)(0) = (*point3d)(1) = (*point3d)(2) = 0.0;
return false;
}
(*point3d)(0) = point[0];
(*point3d)(1) = point[1];
(*point3d)(2) = point[2];
return true;
}
bool OnlineCalibrationService::QueryGroundPlaneInCameraFrame(
Eigen::Vector4d *plane_param) const {
CHECK(plane_param != nullptr);
if (!is_service_ready_) {
(*plane_param)(0) = (*plane_param)(1) = (*plane_param)(2) =
(*plane_param)(3) = 0.0;
return false;
}
auto iter = name_camera_status_map_.find(sensor_name_);
(*plane_param)(0) = iter->second.ground_plane[0];
(*plane_param)(1) = iter->second.ground_plane[1];
(*plane_param)(2) = iter->second.ground_plane[2];
(*plane_param)(3) = iter->second.ground_plane[3];
return true;
}
bool OnlineCalibrationService::QueryCameraToGroundHeightAndPitchAngle(
float *height, float *pitch) const {
CHECK(height != nullptr);
CHECK(pitch != nullptr);
if (!is_service_ready_) {
*height = *pitch = 0.0;
return false;
}
auto iter = name_camera_status_map_.find(sensor_name_);
*height = iter->second.camera_ground_height;
*pitch = iter->second.pitch_angle;
return true;
}
void OnlineCalibrationService::Update(CameraFrame *frame) {
CHECK(frame != nullptr);
sensor_name_ = frame->data_provider->sensor_name();
if (sensor_name_ == master_sensor_name_) {
CalibratorOptions calibrator_options;
calibrator_options.lane_objects =
std::make_shared<std::vector<base::LaneLine>>(frame->lane_objects);
calibrator_options.camera2world_pose =
std::make_shared<Eigen::Affine3d>(frame->camera2world_pose);
calibrator_options.timestamp = &(frame->timestamp);
float pitch_angle = 0.f;
bool updated = calibrator_->Calibrate(calibrator_options, &pitch_angle);
// rebuild the service when updated
if (updated) {
name_camera_status_map_[master_sensor_name_].pitch_angle = pitch_angle;
for (auto iter = name_camera_status_map_.begin();
iter != name_camera_status_map_.end(); iter++) {
// update pitch angle
iter->second.pitch_angle =
iter->second.pitch_angle_diff + iter->second.pitch_angle;
// update ground plane param
iter->second.ground_plane[1] = cos(iter->second.pitch_angle);
iter->second.ground_plane[2] = -sin(iter->second.pitch_angle);
}
}
}
auto iter = name_camera_status_map_.find(sensor_name_);
AINFO << "camera_ground_height: " << iter->second.camera_ground_height
<< " meter.";
AINFO << "pitch_angle: " << iter->second.pitch_angle * 180.0 / M_PI
<< " degree.";
// CHECK(BuildIndex());
is_service_ready_ = true;
}
void OnlineCalibrationService::SetCameraHeightAndPitch(
const std::map<std::string, float> &name_camera_ground_height_map,
const std::map<std::string, float> &name_camera_pitch_angle_diff_map,
const float &pitch_angle_master_sensor) {
name_camera_status_map_[master_sensor_name_].pitch_angle =
pitch_angle_master_sensor;
for (auto iter = name_camera_status_map_.begin();
iter != name_camera_status_map_.end(); ++iter) {
// get iters
auto iter_ground_height = name_camera_ground_height_map.find(iter->first);
auto iter_pitch_angle = name_camera_pitch_angle_diff_map.find(iter->first);
auto iter_pitch_angle_diff =
name_camera_pitch_angle_diff_map.find(iter->first);
CHECK(iter_ground_height != name_camera_ground_height_map.end());
CHECK(iter_pitch_angle != name_camera_pitch_angle_diff_map.end());
CHECK(iter_pitch_angle_diff != name_camera_pitch_angle_diff_map.end());
// set camera status
name_camera_status_map_[iter->first].camera_ground_height =
iter_ground_height->second;
name_camera_status_map_[iter->first].pitch_angle_diff =
iter_pitch_angle->second;
name_camera_status_map_[iter->first].pitch_angle =
pitch_angle_master_sensor + iter_pitch_angle_diff->second;
name_camera_status_map_[iter->first].ground_plane[1] =
cos(name_camera_status_map_[iter->first].pitch_angle);
name_camera_status_map_[iter->first].ground_plane[2] =
-sin(name_camera_status_map_[iter->first].pitch_angle);
name_camera_status_map_[iter->first].ground_plane[3] =
-name_camera_status_map_[iter->first].camera_ground_height;
}
}
std::string OnlineCalibrationService::Name() const {
return "OnlineCalibrationService";
}
REGISTER_CALIBRATION_SERVICE(OnlineCalibrationService);
} // namespace camera
} // namespace perception
} // namespace apollo
|
update status flag to avoid printing wrong error message at debug_infor.cc line 299 (#9046)
|
update status flag to avoid printing wrong error message at debug_infor.cc line 299 (#9046)
|
C++
|
apache-2.0
|
xiaoxq/apollo,xiaoxq/apollo,jinghaomiao/apollo,ycool/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,wanglei828/apollo,ApolloAuto/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo,wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,ApolloAuto/apollo,ycool/apollo,xiaoxq/apollo,ApolloAuto/apollo,ApolloAuto/apollo,xiaoxq/apollo,ApolloAuto/apollo,ycool/apollo
|
2c595cdd871bf09f232e5df65a17e87edf0ffd1b
|
PWGCF/EBYE/MultPt/AliAnalysisMultPt.cxx
|
PWGCF/EBYE/MultPt/AliAnalysisMultPt.cxx
|
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AliAnalysisMultPt:
// Description: Analysis task to get multiplicity
// and pT distributions
// Author: Negin Alizadehvandchali
// ([email protected])
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "TChain.h"
#include "TH3D.h"
#include "TTree.h"
#include "TProfile.h"
#include "TString.h"
#include "TList.h"
#include "AliAnalysisTask.h"
#include "AliAODTrack.h"
#include "AliMultSelection.h"
#include "AliAnalysisManager.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisMultPt.h"
#include "AliAODMCParticle.h"
#include "AliEventCuts.h"
#include "AliAODMCHeader.h"
using namespace std; // std namespace: so you can do things like 'cout'
ClassImp(AliAnalysisMultPt) // classimp: necessary for root
//___________________________________________________________________________________
AliAnalysisMultPt::AliAnalysisMultPt() : AliAnalysisTaskSE(),
fAOD(0), fOutputList(0), MultHist(0), MultPtHist(0), MultPtHistRec(0), MultPtHistGen(0), MultHistRatio(0), fIsMC(0), fPtmin(0.2), fPtmax(5.0), fEtaMin(-0.8), fEtaMax(0.8), fBit(96), fPVzMax(8.0), fPVzMin(0.0), fChi2DoF(3), fTPCNCrossedRows(70), fIsRunFBOnly(0), fTPCNcls(70), fEventCuts(0), fIsPileUpCuts(0), fPileUpLevel(2), fGenName("Hijing")
{
}
//___________________________________________________________________________________
AliAnalysisMultPt::AliAnalysisMultPt(const char* name) : AliAnalysisTaskSE(name),
fAOD(0), fOutputList(0), MultHist(0), MultPtHist(0), MultPtHistRec(0), MultPtHistGen(0), MultHistRatio(0), fIsMC(0), fPtmin(0.2), fPtmax(5.0), fEtaMin(-0.8), fEtaMax(0.8), fBit(96), fPVzMax(8.0), fPVzMin(0.0), fChi2DoF(3), fTPCNCrossedRows(70), fIsRunFBOnly(0), fTPCNcls(70), fEventCuts(0), fIsPileUpCuts(0), fPileUpLevel(2), fGenName("Hijing")
{
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
//___________________________________________________________________________________
AliAnalysisMultPt::~AliAnalysisMultPt()
{
// destructor
if(fOutputList) {
delete fOutputList; // at the end of your task, it is deleted from memory by calling this function
}
}
//___________________________________________________________________________________
void AliAnalysisMultPt::UserCreateOutputObjects()
{
// Initialize output list of containers
if (fOutputList != NULL) {
delete fOutputList;
fOutputList = NULL;
}
if (!fOutputList) {
fOutputList = new TList();
fOutputList->SetOwner(kTRUE);
}
//______________________________________ Raw Data:
MultHist = new TH1D("MultHist", "Mult", 4000, 0, 4000);
fOutputList->Add(MultHist);
MultHist->SetTitle("Multiplicity Distribution - Data");
MultHist->SetXTitle("N_{ch}");
MultHist->SetYTitle("Number of Events");
MultHist->SetMarkerSize(1.2);
MultPtHist = new TH2D("MultPtHist", "MultpT", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHist);
MultPtHist->SetTitle("pT vs Multiplicity - Data");
MultPtHist->SetXTitle("N_{ch}");
MultPtHist->SetYTitle("pT");
MultPtHist->SetMarkerSize(1.2);
if(fIsMC) {
//______________________________________ Reconstructed:
MultPtHistRec = new TH2D("MultPtHistRec", "MultPt-Rec", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHistRec);
MultPtHistRec->SetTitle("pT vs Reconstructed Multiplicity");
MultPtHistRec->SetXTitle("Reconstructed N_{ch}");
MultPtHistRec->SetYTitle("pT");
MultPtHistRec->SetMarkerSize(1.2);
//______________________________________ Generated:
MultPtHistGen = new TH2D("MultPtHistGen", "MultPt-Gen", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHistGen);
MultPtHistGen->SetTitle("pT vs Generated Multiplicity");
MultPtHistGen->SetXTitle("Generated N_{ch}");
MultPtHistGen->SetYTitle("pT");
MultPtHistGen->SetMarkerSize(1.2);
//______________________________________ Ratio of Gen mult over Rec mult:
MultHistRatio = new TH2D("MultHistRatio", "Ratio", 4000, 0, 4000, 4000, 0, 4000);
fOutputList->Add(MultHistRatio);
MultHistRatio->SetTitle("Generated Multiplicity vs Reconstructed");
MultHistRatio->SetXTitle("Reconstructed N_{ch}");
MultHistRatio->SetYTitle("Generated N_{ch}");
MultHistRatio->SetMarkerSize(1.2);
}
// add the list to our output file
PostData(1, fOutputList);
//PostData(1, mixer);
}
//___________________________________________________________________________________
void AliAnalysisMultPt::UserExec(Option_t *)
{
// get an event from the analysis manager:
fAOD = dynamic_cast<AliAODEvent*> (InputEvent());
// check if there actually is an event:
if(!fAOD) return;
if(fIsPileUpCuts){
fEventCuts.fUseITSTPCCluCorrelationCut = fPileUpLevel;
if (!fEventCuts.AcceptEvent(fAOD)) return;
}
TClonesArray *stack =0;
if(fIsMC) {
TList *lst = fAOD->GetList();
stack = (TClonesArray*)lst->FindObject(AliAODMCParticle::StdBranchName());
if(!stack) return;
}
if(fIsPileUpCuts){
AliAODMCHeader *mcHeader = 0;
mcHeader = (AliAODMCHeader*)fAOD->GetList()->FindObject(AliAODMCHeader::StdBranchName());
if(!mcHeader) {
printf("AliAnalysisTaskSEHFTreeCreator::UserExec: MC header branch not found!\n");
return;
}
Bool_t isPileupInGeneratedEvent = kFALSE;
isPileupInGeneratedEvent = AliAnalysisUtils::IsPileupInGeneratedEvent(mcHeader, fGenName);
if(isPileupInGeneratedEvent) return;
}
//making a cut in pvz -8 to 8cm
const AliAODVertex *PrimaryVertex = fAOD->GetVertex(0);
if(!PrimaryVertex) return;
Float_t PVz = PrimaryVertex->GetZ();
if(fabs(PVz)>fPVzMax) return;
if(fabs(PVz)<fPVzMin) return;
//___________________________________________________________________________________ Raw Data:
if(!fIsMC){
//For charged particle
int Mult=0;
// loop over all these tracks:
for(Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
// if we failed, skip this track
if(!track) continue;
if(!fIsRunFBOnly){
if(track->GetTPCNcls()<fTPCNcls || track->GetTPCNCrossedRows()<fTPCNCrossedRows || track->Chi2perNDF() > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
}
if(track->Charge()==0) continue;//only get charged tracks
if(track->Eta() > fEtaMax || track->Eta() < fEtaMin) continue;//eta cut
if(track->Pt() < fPtmin|| track->Pt() > fPtmax) continue; //pt cut
if(!track->TestFilterBit(fBit)) continue;
Mult++;
}
//Number of events vs multiplicity
MultHist->Fill(Mult);
for( Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
// if we failed, skip this track:
if(!track) continue;
if(track->Charge()==0) continue;//only get charged tracks
if(track->Eta() > fEtaMax || track->Eta() < fEtaMin) continue;//eta cut
if(track->Pt() < fPtmin|| track->Pt() > fPtmax) continue; //pt cut
if(!track->TestFilterBit(fBit)) continue;
MultPtHist->Fill(Mult, track->Pt());
}
}
//___________________________________________________________________________________ MONTE-CARLO:
if(fIsMC){
//______________________________________ RECONSTRUCTED part:
int MultRec=0; //Reconstructed Multiplicity
for(Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i)); // get a track (type AliAODTrack) from the event
if(!track) continue;
if(!track->TestFilterBit(fBit)) continue;
int label = TMath::Abs(track->GetLabel());
//mcTrack is the reconstructed track
AliAODMCParticle* mcTrack = dynamic_cast<AliAODMCParticle*>(stack->At(label));
if (!mcTrack) continue;
if (!mcTrack->IsPhysicalPrimary()) continue;
Float_t pTrec = mcTrack->Pt(); //reconstructed pT
Float_t etarec = mcTrack->Eta(); //reconstructed Eta
Short_t chargeMCRec = mcTrack->Charge(); //reconstructed charge
Float_t crossedrows = track->GetTPCNCrossedRows();
Float_t chi2 = track->Chi2perNDF();
Float_t ncl = track->GetTPCNcls();
Int_t isfb = 0;
if(track->TestFilterBit(fBit)) isfb=1;
if(isfb==0) continue; //choose filterbit
if(ncl<fTPCNcls || crossedrows<fTPCNCrossedRows || chi2 > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
if(abs(chargeMCRec)<=1) continue;
if(etarec > fEtaMax || etarec < fEtaMin) continue;//eta cut
if(pTrec < fPtmin || pTrec > fPtmax) continue; //pt cut
MultRec++;
}
for( Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
if(!track) continue;
if(!track->TestFilterBit(fBit)) continue;
int label = TMath::Abs(track->GetLabel());
//mcTrack is the reconstructed track
AliAODMCParticle* mcTrack = dynamic_cast<AliAODMCParticle*>(stack->At(label));
if (!mcTrack) continue;
if(!mcTrack->IsPhysicalPrimary()) continue;
Float_t pTrec = mcTrack->Pt(); //reconstructed pT
Float_t etarec = mcTrack->Eta(); //reconstructed Eta
Short_t chargeMCRec = mcTrack->Charge();
Float_t crossedrows = track->GetTPCNCrossedRows();
Float_t chi2 = track->Chi2perNDF();
Float_t ncl = track->GetTPCNcls();
Int_t isfb = 0;
if(track->TestFilterBit(fBit)) isfb=1;
if(isfb==0) continue;//choose filterbit
if(ncl<fTPCNcls || crossedrows<fTPCNCrossedRows || chi2 > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
if(abs(chargeMCRec)<=1) continue;
if(etarec > fEtaMax || etarec < fEtaMin) continue; //eta cut
if(pTrec < fPtmin || pTrec > fPtmax) continue; //pt cut
MultPtHistRec->Fill(MultRec, pTrec);
}
//______________________________________ GENERATED part:
int nMCTracks;
if (!stack) nMCTracks = 0;
else nMCTracks = stack->GetEntries();
int MultGen = 0; //Generated Multiplicity
for ( Int_t i(0); i < nMCTracks; i++) {
AliAODMCParticle *p1=(AliAODMCParticle*)stack->UncheckedAt(i);
if(!p1) continue;
if(!p1->IsPhysicalPrimary()) continue;
Float_t pTMCgen = p1->Pt();
Float_t etaMCgen = p1->Eta();
Short_t chargeMCgen = p1->Charge();
if(etaMCgen > fEtaMax || etaMCgen < fEtaMin ) continue;
if(pTMCgen < fPtmin|| pTMCgen > fPtmax) continue;
if(abs(chargeMCgen)<=1) continue;
MultGen++;
}
for ( Int_t i(0); i < nMCTracks; i++) {
AliAODMCParticle *p1=(AliAODMCParticle*)stack->UncheckedAt(i);
if (!p1) continue;
if(!p1->IsPhysicalPrimary()) continue;
Float_t pTMCgen = p1->Pt();
Float_t etaMCgen = p1->Eta();
Short_t chargeMCgen = p1->Charge();
if(etaMCgen > fEtaMax || etaMCgen < fEtaMin ) continue;
if(pTMCgen < fPtmin|| pTMCgen > fPtmax) continue;
if(abs(chargeMCgen)<=1) continue;
MultPtHistGen->Fill(MultGen, pTMCgen);
}
//Generated Mult vs Reconstructed Mult
MultHistRatio->Fill(MultRec, MultGen);
}
PostData(1, fOutputList);
}
//________________________________________________________________________
void AliAnalysisMultPt::Terminate(Option_t *)
{
// terminate
// called at the END of the analysis (when all events are processed)
}
|
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AliAnalysisMultPt:
// Description: Analysis task to get multiplicity
// and pT distributions
// Author: Negin Alizadehvandchali
// ([email protected])
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "TChain.h"
#include "TH3D.h"
#include "TTree.h"
#include "TProfile.h"
#include "TString.h"
#include "TList.h"
#include "AliAnalysisTask.h"
#include "AliAODTrack.h"
#include "AliMultSelection.h"
#include "AliAnalysisManager.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisMultPt.h"
#include "AliAODMCParticle.h"
#include "AliEventCuts.h"
#include "AliAODMCHeader.h"
#include "TCanvas.h"
using namespace std; // std namespace: so you can do things like 'cout'
ClassImp(AliAnalysisMultPt) // classimp: necessary for root
//___________________________________________________________________________________
AliAnalysisMultPt::AliAnalysisMultPt() : AliAnalysisTaskSE(),
fAOD(0), fOutputList(0), MultHist(0), MultPtHist(0), MultPtHistRec(0), MultPtHistGen(0), MultHistRatio(0), fIsMC(0), fPtmin(0.2), fPtmax(5.0), fEtaMin(-0.8), fEtaMax(0.8), fBit(96), fPVzMax(8.0), fPVzMin(0.0), fChi2DoF(3), fTPCNCrossedRows(70), fIsRunFBOnly(0), fTPCNcls(70), fEventCuts(0), fIsPileUpCuts(0), fPileUpLevel(2), fGenName("Hijing")
{
}
//___________________________________________________________________________________
AliAnalysisMultPt::AliAnalysisMultPt(const char* name) : AliAnalysisTaskSE(name),
fAOD(0), fOutputList(0), MultHist(0), MultPtHist(0), MultPtHistRec(0), MultPtHistGen(0), MultHistRatio(0), fIsMC(0), fPtmin(0.2), fPtmax(5.0), fEtaMin(-0.8), fEtaMax(0.8), fBit(96), fPVzMax(8.0), fPVzMin(0.0), fChi2DoF(3), fTPCNCrossedRows(70), fIsRunFBOnly(0), fTPCNcls(70), fEventCuts(0), fIsPileUpCuts(0), fPileUpLevel(2), fGenName("Hijing")
{
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
//___________________________________________________________________________________
AliAnalysisMultPt::~AliAnalysisMultPt()
{
// destructor
if(fOutputList) {
delete fOutputList; // at the end of your task, it is deleted from memory by calling this function
}
}
//___________________________________________________________________________________
void AliAnalysisMultPt::UserCreateOutputObjects()
{
// Initialize output list of containers
if (fOutputList != NULL) {
delete fOutputList;
fOutputList = NULL;
}
if (!fOutputList) {
fOutputList = new TList();
fOutputList->SetOwner(kTRUE);
}
//______________________________________ Raw Data:
MultHist = new TH1D("MultHist", "Mult", 4000, 0, 4000);
fOutputList->Add(MultHist);
MultHist->SetTitle("Multiplicity Distribution - Data");
MultHist->SetXTitle("N_{ch}");
MultHist->SetYTitle("Number of Events");
MultHist->SetMarkerSize(1.2);
MultPtHist = new TH2D("MultPtHist", "MultpT", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHist);
MultPtHist->SetTitle("pT vs Multiplicity - Data");
MultPtHist->SetXTitle("N_{ch}");
MultPtHist->SetYTitle("pT");
MultPtHist->SetMarkerSize(1.2);
//______________________________________ Reconstructed:
MultPtHistRec = new TH2D("MultPtHistRec", "MultPt-Rec", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHistRec);
MultPtHistRec->SetTitle("pT vs Reconstructed Multiplicity");
MultPtHistRec->SetXTitle("Reconstructed N_{ch}");
MultPtHistRec->SetYTitle("pT");
MultPtHistRec->SetMarkerSize(1.2);
//______________________________________ Generated:
MultPtHistGen = new TH2D("MultPtHistGen", "MultPt-Gen", 4000, 0, 4000, 50, 0, 5);
fOutputList->Add(MultPtHistGen);
MultPtHistGen->SetTitle("pT vs Generated Multiplicity");
MultPtHistGen->SetXTitle("Generated N_{ch}");
MultPtHistGen->SetYTitle("pT");
MultPtHistGen->SetMarkerSize(1.2);
//______________________________________ Ratio of Gen mult over Rec mult:
MultHistRatio = new TH2D("MultHistRatio", "Ratio", 4000, 0, 4000, 4000, 0, 4000);
fOutputList->Add(MultHistRatio);
MultHistRatio->SetTitle("Generated Multiplicity vs Reconstructed");
MultHistRatio->SetXTitle("Reconstructed N_{ch}");
MultHistRatio->SetYTitle("Generated N_{ch}");
MultHistRatio->SetMarkerSize(1.2);
// add the list to our output file
PostData(1, fOutputList);
}
//___________________________________________________________________________________
void AliAnalysisMultPt::UserExec(Option_t *)
{
// get an event from the analysis manager:
fAOD = dynamic_cast<AliAODEvent*> (InputEvent());
// check if there actually is an event:
if(!fAOD) return;
if(fIsPileUpCuts){
fEventCuts.fUseITSTPCCluCorrelationCut = fPileUpLevel;
if (!fEventCuts.AcceptEvent(fAOD)) return;
}
TClonesArray *stack =0;
if(fIsMC) {
TList *lst = fAOD->GetList();
stack = (TClonesArray*)lst->FindObject(AliAODMCParticle::StdBranchName());
if(!stack) return;
}
if(fIsPileUpCuts){
AliAODMCHeader *mcHeader = 0;
mcHeader = (AliAODMCHeader*)fAOD->GetList()->FindObject(AliAODMCHeader::StdBranchName());
if(!mcHeader) {
printf("AliAnalysisTaskSEHFTreeCreator::UserExec: MC header branch not found!\n");
return;
}
Bool_t isPileupInGeneratedEvent = kFALSE;
isPileupInGeneratedEvent = AliAnalysisUtils::IsPileupInGeneratedEvent(mcHeader, fGenName);
if(isPileupInGeneratedEvent) return;
}
//making a cut in pvz -8 to 8cm
const AliAODVertex *PrimaryVertex = fAOD->GetVertex(0);
if(!PrimaryVertex) return;
Float_t PVz = PrimaryVertex->GetZ();
if(fabs(PVz)>fPVzMax) return;
if(fabs(PVz)<fPVzMin) return;
//___________________________________________________________________________________ Raw Data:
if(!fIsMC){
//For charged particle
int Mult=0;
// loop over all these tracks:
for(Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
// if we failed, skip this track
if(!track) continue;
if(!fIsRunFBOnly){
if(track->GetTPCNcls()<fTPCNcls || track->GetTPCNCrossedRows()<fTPCNCrossedRows || track->Chi2perNDF() > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
}
if(track->Charge()==0) continue;//only get charged tracks
if(track->Eta() > fEtaMax || track->Eta() < fEtaMin) continue;//eta cut
if(track->Pt() < fPtmin|| track->Pt() > fPtmax) continue; //pt cut
if(!track->TestFilterBit(fBit)) continue;
Mult++;
}
//Number of events vs multiplicity
MultHist->Fill(Mult);
for( Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
// if we failed, skip this track:
if(!track) continue;
if(!fIsRunFBOnly){
if(track->GetTPCNcls()<fTPCNcls || track->GetTPCNCrossedRows()<fTPCNCrossedRows || track->Chi2perNDF() > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
}
if(track->Charge()==0) continue;//only get charged tracks
if(track->Eta() > fEtaMax || track->Eta() < fEtaMin) continue;//eta cut
if(track->Pt() < fPtmin|| track->Pt() > fPtmax) continue; //pt cut
if(!track->TestFilterBit(fBit)) continue;
MultPtHist->Fill(Mult, track->Pt());
}
}
//___________________________________________________________________________________ MONTE-CARLO:
if(fIsMC){
//______________________________________ RECONSTRUCTED part:
int MultRec=0; //Reconstructed Multiplicity
for(Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i)); // get a track (type AliAODTrack) from the event
if(!track) continue;
if(!track->TestFilterBit(fBit)) continue;
int label = TMath::Abs(track->GetLabel());
//mcTrack is the reconstructed track
AliAODMCParticle* mcTrack = dynamic_cast<AliAODMCParticle*>(stack->At(label));
if (!mcTrack) continue;
if (!mcTrack->IsPhysicalPrimary()) continue;
Float_t pTrec = mcTrack->Pt(); //reconstructed pT
Float_t etarec = mcTrack->Eta(); //reconstructed Eta
Short_t chargeMCRec = mcTrack->Charge(); //reconstructed charge
Float_t crossedrows = track->GetTPCNCrossedRows();
Float_t chi2 = track->Chi2perNDF();
Float_t ncl = track->GetTPCNcls();
if(ncl<fTPCNcls || crossedrows<fTPCNCrossedRows || chi2 > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
if(abs(chargeMCRec)<=1) continue;
if(etarec > fEtaMax || etarec < fEtaMin) continue;//eta cut
if(pTrec < fPtmin || pTrec > fPtmax) continue; //pt cut
MultRec++;
}
for( Int_t i(0); i < fAOD->GetNumberOfTracks(); i++) {
// get a track (type AliAODTrack) from the event:
AliAODTrack* track = static_cast<AliAODTrack*>(fAOD->GetTrack(i));
if(!track) continue;
if(!track->TestFilterBit(fBit)) continue;
int label = TMath::Abs(track->GetLabel());
//mcTrack is the reconstructed track
AliAODMCParticle* mcTrack = dynamic_cast<AliAODMCParticle*>(stack->At(label));
if (!mcTrack) continue;
if(!mcTrack->IsPhysicalPrimary()) continue;
Float_t pTrec = mcTrack->Pt(); //reconstructed pT
Float_t etarec = mcTrack->Eta(); //reconstructed Eta
Short_t chargeMCRec = mcTrack->Charge();
Float_t crossedrows = track->GetTPCNCrossedRows();
Float_t chi2 = track->Chi2perNDF();
Float_t ncl = track->GetTPCNcls();
if(ncl<fTPCNcls || crossedrows<fTPCNCrossedRows || chi2 > fChi2DoF) continue;// cut in TPC Ncls , crossed rows and chi2/dof
if(abs(chargeMCRec)<=1) continue;
if(etarec > fEtaMax || etarec < fEtaMin) continue; //eta cut
if(pTrec < fPtmin || pTrec > fPtmax) continue; //pt cut
MultPtHistRec->Fill(MultRec, pTrec);
}
//______________________________________ GENERATED part:
int nMCTracks;
if (!stack) nMCTracks = 0;
else nMCTracks = stack->GetEntries();
int MultGen = 0; //Generated Multiplicity
for ( Int_t i(0); i < nMCTracks; i++) {
AliAODMCParticle *p1=(AliAODMCParticle*)stack->UncheckedAt(i);
if(!p1) continue;
if(!p1->IsPhysicalPrimary()) continue;
Float_t pTMCgen = p1->Pt();
Float_t etaMCgen = p1->Eta();
Short_t chargeMCgen = p1->Charge();
if(etaMCgen > fEtaMax || etaMCgen < fEtaMin ) continue;
if(pTMCgen < fPtmin|| pTMCgen > fPtmax) continue;
if(abs(chargeMCgen)<=1) continue;
MultGen++;
}
for ( Int_t i(0); i < nMCTracks; i++) {
AliAODMCParticle *p1=(AliAODMCParticle*)stack->UncheckedAt(i);
if (!p1) continue;
if(!p1->IsPhysicalPrimary()) continue;
Float_t pTMCgen = p1->Pt();
Float_t etaMCgen = p1->Eta();
Short_t chargeMCgen = p1->Charge();
if(etaMCgen > fEtaMax || etaMCgen < fEtaMin ) continue;
if(pTMCgen < fPtmin|| pTMCgen > fPtmax) continue;
if(abs(chargeMCgen)<=1) continue;
MultPtHistGen->Fill(MultGen, pTMCgen);
}
//Generated Mult vs Reconstructed Mult
MultHistRatio->Fill(MultRec, MultGen);
}
}
//________________________________________________________________________
void AliAnalysisMultPt::Terminate(Option_t *)
{
// terminate
// called at the END of the analysis (when all events are processed)
}
|
Update AliAnalysisMultPt.cxx
|
Update AliAnalysisMultPt.cxx
|
C++
|
bsd-3-clause
|
pchrista/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,pchrista/AliPhysics,rbailhac/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,AMechler/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,nschmidtALICE/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,mpuccio/AliPhysics,AMechler/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,rihanphys/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,rihanphys/AliPhysics,adriansev/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,alisw/AliPhysics,adriansev/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,rihanphys/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics
|
fa654e6bd9069cfafc81b2935122e199b29e1678
|
io/io/src/TFPBlock.cxx
|
io/io/src/TFPBlock.cxx
|
#ifndef ROOT_TFPBlock
#include "TFPBlock.h"
#endif
#include <cstdlib>
#ifndef __APPLE__
#include <malloc.h>
#endif
ClassImp(TFPBlock)
//__________________________________________________________________
//constructor
TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for (Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += length[i];
}
fFullSize = aux;
fBuffer = new char[fFullSize];
}
//__________________________________________________________________
//destructor
TFPBlock::~TFPBlock()
{
delete[] fPos;
delete[] fLen;
delete[] fBuffer;
}
//__________________________________________________________________
Long64_t* TFPBlock::GetPos()
{
// Get pointer to the array of postions.
return fPos;
}
//__________________________________________________________________
Int_t* TFPBlock::GetLen()
{
// Get pointer to the array of lengths.
return fLen;
}
//__________________________________________________________________
Int_t TFPBlock::GetFullSize()
{
// Return size of the block.
return fFullSize;
}
//__________________________________________________________________
Int_t TFPBlock::GetNoElem()
{
// Return number of elements in the block.
return fNblock;
}
//__________________________________________________________________
Long64_t TFPBlock::GetPos(Int_t i)
{
// Get position of the element at index i.
return fPos[i];
}
//__________________________________________________________________
Int_t TFPBlock::GetLen(Int_t i)
{
// Get length of the element at index i.
return fLen[i];
}
//__________________________________________________________________
char* TFPBlock::GetBuffer()
{
// Get block buffer.
return fBuffer;
}
//__________________________________________________________________
void TFPBlock::SetBuffer(char* buf)
{
//Set block buffer.
fBuffer = buf;
}
//__________________________________________________________________
void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
// Reallocate the block's buffer based on the length
// of the elements it will contain.
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for(Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += fLen[i];
}
fFullSize = aux;
fBuffer = (char*) realloc(fBuffer, fFullSize);
}
|
#include "TFPBlock.h"
#include "TStorage.h"
#include <cstdlib>
ClassImp(TFPBlock)
//__________________________________________________________________
//constructor
TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for (Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += length[i];
}
fFullSize = aux;
fBuffer = new char[fFullSize];
}
//__________________________________________________________________
//destructor
TFPBlock::~TFPBlock()
{
delete[] fPos;
delete[] fLen;
delete[] fBuffer;
}
//__________________________________________________________________
Long64_t* TFPBlock::GetPos()
{
// Get pointer to the array of postions.
return fPos;
}
//__________________________________________________________________
Int_t* TFPBlock::GetLen()
{
// Get pointer to the array of lengths.
return fLen;
}
//__________________________________________________________________
Int_t TFPBlock::GetFullSize()
{
// Return size of the block.
return fFullSize;
}
//__________________________________________________________________
Int_t TFPBlock::GetNoElem()
{
// Return number of elements in the block.
return fNblock;
}
//__________________________________________________________________
Long64_t TFPBlock::GetPos(Int_t i)
{
// Get position of the element at index i.
return fPos[i];
}
//__________________________________________________________________
Int_t TFPBlock::GetLen(Int_t i)
{
// Get length of the element at index i.
return fLen[i];
}
//__________________________________________________________________
char* TFPBlock::GetBuffer()
{
// Get block buffer.
return fBuffer;
}
//__________________________________________________________________
void TFPBlock::SetBuffer(char* buf)
{
//Set block buffer.
fBuffer = buf;
}
//__________________________________________________________________
void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
// Reallocate the block's buffer based on the length
// of the elements it will contain.
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for(Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += fLen[i];
}
fBuffer = TStorage::ReAllocChar(fBuffer, aux, fFullSize);
fFullSize = aux;
}
|
use TStorage::ReAlloc() instead of realloc() so that there delete[] is still ok.
|
use TStorage::ReAlloc() instead of realloc() so that there delete[] is still ok.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@39283 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical
|
f991e8d399f714c737e4d58614f20f2c31cb9c11
|
PWGLF/RESONANCES/AliRsnMiniParticle.cxx
|
PWGLF/RESONANCES/AliRsnMiniParticle.cxx
|
//
// This object is used as lightweight temporary container
// of all information needed from any input object and
// useful for resonance analysis.
// Lists of such objects are stored in a buffer, in order
// to allow an event mixing.
//
#include <TDatabasePDG.h>
#include <TParticlePDG.h>
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliRsnEvent.h"
#include "AliRsnMiniEvent.h"
#include "AliRsnMiniParticle.h"
ClassImp(AliRsnMiniParticle)
//__________________________________________________________________________________________________
void AliRsnMiniParticle::Clear(Option_t *)
{
//
// Clears particle
//
fIndex = -0x80000000;
fIndexDaughters[0] = fIndexDaughters[1] = fIndexDaughters[2] = -0x80000000;
fCharge = 0;
fPDG = 0;
fMother = 0;
fMotherPDG = 0;
fDCA = 0;
fNTotSisters = 0;
fIsFromB = kFALSE;
fIsQuarkFound = kFALSE;
fCutBits = 0;
fPassesOOBPileupCut = kTRUE;
}
//__________________________________________________________________________________________________
void AliRsnMiniParticle::CopyDaughter(AliRsnDaughter *daughter)
{
//
// Sets data members from the passed object
//
// reset what could not be initialized
fDCA = 0.0; //typically used for D0 analysis
fPDG = 0;
fMother = -1;
fMotherPDG = 0;
fNTotSisters = -1;
fIsFromB = kFALSE;
fIsQuarkFound = kFALSE;
fCutBits = 0x0;
fPassesOOBPileupCut = kTRUE;
fPsim[0] = fPrec[0] = fPmother[0] = fPsim[1] = fPrec[1] = fPmother[1] = fPsim[2] = fPrec[2] = fPmother[2] = 0.0;
fIndexDaughters[0] = fIndexDaughters[1] = fIndexDaughters[2] = -0x80000000;
fMass[0] = fMass[1] = -1.0;
// charge
if (daughter->IsPos())
fCharge = '+';
else if (daughter->IsNeg())
fCharge = '-';
else{
AliAODcascade *Xiaod = (AliAODcascade *)daughter->Ref2AODcascade();
if(Xiaod){ // For ESD Cascade
int aodCharge = Xiaod->ChargeXi();
if (aodCharge > 0)
fCharge = '+';
else if (aodCharge < 0)
fCharge = '-';
else
fCharge = '0';
}
else fCharge = '0';
}
// rec info
if (daughter->GetRef()) {
fPrec[0] = daughter->GetRef()->Px();
fPrec[1] = daughter->GetRef()->Py();
fPrec[2] = daughter->GetRef()->Pz();
AliAODcascade *xi = daughter->Ref2AODcascade();
if(xi){ // special treatment for cascade AODs
fPrec[0] = xi->MomXiX();
fPrec[1] = xi->MomXiY();
fPrec[2] = xi->MomXiZ();
}
}
// MC info
if (daughter->GetRefMC()) {
fPsim[0] = daughter->GetRefMC()->Px();
fPsim[1] = daughter->GetRefMC()->Py();
fPsim[2] = daughter->GetRefMC()->Pz();
fPDG = daughter->GetPDG();
fMother = daughter->GetMother();
fMotherPDG = daughter->GetMotherPDG();
}
AliRsnEvent *event = (AliRsnEvent *) daughter->GetOwnerEvent();
if (!event) {
AliWarning("Invalid reference event: cannot copy DCA nor Nsisters.");
return;
}
if (event->IsAOD()){
// DCA to Primary Vertex for AOD
AliAODTrack *track = daughter->Ref2AODtrack();
AliAODv0 *v0 = daughter->Ref2AODv0();
AliAODcascade *xi = daughter->Ref2AODcascade();
AliAODEvent *aodEvent = (AliAODEvent*) event->GetRefAOD();
if (track && aodEvent) {
AliVVertex *vertex = (AliVVertex*) aodEvent->GetPrimaryVertex();
Double_t b[2], cov[3];
if (vertex) {
if ( !((track->GetStatus() & AliESDtrack::kTPCin) == 0) && !((track->GetStatus() & AliESDtrack::kTPCrefit) == 0) && !((track->GetStatus() & AliESDtrack::kITSrefit) == 0) ){
if (track->PropagateToDCA(vertex, aodEvent->GetMagneticField(), kVeryBig, b, cov))
fDCA = b[0];
}
}
}
if (v0 && aodEvent) {
fIndexDaughters[0] = v0->GetPosID();
fIndexDaughters[1] = v0->GetNegID();
// Printf("!!!!!!!! RSN index=%d v0Pos=%d v0Neg=%d", fIndex, fIndexDaughters[0], fIndexDaughters[1]);
}
if (xi && aodEvent) {
fIndexDaughters[0] = xi->GetPosID();
fIndexDaughters[1] = xi->GetNegID();
fIndexDaughters[2] = xi->GetBachID();
// Printf("!!!!!!!! RSN index=%d xiPos=%d xiNeg=%d xiBach=%d", fIndex, fIndexDaughters[0], fIndexDaughters[1], fIndexDaughters[2]);
}
if (aodEvent) {
Double_t bfield = aodEvent->GetMagneticField();
if (xi) {
fPassesOOBPileupCut = false;
AliAODTrack* tp = (AliAODTrack *) (xi->GetDaughter(0));
AliAODTrack* tn = (AliAODTrack *) (xi->GetDaughter(1));
AliAODTrack* tb = (AliAODTrack *) (xi->GetDecayVertexXi()->GetDaughter(0));
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) || TrackPassesOOBPileupCut(tb, bfield) ) fPassesOOBPileupCut = true;
} else if (v0) {
fPassesOOBPileupCut = false;
AliAODTrack* tp = (AliAODTrack *) (v0->GetSecondaryVtx()->GetDaughter(0));
AliAODTrack* tn = (AliAODTrack *) (v0->GetSecondaryVtx()->GetDaughter(1));
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) ) fPassesOOBPileupCut = true;
}
}
// Number of Daughters from MC and Momentum of the Mother
if (event->GetRefMC()) {
TClonesArray * list = event->GetAODList();
AliAODMCParticle *part = (AliAODMCParticle *)list->At(fMother);
if (part) {
fNTotSisters = part->GetNDaughters();
fPmother[0] = part->Px();
fPmother[1] = part->Py();
fPmother[2] = part->Pz();
Int_t istep = 0;
Int_t pdgGranma = 0;
Int_t abspdgGranma =0;
Int_t mother_temp = daughter->GetMother();
while (mother_temp >=0 ){
istep++;
AliDebug(2,Form("mother at step %d = %d", istep, mother_temp));
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(list->At(mother_temp));
if (mcGranma){
pdgGranma = mcGranma->GetPdgCode();
AliDebug(2,Form("Pdg mother at step %d = %d", istep, pdgGranma));
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)){
fIsFromB=kTRUE;
}
if(abspdgGranma==4 || abspdgGranma==5) fIsQuarkFound=kTRUE;
mother_temp = mcGranma->GetMother();
}else{
AliError("Failed casting the mother particle!");
break;
}
}
}
}
} else {
if (event->IsESD()){
//DCA to Primary Vertex for ESD
AliESDtrack *track = daughter->Ref2ESDtrack();
AliESDv0 *v0 = daughter->Ref2ESDv0();
AliESDcascade *xi = daughter->Ref2ESDcascade();
AliESDEvent *esdEvent = (AliESDEvent*) event->GetRefESD();
if (track && esdEvent) {
AliVVertex *vertex = (AliVVertex*) esdEvent->GetPrimaryVertex();
Double_t b[2], cov[3];
if (vertex) {
if ( !((track->GetStatus() & AliESDtrack::kTPCin) == 0) && !((track->GetStatus() & AliESDtrack::kTPCrefit) == 0) && !((track->GetStatus() & AliESDtrack::kITSrefit) == 0) ){
if (track->PropagateToDCA(vertex, esdEvent->GetMagneticField(), kVeryBig, b, cov))
fDCA = b[0];
}
}
}
if (v0 && esdEvent) {
fIndexDaughters[0] = v0->GetPindex();
fIndexDaughters[1] = v0->GetNindex();
}
if (xi && esdEvent) {
fIndexDaughters[0] = xi->GetPindex();
fIndexDaughters[1] = xi->GetNindex();
fIndexDaughters[2] = xi->GetBindex();
}
if (esdEvent) {
Double_t bfield = esdEvent->GetMagneticField();
if (xi) {
fPassesOOBPileupCut = false;
AliESDtrack* tp = esdEvent->GetTrack(xi->GetPindex());
AliESDtrack* tn = esdEvent->GetTrack(xi->GetNindex());
AliESDtrack* tb = esdEvent->GetTrack(xi->GetBindex());
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) || TrackPassesOOBPileupCut(tb, bfield) ) fPassesOOBPileupCut = true;
} else if (v0) {
fPassesOOBPileupCut = false;
AliESDtrack* tp = esdEvent->GetTrack(v0->GetPindex());
AliESDtrack* tn = esdEvent->GetTrack(v0->GetNindex());
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) ) fPassesOOBPileupCut = true;
}
}
// Number of Daughters from MC and Momentum of the Mother
if (event->GetRefMC()) {
AliMCParticle *part = (AliMCParticle *)event->GetRefMC()->GetTrack(fMother);
AliMCEvent * MCEvent = event->GetRefMCESD();
if(part){
fNTotSisters = part->Particle()->GetNDaughters();
fPmother[0] = part->Px();
fPmother[1] = part->Py();
fPmother[2] = part->Pz();
Int_t istep = 0;
Int_t pdgGranma = 0;
Int_t abspdgGranma =0;
Int_t mother_temp = daughter->GetMother();
while (mother_temp >=0 ){
istep++;
AliDebug(2,Form("mother at step %d = %d", istep, mother_temp));
AliMCParticle* mcGranma = dynamic_cast<AliMCParticle*>(MCEvent->GetTrack(mother_temp));
if (mcGranma){
pdgGranma = mcGranma->PdgCode();
AliDebug(2,Form("Pdg mother at step %d = %d", istep, pdgGranma));
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)){
fIsFromB=kTRUE;
}
if(abspdgGranma==4 || abspdgGranma==5) fIsQuarkFound=kTRUE;
mother_temp = mcGranma->GetMother();
}else{
AliError("Failed casting the mother particle!");
break;
}
}
}
}
}
}
}
//__________________________________________________________________________________________________
Double_t AliRsnMiniParticle::Mass()
{
//
// return PDG mass of particle
//
TDatabasePDG *db = TDatabasePDG::Instance();
TParticlePDG *part = db->GetParticle(PDG());
return part->Mass();
}
//__________________________________________________________________________________________________
void AliRsnMiniParticle::Set4Vector(TLorentzVector &v, Float_t mass, Bool_t mc)
{
//
// return 4 vector of particle
//
if (mass<0.0) mass = Mass();
v.SetXYZM(Px(mc), Py(mc), Pz(mc), mass);
}
//__________________________________________________________________________________________________
Bool_t AliRsnMiniParticle::TrackPassesOOBPileupCut(AliESDtrack* t, Double_t b){
if (!t) return true;
if ((t->GetStatus() & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) return true;
if (t->GetTOFExpTDiff(b, true) + 2500 > 1e-6) return true;
return false;
}
//_________________________________________________________________________________________________
Bool_t AliRsnMiniParticle::TrackPassesOOBPileupCut(AliAODTrack* t, Double_t b){
if (!t) return true;
if ((t->GetStatus() & AliVTrack::kITSrefit) == AliVTrack::kITSrefit) return true;
if (t->GetTOFExpTDiff(b, true) + 2500 > 1e-6) return true;
return false;
}
|
//
// This object is used as lightweight temporary container
// of all information needed from any input object and
// useful for resonance analysis.
// Lists of such objects are stored in a buffer, in order
// to allow an event mixing.
//
//Modified by Prottay 23/01/2022([email protected]) to fill K0s inv mass for a given bin of K*+/-
#include <TDatabasePDG.h>
#include <TParticlePDG.h>
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliRsnEvent.h"
#include "AliRsnMiniEvent.h"
#include "AliRsnMiniParticle.h"
#include "AliRsnEvent.h"
#include "AliRsnDaughter.h"
#include "AliRsnMother.h"
#include "AliRsnDaughterDef.h"
#include "AliRsnDaughterDef.h"
ClassImp(AliRsnMiniParticle)
//__________________________________________________________________________________________________
void AliRsnMiniParticle::Clear(Option_t *)
{
//
// Clears particle
//
fIndex = -0x80000000;
fIndexDaughters[0] = fIndexDaughters[1] = fIndexDaughters[2] = -0x80000000;
fCharge = 0;
fPDG = 0;
fMother = 0;
fMotherPDG = 0;
fDCA = 0;
fNTotSisters = 0;
fIsFromB = kFALSE;
fIsQuarkFound = kFALSE;
fCutBits = 0;
fPassesOOBPileupCut = kTRUE;
K0smass=0.0;
}
//__________________________________________________________________________________________________
void AliRsnMiniParticle::CopyDaughter(AliRsnDaughter *daughter)
{
//
// Sets data members from the passed object
//
// reset what could not be initialized
fDCA = 0.0; //typically used for D0 analysis
fPDG = 0;
fMother = -1;
fMotherPDG = 0;
fNTotSisters = -1;
fIsFromB = kFALSE;
fIsQuarkFound = kFALSE;
fCutBits = 0x0;
fPassesOOBPileupCut = kTRUE;
fPsim[0] = fPrec[0] = fPmother[0] = fPsim[1] = fPrec[1] = fPmother[1] = fPsim[2] = fPrec[2] = fPmother[2] = 0.0;
fIndexDaughters[0] = fIndexDaughters[1] = fIndexDaughters[2] = -0x80000000;
fMass[0] = fMass[1] = -1.0;
//charge
if (daughter->IsPos())
fCharge = '+';
else if (daughter->IsNeg())
fCharge = '-';
else{
AliAODcascade *Xiaod = (AliAODcascade *)daughter->Ref2AODcascade();
if(Xiaod){ // For ESD Cascade
int aodCharge = Xiaod->ChargeXi();
if (aodCharge > 0)
fCharge = '+';
else if (aodCharge < 0)
fCharge = '-';
else
fCharge = '0';
}
else fCharge = '0';
}
// rec info
if (daughter->GetRef()) {
fPrec[0] = daughter->GetRef()->Px();
fPrec[1] = daughter->GetRef()->Py();
fPrec[2] = daughter->GetRef()->Pz();
AliAODcascade *xi = daughter->Ref2AODcascade();
if(xi){ // special treatment for cascade AODs
fPrec[0] = xi->MomXiX();
fPrec[1] = xi->MomXiY();
fPrec[2] = xi->MomXiZ();
}
}
// MC info
if (daughter->GetRefMC()) {
fPsim[0] = daughter->GetRefMC()->Px();
fPsim[1] = daughter->GetRefMC()->Py();
fPsim[2] = daughter->GetRefMC()->Pz();
fPDG = daughter->GetPDG();
fMother = daughter->GetMother();
fMotherPDG = daughter->GetMotherPDG();
}
AliRsnEvent *event = (AliRsnEvent *) daughter->GetOwnerEvent();
if (!event) {
AliWarning("Invalid reference event: cannot copy DCA nor Nsisters.");
return;
}
if (event->IsAOD()){
// DCA to Primary Vertex for AOD
AliAODTrack *track = daughter->Ref2AODtrack();
AliAODv0 *v0 = daughter->Ref2AODv0();
AliAODcascade *xi = daughter->Ref2AODcascade();
AliAODEvent *aodEvent = (AliAODEvent*) event->GetRefAOD();
if (track && aodEvent) {
AliVVertex *vertex = (AliVVertex*) aodEvent->GetPrimaryVertex();
Double_t b[2], cov[3];
if (vertex) {
if ( !((track->GetStatus() & AliESDtrack::kTPCin) == 0) && !((track->GetStatus() & AliESDtrack::kTPCrefit) == 0) && !((track->GetStatus() & AliESDtrack::kITSrefit) == 0) ){
if (track->PropagateToDCA(vertex, aodEvent->GetMagneticField(), kVeryBig, b, cov))
fDCA = b[0];
}
}
}
if (v0 && aodEvent) {
fIndexDaughters[0] = v0->GetPosID();
fIndexDaughters[1] = v0->GetNegID();
// Printf("!!!!!!!! RSN index=%d v0Pos=%d v0Neg=%d", fIndex, fIndexDaughters[0], fIndexDaughters[1]);
}
if (xi && aodEvent) {
fIndexDaughters[0] = xi->GetPosID();
fIndexDaughters[1] = xi->GetNegID();
fIndexDaughters[2] = xi->GetBachID();
// Printf("!!!!!!!! RSN index=%d xiPos=%d xiNeg=%d xiBach=%d", fIndex, fIndexDaughters[0], fIndexDaughters[1], fIndexDaughters[2]);
}
if (aodEvent) {
Double_t bfield = aodEvent->GetMagneticField();
if (xi) {
fPassesOOBPileupCut = false;
AliAODTrack* tp = (AliAODTrack *) (xi->GetDaughter(0));
AliAODTrack* tn = (AliAODTrack *) (xi->GetDaughter(1));
AliAODTrack* tb = (AliAODTrack *) (xi->GetDecayVertexXi()->GetDaughter(0));
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) || TrackPassesOOBPileupCut(tb, bfield) ) fPassesOOBPileupCut = true;
} else if (v0) {
fPassesOOBPileupCut = false;
AliAODTrack* tp = (AliAODTrack *) (v0->GetSecondaryVtx()->GetDaughter(0));
AliAODTrack* tn = (AliAODTrack *) (v0->GetSecondaryVtx()->GetDaughter(1));
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) ) fPassesOOBPileupCut = true;
}
}
// Number of Daughters from MC and Momentum of the Mother
if (event->GetRefMC()) {
TClonesArray * list = event->GetAODList();
AliAODMCParticle *part = (AliAODMCParticle *)list->At(fMother);
if (part) {
fNTotSisters = part->GetNDaughters();
fPmother[0] = part->Px();
fPmother[1] = part->Py();
fPmother[2] = part->Pz();
Int_t istep = 0;
Int_t pdgGranma = 0;
Int_t abspdgGranma =0;
Int_t mother_temp = daughter->GetMother();
while (mother_temp >=0 ){
istep++;
AliDebug(2,Form("mother at step %d = %d", istep, mother_temp));
AliAODMCParticle* mcGranma = dynamic_cast<AliAODMCParticle*>(list->At(mother_temp));
if (mcGranma){
pdgGranma = mcGranma->GetPdgCode();
AliDebug(2,Form("Pdg mother at step %d = %d", istep, pdgGranma));
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)){
fIsFromB=kTRUE;
}
if(abspdgGranma==4 || abspdgGranma==5) fIsQuarkFound=kTRUE;
mother_temp = mcGranma->GetMother();
}else{
AliError("Failed casting the mother particle!");
break;
}
}
}
}
} else {
if (event->IsESD()){
//DCA to Primary Vertex for ESD
AliESDtrack *track = daughter->Ref2ESDtrack();
AliESDv0 *v0 = daughter->Ref2ESDv0();
AliESDcascade *xi = daughter->Ref2ESDcascade();
AliESDEvent *esdEvent = (AliESDEvent*) event->GetRefESD();
if (track && esdEvent) {
AliVVertex *vertex = (AliVVertex*) esdEvent->GetPrimaryVertex();
Double_t b[2], cov[3];
if (vertex) {
if ( !((track->GetStatus() & AliESDtrack::kTPCin) == 0) && !((track->GetStatus() & AliESDtrack::kTPCrefit) == 0) && !((track->GetStatus() & AliESDtrack::kITSrefit) == 0) ){
if (track->PropagateToDCA(vertex, esdEvent->GetMagneticField(), kVeryBig, b, cov))
fDCA = b[0];
}
}
}
if (v0 && esdEvent) {
fIndexDaughters[0] = v0->GetPindex();
fIndexDaughters[1] = v0->GetNindex();
double ma=v0->GetEffMass();
K0smass=ma;
}
if (xi && esdEvent) {
fIndexDaughters[0] = xi->GetPindex();
fIndexDaughters[1] = xi->GetNindex();
fIndexDaughters[2] = xi->GetBindex();
}
if (esdEvent) {
Double_t bfield = esdEvent->GetMagneticField();
if (xi) {
fPassesOOBPileupCut = false;
AliESDtrack* tp = esdEvent->GetTrack(xi->GetPindex());
AliESDtrack* tn = esdEvent->GetTrack(xi->GetNindex());
AliESDtrack* tb = esdEvent->GetTrack(xi->GetBindex());
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) || TrackPassesOOBPileupCut(tb, bfield) ) fPassesOOBPileupCut = true;
} else if (v0) {
fPassesOOBPileupCut = false;
AliESDtrack* tp = esdEvent->GetTrack(v0->GetPindex());
AliESDtrack* tn = esdEvent->GetTrack(v0->GetNindex());
if ( TrackPassesOOBPileupCut(tp, bfield) || TrackPassesOOBPileupCut(tn, bfield) ) fPassesOOBPileupCut = true;
}
}
// Number of Daughters from MC and Momentum of the Mother
if (event->GetRefMC()) {
AliMCParticle *part = (AliMCParticle *)event->GetRefMC()->GetTrack(fMother);
AliMCEvent * MCEvent = event->GetRefMCESD();
if(part){
fNTotSisters = part->Particle()->GetNDaughters();
fPmother[0] = part->Px();
fPmother[1] = part->Py();
fPmother[2] = part->Pz();
Int_t istep = 0;
Int_t pdgGranma = 0;
Int_t abspdgGranma =0;
Int_t mother_temp = daughter->GetMother();
while (mother_temp >=0 ){
istep++;
AliDebug(2,Form("mother at step %d = %d", istep, mother_temp));
AliMCParticle* mcGranma = dynamic_cast<AliMCParticle*>(MCEvent->GetTrack(mother_temp));
if (mcGranma){
pdgGranma = mcGranma->PdgCode();
AliDebug(2,Form("Pdg mother at step %d = %d", istep, pdgGranma));
abspdgGranma = TMath::Abs(pdgGranma);
if ((abspdgGranma > 500 && abspdgGranma < 600) || (abspdgGranma > 5000 && abspdgGranma < 6000)){
fIsFromB=kTRUE;
}
if(abspdgGranma==4 || abspdgGranma==5) fIsQuarkFound=kTRUE;
mother_temp = mcGranma->GetMother();
}else{
AliError("Failed casting the mother particle!");
break;
}
}
}
}
}
}
}
//__________________________________________________________________________________________________
Double_t AliRsnMiniParticle::Mass()
{
//
// return PDG mass of particle
//
TDatabasePDG *db = TDatabasePDG::Instance();
TParticlePDG *part = db->GetParticle(PDG());
return part->Mass();
}
//__________________________________________________________________________________________________
Double_t AliRsnMiniParticle::K0Mass()
{
return K0smass;
}
//__________________________________________________________________________________________________
void AliRsnMiniParticle::Set4Vector(TLorentzVector &v, Float_t mass, Bool_t mc)
{
//
// return 4 vector of particle
//
if (mass<0.0) mass = Mass();
v.SetXYZM(Px(mc), Py(mc), Pz(mc), mass);
}
//__________________________________________________________________________________________________
Bool_t AliRsnMiniParticle::TrackPassesOOBPileupCut(AliESDtrack* t, Double_t b){
if (!t) return true;
if ((t->GetStatus() & AliESDtrack::kITSrefit) == AliESDtrack::kITSrefit) return true;
if (t->GetTOFExpTDiff(b, true) + 2500 > 1e-6) return true;
return false;
}
//_________________________________________________________________________________________________
Bool_t AliRsnMiniParticle::TrackPassesOOBPileupCut(AliAODTrack* t, Double_t b){
if (!t) return true;
if ((t->GetStatus() & AliVTrack::kITSrefit) == AliVTrack::kITSrefit) return true;
if (t->GetTOFExpTDiff(b, true) + 2500 > 1e-6) return true;
return false;
}
|
Update AliRsnMiniParticle.cxx
|
Update AliRsnMiniParticle.cxx
|
C++
|
bsd-3-clause
|
AMechler/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,rbailhac/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,rihanphys/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,AMechler/AliPhysics,rbailhac/AliPhysics,adriansev/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,AMechler/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,fcolamar/AliPhysics,nschmidtALICE/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,rihanphys/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics
|
e25e332abdd8e57a288233864cca6b06cbcdee7a
|
src/condor_gridmanager/transferrequest.cpp
|
src/condor_gridmanager/transferrequest.cpp
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_config.h"
#include "gridmanager.h"
#include "transferrequest.h"
TransferRequest::TransferRequest( Proxy *proxy, const StringList &src_list,
const StringList &dst_list, int notify_tid )
: m_src_urls( src_list ), m_dst_urls( dst_list )
{
m_notify_tid = notify_tid;
m_gahp = NULL;
m_status = TransferQueued;
m_proxy = AcquireProxy( proxy, (TimerHandlercpp)&TransferRequest::CheckRequest, this );
m_CheckRequest_tid = daemonCore->Register_Timer( 0,
(TimerHandlercpp)&TransferRequest::CheckRequest,
"TransferRequest::CheckRequest", (Service*)this );
if ( m_src_urls.number() != m_dst_urls.number() ) {
sprintf( m_errMsg, "Unenven number of source and destination URLs" );
m_status = TransferFailed;
return;
}
std::string buff;
char *gahp_path = param( "NORDUGRID_GAHP" );
if ( gahp_path == NULL ) {
sprintf( m_errMsg, "NORDUGRID_GAHP not defined" );
m_status = TransferFailed;
return;
}
sprintf( buff, "NORDUGRID/%s", m_proxy->subject->fqan );
m_gahp = new GahpClient( buff.c_str(), gahp_path );
m_gahp->setNotificationTimerId( m_CheckRequest_tid );
m_gahp->setMode( GahpClient::normal );
m_gahp->setTimeout( param_integer( "GRIDMANAGER_GAHP_CALL_TIMEOUT", 5 * 60 ) );
free( gahp_path );
}
TransferRequest::~TransferRequest()
{
if ( m_CheckRequest_tid != TIMER_UNSET ) {
daemonCore->Cancel_Timer( m_CheckRequest_tid );
}
if ( m_proxy ) {
ReleaseProxy( m_proxy, (TimerHandlercpp)&TransferRequest::CheckRequest, this );
}
delete m_gahp;
}
void TransferRequest::CheckRequest()
{
daemonCore->Reset_Timer( m_CheckRequest_tid, TIMER_NEVER );
if ( m_status == TransferFailed || m_status == TransferDone ) {
return;
}
if ( !m_gahp->Initialize( m_proxy ) ) {
m_errMsg = "Failed to start gahp";
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
if ( m_status == TransferQueued ) {
m_src_urls.rewind();
m_dst_urls.rewind();
const char *first_src = m_src_urls.next();
const char *first_dst = m_dst_urls.next();
int rc = m_gahp->gridftp_transfer( first_src, first_dst );
if ( rc != GAHPCLIENT_COMMAND_PENDING ) {
sprintf( m_errMsg, "Failed to start transfer request" );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
m_status = TransferActive;
} else {
int rc = m_gahp->gridftp_transfer( NULL, NULL );
if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
return;
}
if ( rc != 0 ) {
sprintf( m_errMsg, "Transfer failed: %s\n", m_gahp->getErrorString() );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
const char *next_src = m_src_urls.next();
const char *next_dst = m_dst_urls.next();
if ( !next_src || !next_dst ) {
m_status = TransferDone;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
rc = m_gahp->gridftp_transfer( next_src, next_dst );
if ( rc != GAHPCLIENT_COMMAND_PENDING ) {
sprintf( m_errMsg, "Failed to start transfer request" );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
}
}
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_config.h"
#include "gridmanager.h"
#include "transferrequest.h"
TransferRequest::TransferRequest( Proxy *proxy, const StringList &src_list,
const StringList &dst_list, int notify_tid )
: m_src_urls( src_list ), m_dst_urls( dst_list )
{
m_notify_tid = notify_tid;
m_gahp = NULL;
m_status = TransferQueued;
m_proxy = AcquireProxy( proxy, (TimerHandlercpp)&TransferRequest::CheckRequest, this );
m_CheckRequest_tid = daemonCore->Register_Timer( 0,
(TimerHandlercpp)&TransferRequest::CheckRequest,
"TransferRequest::CheckRequest", (Service*)this );
if ( m_src_urls.number() != m_dst_urls.number() ) {
sprintf( m_errMsg, "Unenven number of source and destination URLs" );
m_status = TransferFailed;
return;
}
std::string buff;
char *gahp_path = param( "NORDUGRID_GAHP" );
if ( gahp_path == NULL ) {
sprintf( m_errMsg, "NORDUGRID_GAHP not defined" );
m_status = TransferFailed;
return;
}
sprintf( buff, "NORDUGRID/%s", m_proxy->subject->fqan );
m_gahp = new GahpClient( buff.c_str(), gahp_path );
m_gahp->setNotificationTimerId( m_CheckRequest_tid );
m_gahp->setMode( GahpClient::normal );
m_gahp->setTimeout( param_integer( "GRIDMANAGER_GAHP_CALL_TIMEOUT", 5 * 60 ) );
free( gahp_path );
}
TransferRequest::~TransferRequest()
{
if ( m_CheckRequest_tid != TIMER_UNSET ) {
daemonCore->Cancel_Timer( m_CheckRequest_tid );
}
if ( m_proxy ) {
ReleaseProxy( m_proxy, (TimerHandlercpp)&TransferRequest::CheckRequest, this );
}
delete m_gahp;
}
void TransferRequest::CheckRequest()
{
daemonCore->Reset_Timer( m_CheckRequest_tid, TIMER_NEVER );
if ( m_status == TransferFailed || m_status == TransferDone ) {
return;
}
if ( !m_gahp->Initialize( m_proxy ) ) {
m_errMsg = "Failed to start gahp";
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
if ( m_status == TransferQueued ) {
m_src_urls.rewind();
m_dst_urls.rewind();
const char *first_src = m_src_urls.next();
const char *first_dst = m_dst_urls.next();
int rc = m_gahp->gridftp_transfer( first_src, first_dst );
if ( rc != GAHPCLIENT_COMMAND_PENDING ) {
sprintf( m_errMsg, "Failed to start transfer request" );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
m_status = TransferActive;
} else {
int rc = m_gahp->gridftp_transfer( NULL, NULL );
if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
return;
}
if ( rc != 0 ) {
sprintf( m_errMsg, "Transfer failed: %s", m_gahp->getErrorString() );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
const char *next_src = m_src_urls.next();
const char *next_dst = m_dst_urls.next();
if ( !next_src || !next_dst ) {
m_status = TransferDone;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
rc = m_gahp->gridftp_transfer( next_src, next_dst );
if ( rc != GAHPCLIENT_COMMAND_PENDING ) {
sprintf( m_errMsg, "Failed to start transfer request" );
m_status = TransferFailed;
daemonCore->Reset_Timer( m_notify_tid, 0 );
return;
}
}
}
|
Fix bad HoldReason on Cream file transfer error. #1689
|
Fix bad HoldReason on Cream file transfer error. #1689
If a Cream file transfer fails, the gridmanager attempts to set a
HoldReason in the job ad that contains a newline. The schedd rejects the
attempt, and the gridmanager ends up not putting the job on hold.
|
C++
|
apache-2.0
|
mambelli/osg-bosco-marco,zhangzhehust/htcondor,zhangzhehust/htcondor,htcondor/htcondor,zhangzhehust/htcondor,mambelli/osg-bosco-marco,zhangzhehust/htcondor,neurodebian/htcondor,neurodebian/htcondor,htcondor/htcondor,mambelli/osg-bosco-marco,djw8605/condor,djw8605/htcondor,djw8605/htcondor,djw8605/htcondor,htcondor/htcondor,mambelli/osg-bosco-marco,clalancette/condor-dcloud,djw8605/condor,mambelli/osg-bosco-marco,mambelli/osg-bosco-marco,djw8605/condor,djw8605/condor,zhangzhehust/htcondor,htcondor/htcondor,bbockelm/condor-network-accounting,djw8605/htcondor,djw8605/htcondor,djw8605/htcondor,bbockelm/condor-network-accounting,mambelli/osg-bosco-marco,htcondor/htcondor,clalancette/condor-dcloud,zhangzhehust/htcondor,djw8605/htcondor,neurodebian/htcondor,djw8605/htcondor,bbockelm/condor-network-accounting,bbockelm/condor-network-accounting,djw8605/htcondor,clalancette/condor-dcloud,neurodebian/htcondor,djw8605/condor,zhangzhehust/htcondor,neurodebian/htcondor,bbockelm/condor-network-accounting,htcondor/htcondor,zhangzhehust/htcondor,clalancette/condor-dcloud,neurodebian/htcondor,bbockelm/condor-network-accounting,clalancette/condor-dcloud,djw8605/condor,clalancette/condor-dcloud,htcondor/htcondor,clalancette/condor-dcloud,neurodebian/htcondor,mambelli/osg-bosco-marco,djw8605/condor,zhangzhehust/htcondor,bbockelm/condor-network-accounting,htcondor/htcondor,neurodebian/htcondor,neurodebian/htcondor,bbockelm/condor-network-accounting,djw8605/condor
|
1c17104466ffc649740d767e64a8b7dfa3efa9d0
|
excercise03/01.cpp
|
excercise03/01.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int n; /* size of the board */
int *board; /* 0 MEANS EMPTY */
/*
Coordinates of the board
1 2 3 4
1 +------- y (cell)
2 |
3 |
4 |
x (line)
x starts with 1; 0 is not used
y starts with 1; 0 MEANS EMPTY
board[0] is not used.
board[1] = 3; means queen is at line 1, cell 3.
board[1] = 0; means queen is not exist at line 1.
*/
bool is_able_to_set_se(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_able_to_set_se(x + 1, y + 1);
}
bool is_able_to_set_s(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_able_to_set_s(x + 1, y);
}
bool is_able_to_set_sw(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_able_to_set_sw(x + 1, y - 1);
}
bool is_able_to_set(const int x, const int y)
{
if(is_able_to_set_se(x, y) && is_able_to_set_s(x, y) && is_able_to_set_sw(x, y)) return true;
return false;
}
int b_set(const int x, const int y)
{
/* set y to x */
board[x - 1] = y;
return 0;
}
int b_unset(const int x)
{
/* unset x */
board[x - 1] = 0; /* 0 MEANS EMPTY */
return 0;
}
int count_n_queens(const int x, const int y)
{
/* base case */
if(y < 1) return 0; /* y reached left side */
/* recursive case */
if(is_able_to_set(x, y))
{
if(x - 1 >= 1) return count_n_queens(x, y - 1) + b_set(x, y) + count_n_queens(x - 1, ::n) + b_unset(x);
if(is_able_to_set(x - 1, ::n)) return count_n_queens(x, y - 1) + 1; /* x reached top side; Queen can be here! */
}
return count_n_queens(x, y - 1);
}
int main(void)
{
for(n = 1; n <= 15; n++)
{
board = (int *)malloc(sizeof(int) * n);
memset(board, 0, sizeof(int) * n); /* 0 MEANS EMPTY */
printf("N(%d) Result=%d\n", n, count_n_queens(n, n));
free(board);
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int n; /* size of the board */
int *board; /* 0 MEANS EMPTY */
/*
Coordinates of the board
1 2 3 4
1 +------- y (cell)
2 |
3 |
4 |
x (line)
x starts with 1; 0 is not used
y starts with 1; 0 MEANS EMPTY
board[0] is not used.
board[1] = 3; means queen is at line 1, cell 3.
board[1] = 0; means queen is not exist at line 1.
*/
bool is_setable_se(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_setable_se(x + 1, y + 1);
}
bool is_setable_s(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_setable_s(x + 1, y);
}
bool is_setable_sw(const int x, const int y)
{
/* base case */
if(x < 1 || x > n || y < 1 || y > n) return true;
if(board[x - 1] == y) return false; /* queen is exist */
/* recursive case */
return is_setable_sw(x + 1, y - 1);
}
bool is_setable(const int x, const int y)
{
if(is_setable_se(x, y) && is_setable_s(x, y) && is_setable_sw(x, y)) return true;
return false;
}
int b_set(const int x, const int y)
{
/* set y to x */
board[x - 1] = y;
return 0;
}
int b_unset(const int x)
{
/* unset x */
board[x - 1] = 0; /* 0 MEANS EMPTY */
return 0;
}
int count_n_queens(const int x, const int y)
{
/* base case */
if(y < 1) return 0; /* y reached left side */
/* recursive case */
if(is_setable(x, y))
{
if(x - 1 >= 1) return count_n_queens(x, y - 1) + b_set(x, y) + count_n_queens(x - 1, ::n) + b_unset(x);
if(is_setable(x - 1, ::n)) return count_n_queens(x, y - 1) + 1; /* x reached top side; Queen can be here! */
}
return count_n_queens(x, y - 1);
}
int main(void)
{
for(n = 1; n <= 15; n++)
{
board = (int *)malloc(sizeof(int) * n);
memset(board, 0, sizeof(int) * n); /* 0 MEANS EMPTY */
printf("N(%d) Result=%d\n", n, count_n_queens(n, n));
free(board);
}
return 0;
}
|
Rename 'is_able_to_set()' to 'is_setable()'
|
Rename 'is_able_to_set()' to 'is_setable()'
|
C++
|
mit
|
kdzlvaids/algorithm_and_practice-pknu-2016,kdzlvaids/algorithm_and_practice-pknu-2016
|
cda066bd2ebd5a3b693608f64a9f75e127d8e971
|
gate/GateServerContext.cpp
|
gate/GateServerContext.cpp
|
#include "net/TcpServer.h"
#include "GateChannelProxy.h"
#include "base/Log.h"
#include "component/IniConfigParser.h"
////////////////////////////////
#include "GateServerContext.h"
#if 1
int GateServerContext::Init(const char * pszConfigFile)
{
parser = shared_ptr<IniConfigParser>(new IniConfigParser());
parser->SetRootName("gate");
if(!pszConfigFile || !File::Exist(pszConfigFile))
{
printf("config file %s is not exist , so create it use default option .",pszConfigFile);
parser->Create("gate");
static const char * kv[][2] = {
//gate server
{"ip","127.0.0.1"},
{"port","58800"},
{"max_clients","5000"},
{"logfile","gate.log"},
{"daemon","0"},
//console
{"console:ip","127.0.0.1"},
{"console:port","58810"},
/////////////add default config above////////////////
{NULL,NULL}};
int i = 0;
ConfigValue v;
while(kv[i][0])
{
v.key = kv[i][0];
v.value = kv[i][1];
parser->CreateConfig(v);
++i;
}
parser->DumpConfig(pszConfigFile);
printf("create default config ok !");
return -1;
}
else if(parser->ReadConfigFile(pszConfigFile))
{
return -2;
}
return 0;
}
int GateServerContext::SetServer(TcpServer* pServer)
{
gateServer = pServer;
return 0;
}
#endif
|
#include "net/TcpServer.h"
#include "GateChannelProxy.h"
#include "base/Log.h"
#include "component/IniConfigParser.h"
////////////////////////////////
#include "GateServerContext.h"
#if 1
int GateServerContext::Init(const char * pszConfigFile)
{
parser = shared_ptr<IniConfigParser>(new IniConfigParser());
parser->SetRootName("gate");
if(!pszConfigFile)
{
pszConfigFile = "gate.cfg.example";
}
if(!File::Exist(pszConfigFile))
{
printf("config file %s is not exist , so create it use default option .",pszConfigFile);
parser->Create("gate");
static const char * kv[][2] = {
//gate server
{"ip","127.0.0.1"},
{"port","58800"},
{"max_clients","5000"},
{"logfile","gate.log"},
{"daemon","0"},
//console
{"console:ip","127.0.0.1"},
{"console:port","58810"},
/////////////add default config above////////////////
{NULL,NULL}};
int i = 0;
ConfigValue v;
while(kv[i][0])
{
v.key = kv[i][0];
v.value = kv[i][1];
parser->CreateConfig(v);
++i;
}
parser->DumpConfig(pszConfigFile);
printf("create default config ok !");
return -1;
}
else if(parser->ReadConfigFile(pszConfigFile))
{
return -2;
}
return 0;
}
int GateServerContext::SetServer(TcpServer* pServer)
{
gateServer = pServer;
return 0;
}
#endif
|
add ctx default arg gat.cfg
|
add ctx default arg gat.cfg
|
C++
|
mit
|
jj4jj/playground,jj4jj/playground,jj4jj/playground
|
7e19f57d6da78a6b97e3f110001628076c221ce2
|
ash/system/audio/tray_volume.cc
|
ash/system/audio/tray_volume.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/audio/tray_volume.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "base/utf_string_conversions.h"
#include "grit/ui_resources.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/slider.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"
namespace ash {
namespace internal {
namespace {
const int kVolumeImageWidth = 44;
const int kVolumeImageHeight = 44;
const int kVolumeLevel = 5;
}
namespace tray {
class VolumeButton : public views::ToggleImageButton {
public:
explicit VolumeButton(views::ButtonListener* listener)
: views::ToggleImageButton(listener),
image_index_(-1) {
image_ = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_AURA_UBER_TRAY_VOLUME_LEVELS);
Update();
}
virtual ~VolumeButton() {}
void Update() {
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
int level = static_cast<int>(delegate->GetVolumeLevel() * 100);
int image_index = level / (100 / kVolumeLevel);
if (level > 0 && image_index == 0)
++image_index;
if (level == 100)
image_index = kVolumeLevel - 1;
else if (image_index == kVolumeLevel - 1)
--image_index;
if (image_index != image_index_) {
SkIRect region = SkIRect::MakeXYWH(0, image_index * kVolumeImageHeight,
kVolumeImageWidth, kVolumeImageHeight);
SkBitmap bitmap;
image_.ToSkBitmap()->extractSubset(&bitmap, region);
SetImage(views::CustomButton::BS_NORMAL, &bitmap);
image_index_ = image_index;
}
SchedulePaint();
}
private:
// Overridden from views::View.
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
views::ToggleImageButton::OnPaint(canvas);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
if (!delegate->IsAudioMuted())
return;
SkPaint paint;
paint.setColor(SkColorSetARGB(63, 0, 0, 0));
paint.setStrokeWidth(SkIntToScalar(3));
canvas->sk_canvas()->drawLine(SkIntToScalar(width() - 10),
SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(height() - 10),
paint);
}
gfx::Image image_;
int image_index_;
DISALLOW_COPY_AND_ASSIGN(VolumeButton);
};
class VolumeView : public views::View,
public views::ButtonListener,
public views::SliderListener {
public:
VolumeView() {
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
0, 0, 5));
icon_ = new VolumeButton(this);
AddChildView(icon_);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
slider_ = new views::Slider(this, views::Slider::HORIZONTAL);
slider_->SetValue(delegate->GetVolumeLevel());
slider_->set_border(views::Border::CreateEmptyBorder(0, 0, 0, 20));
AddChildView(slider_);
}
virtual ~VolumeView() {}
void SetVolumeLevel(float percent) {
slider_->SetValue(percent);
}
private:
// Overridden from views::ButtonListener.
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) OVERRIDE {
CHECK(sender == icon_);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
delegate->SetAudioMuted(!delegate->IsAudioMuted());
}
// Overridden from views:SliderListener.
virtual void SliderValueChanged(views::Slider* sender,
float value,
float old_value,
views::SliderChangeReason reason) OVERRIDE {
if (reason == views::VALUE_CHANGED_BY_USER)
ash::Shell::GetInstance()->tray_delegate()->SetVolumeLevel(value);
icon_->Update();
}
VolumeButton* icon_;
views::Slider* slider_;
DISALLOW_COPY_AND_ASSIGN(VolumeView);
};
} // namespace tray
TrayVolume::TrayVolume() {
}
TrayVolume::~TrayVolume() {
}
views::View* TrayVolume::CreateTrayView(user::LoginStatus status) {
return NULL;
}
views::View* TrayVolume::CreateDefaultView(user::LoginStatus status) {
volume_view_.reset(new tray::VolumeView);
return volume_view_.get();
}
views::View* TrayVolume::CreateDetailedView(user::LoginStatus status) {
volume_view_.reset(new tray::VolumeView);
return volume_view_.get();
}
void TrayVolume::DestroyTrayView() {
}
void TrayVolume::DestroyDefaultView() {
volume_view_.reset();
}
void TrayVolume::DestroyDetailedView() {
volume_view_.reset();
}
void TrayVolume::OnVolumeChanged(float percent) {
if (volume_view_.get()) {
volume_view_->SetVolumeLevel(percent);
return;
}
PopupDetailedView(kTrayPopupAutoCloseDelayInSeconds, false);
}
} // namespace internal
} // namespace ash
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/audio/tray_volume.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "base/utf_string_conversions.h"
#include "grit/ui_resources.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/slider.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/view.h"
namespace ash {
namespace internal {
namespace {
const int kVolumeImageWidth = 44;
const int kVolumeImageHeight = 44;
const int kVolumeLevel = 5;
}
namespace tray {
class VolumeButton : public views::ToggleImageButton {
public:
explicit VolumeButton(views::ButtonListener* listener)
: views::ToggleImageButton(listener),
image_index_(-1) {
image_ = ui::ResourceBundle::GetSharedInstance().GetImageNamed(
IDR_AURA_UBER_TRAY_VOLUME_LEVELS);
Update();
}
virtual ~VolumeButton() {}
void Update() {
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
int level = static_cast<int>(delegate->GetVolumeLevel() * 100);
int image_index = level / (100 / kVolumeLevel);
if (level > 0 && image_index == 0)
++image_index;
if (level == 100)
image_index = kVolumeLevel - 1;
else if (image_index == kVolumeLevel - 1)
--image_index;
if (image_index != image_index_) {
SkIRect region = SkIRect::MakeXYWH(0, image_index * kVolumeImageHeight,
kVolumeImageWidth, kVolumeImageHeight);
SkBitmap bitmap;
image_.ToSkBitmap()->extractSubset(&bitmap, region);
SetImage(views::CustomButton::BS_NORMAL, &bitmap);
image_index_ = image_index;
}
SchedulePaint();
}
private:
// Overridden from views::View.
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
views::ToggleImageButton::OnPaint(canvas);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
if (!delegate->IsAudioMuted())
return;
SkPaint paint;
paint.setColor(SkColorSetARGB(63, 0, 0, 0));
paint.setStrokeWidth(SkIntToScalar(3));
canvas->sk_canvas()->drawLine(SkIntToScalar(width() - 10),
SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(height() - 10),
paint);
}
gfx::Image image_;
int image_index_;
DISALLOW_COPY_AND_ASSIGN(VolumeButton);
};
class VolumeView : public views::View,
public views::ButtonListener,
public views::SliderListener {
public:
VolumeView() {
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
0, 0, 5));
icon_ = new VolumeButton(this);
AddChildView(icon_);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
slider_ = new views::Slider(this, views::Slider::HORIZONTAL);
slider_->SetValue(delegate->GetVolumeLevel());
slider_->set_border(views::Border::CreateEmptyBorder(0, 0, 0, 20));
AddChildView(slider_);
}
virtual ~VolumeView() {}
void SetVolumeLevel(float percent) {
slider_->SetValue(percent);
// It is possible that the volume was (un)muted, but the actual volume level
// did not change. In that case, setting the value of the slider won't
// trigger a repaint. So explicitly trigger a repaint.
icon_->SchedulePaint();
}
private:
// Overridden from views::ButtonListener.
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) OVERRIDE {
CHECK(sender == icon_);
ash::SystemTrayDelegate* delegate =
ash::Shell::GetInstance()->tray_delegate();
delegate->SetAudioMuted(!delegate->IsAudioMuted());
}
// Overridden from views:SliderListener.
virtual void SliderValueChanged(views::Slider* sender,
float value,
float old_value,
views::SliderChangeReason reason) OVERRIDE {
if (reason == views::VALUE_CHANGED_BY_USER)
ash::Shell::GetInstance()->tray_delegate()->SetVolumeLevel(value);
icon_->Update();
}
VolumeButton* icon_;
views::Slider* slider_;
DISALLOW_COPY_AND_ASSIGN(VolumeView);
};
} // namespace tray
TrayVolume::TrayVolume() {
}
TrayVolume::~TrayVolume() {
}
views::View* TrayVolume::CreateTrayView(user::LoginStatus status) {
return NULL;
}
views::View* TrayVolume::CreateDefaultView(user::LoginStatus status) {
volume_view_.reset(new tray::VolumeView);
return volume_view_.get();
}
views::View* TrayVolume::CreateDetailedView(user::LoginStatus status) {
volume_view_.reset(new tray::VolumeView);
return volume_view_.get();
}
void TrayVolume::DestroyTrayView() {
}
void TrayVolume::DestroyDefaultView() {
volume_view_.reset();
}
void TrayVolume::DestroyDetailedView() {
volume_view_.reset();
}
void TrayVolume::OnVolumeChanged(float percent) {
if (volume_view_.get()) {
volume_view_->SetVolumeLevel(percent);
return;
}
PopupDetailedView(kTrayPopupAutoCloseDelayInSeconds, false);
}
} // namespace internal
} // namespace ash
|
Update the volume icon when audio is muted/unmuted.
|
ash: Update the volume icon when audio is muted/unmuted.
[email protected]
BUG=118116
TEST=none
Review URL: https://chromiumcodereview.appspot.com/9706007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@126671 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.