hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2dc0bd04a90e72289320c99f61c1bcc8e15e92a0 | 2,437 | hh | C++ | TrkBase/TrkPocaBase.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | TrkBase/TrkPocaBase.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | TrkBase/TrkPocaBase.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: TrkPocaBase.hh,v 1.11 2006/03/25 15:15:56 brownd Exp $
//
// Description:
// Base class for various Poca classes; holds infrastructure, and one
// common algorithm. Ctor and dtor protected, to prevent instantiation.
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author(s): Steve Schaffner
//------------------------------------------------------------------------
#ifndef TRKPOCABASE_HH
#define TRKPOCABASE_HH
#include "TrkBase/TrkErrCode.hh"
class Trajectory;
class HepPoint;
// struct for passing around associated traj information
struct TrkPocaTraj{
TrkPocaTraj(const Trajectory& traj, double flt, bool rflt) :
_traj(traj),_flt(flt),_rflt(rflt) {}
const Trajectory& _traj;
double _flt;
bool _rflt;
};
// Class interface
class TrkPocaBase {
protected:
TrkPocaBase(double flt1, double flt2, double precision);
TrkPocaBase(double flt1, double precision);
TrkPocaBase();
TrkPocaBase(const TrkPocaBase& other);
TrkPocaBase& operator = (const TrkPocaBase& other);
public:
inline const TrkErrCode& status() const; // did the calculation succeed?
inline double flt1() const; // path length on traj 1 @ poca
inline double flt2() const;
inline double precision(); // In case anyone wants to know
virtual ~TrkPocaBase();
virtual double doca() const = 0;
virtual TrkPocaBase* clone() const = 0; // returns ownership
protected:
double _precision;
double _flt1;
double _flt2;
TrkErrCode _status;
void minimize(TrkPocaTraj& traj1, TrkPocaTraj& traj2);
void minimize(TrkPocaTraj& traj1, const HepPoint& pt);
void stepTowardPoca(TrkPocaTraj& traj1,TrkPocaTraj& traj2);
void stepToPointPoca(TrkPocaTraj& traj, const HepPoint& pt);
static void setFlt(double flt,TrkPocaTraj& traj);
static double _maxDist; // step > maxDist => parallel
static int _maxTry;
static double _extrapToler; // error allowed in picking step size
};
// Inlined functions
double
TrkPocaBase::precision() {return _precision;}
const TrkErrCode&
TrkPocaBase::status() const {return _status;}
double
TrkPocaBase::flt1() const {return _flt1;}
double
TrkPocaBase::flt2() const {return _flt2;}
#endif
| 29.719512 | 78 | 0.651621 | brownd1978 |
2dc0e3dc4aa7f7f24b3b0264c14ab5ab99c17226 | 1,644 | cpp | C++ | Source/opennwa/construct/nwa_complement.cpp | jusito/WALi-OpenNWA | 2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99 | [
"MIT"
] | 15 | 2015-03-07T17:25:57.000Z | 2022-02-04T20:17:00.000Z | src/wpds/Source/opennwa/construct/nwa_complement.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 1 | 2018-03-03T05:58:55.000Z | 2018-03-03T12:26:10.000Z | src/wpds/Source/opennwa/construct/nwa_complement.cpp | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 15 | 2015-09-25T17:44:35.000Z | 2021-07-18T18:25:38.000Z | #include "opennwa/Nwa.hpp"
#include "opennwa/construct/complement.hpp"
#include "opennwa/construct/determinize.hpp"
namespace opennwa
{
namespace construct
{
NwaRefPtr complement( Nwa const & source )
{
NwaRefPtr nwa( new Nwa());
complement(*nwa, source);
return nwa;
}
/**
*
* @brief constructs the NWA that is the complement of the given NWA
*
* @param - first: the NWA to perform the complement of
*
*/
void complement( Nwa & out, Nwa const & first )
{
//Q: How should clientInfos be generated for the complemented NWA?
//A: The clientInfos from the component machines are copied and added to the complemented NWA.
//Clear all states(except the stuck state) and transitions from this machine.
out.clear();
//Start with a deterministic copy of the given NWA.
// FIXME: keep information about whether a machine is deterministic
if(CONSTANT_CONDITION(true)) //! first.isDeterministic() )
{
determinize(out, first); //Note: determinize() will take care of clientInfo information.
}
else
{
out = first;
}
//FinalStates = AllStates - FinalStates
StateSet oldFinalStates(out.beginFinalStates(), out.endFinalStates());
out.clearFinalStates();
for( Nwa::StateIterator sit = out.beginStates(); sit != out.endStates(); sit++ )
{
if( oldFinalStates.count(*sit) == 0 )
out.addFinalState(*sit);
}
}
}
}
// Yo, Emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// End:
| 25.292308 | 100 | 0.615572 | jusito |
2dc3f099fae04d5795f454d6b575dc9745d56adf | 36 | cpp | C++ | edabit/Cpp/hello.cpp | nikku1234/Code-Practise | 94eb6680ea36efd10856c377000219285f77e5a4 | [
"Apache-2.0"
] | 9 | 2020-07-02T06:06:17.000Z | 2022-02-26T11:08:09.000Z | edabit/Cpp/hello.cpp | nikku1234/Code-Practise | 94eb6680ea36efd10856c377000219285f77e5a4 | [
"Apache-2.0"
] | 1 | 2021-11-04T17:26:36.000Z | 2021-11-04T17:26:36.000Z | edabit/Cpp/hello.cpp | nikku1234/Code-Practise | 94eb6680ea36efd10856c377000219285f77e5a4 | [
"Apache-2.0"
] | 8 | 2021-01-31T10:31:12.000Z | 2022-03-13T09:15:55.000Z | bool returnTrue() {
return true;
}
| 9 | 19 | 0.666667 | nikku1234 |
2dc465643cc9382902e1629f2794fe969d7bcb0e | 461 | cpp | C++ | Assignment/Assignment-1/2140_Herd_Sums.cpp | Hantao-Ye/CS97-SI | 410dd79cc563d47f93d8d1c96e603e4de8dfcf70 | [
"MIT"
] | null | null | null | Assignment/Assignment-1/2140_Herd_Sums.cpp | Hantao-Ye/CS97-SI | 410dd79cc563d47f93d8d1c96e603e4de8dfcf70 | [
"MIT"
] | null | null | null | Assignment/Assignment-1/2140_Herd_Sums.cpp | Hantao-Ye/CS97-SI | 410dd79cc563d47f93d8d1c96e603e4de8dfcf70 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int num = 0, output = 1;
cin >> num;
for (int i = 1; i <= (num / 2) + 1; i++)
{
int sum = 0;
for (int j = i; j <= (num / 2) + 1; j++)
{
sum += j;
if (sum == num)
{
output++;
break;
}
else if (sum > num)
break;
}
}
cout << output << endl;
} | 17.074074 | 48 | 0.32538 | Hantao-Ye |
2dc49896be9f0606c4795f3c5288a2aebe6b3b88 | 38,017 | hpp | C++ | src/lib/common/plot.hpp | bitslow/fcpp | abdaed70ccedb1a377e24d3b7c78b2ec203e111f | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2020-05-03T15:53:22.000Z | 2020-11-30T12:14:01.000Z | src/lib/common/plot.hpp | bitslow/fcpp | abdaed70ccedb1a377e24d3b7c78b2ec203e111f | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2021-05-17T16:46:22.000Z | 2021-12-22T15:12:22.000Z | src/lib/common/plot.hpp | bitslow/fcpp | abdaed70ccedb1a377e24d3b7c78b2ec203e111f | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2020-05-08T11:47:57.000Z | 2022-01-15T21:28:10.000Z | // Copyright © 2021 Giorgio Audrito. All Rights Reserved.
/**
* @file plot.hpp
* @brief Plot building tools.
*/
#ifndef FCPP_COMMON_PLOT_H_
#define FCPP_COMMON_PLOT_H_
#include <cstdint>
#include <ctime>
#include <limits>
#include <map>
#include <ratio>
#include <set>
#include <sstream>
#include <vector>
#include "lib/common/mutex.hpp"
#include "lib/common/serialize.hpp"
#include "lib/common/tagged_tuple.hpp"
#include "lib/option/aggregator.hpp"
/**
* @brief Namespace containing all the objects in the FCPP library.
*/
namespace fcpp {
//! @brief Namespace for filtering functions.
namespace filter {
//! @brief Filters values within `L/den` and `U/den` (included).
template <intmax_t L, intmax_t U, intmax_t den = 1>
struct within {
template <typename V>
bool operator()(V v) const {
v *= den;
if (L > std::numeric_limits<intmax_t>::min() and L > v) return false;
if (U < std::numeric_limits<intmax_t>::max() and U < v) return false;
return true;
}
};
//! @brief Filters values above `L/den` (included).
template <intmax_t L, intmax_t den = 1>
using above = within<L, std::numeric_limits<intmax_t>::max(), den>;
//! @brief Filters values below `U/den` (included).
template <intmax_t U, intmax_t den = 1>
using below = within<std::numeric_limits<intmax_t>::min(), U, den>;
//! @brief Filters values equal to `V/den`.
template <intmax_t V, intmax_t den = 1>
using equal = within<V, V, den>;
//! @brief Negate a filter.
template <typename F>
struct neg : F {
template <typename V>
bool operator()(V v) const {
return not F::operator()(v);
}
};
//! @brief Joins filters (or).
template <typename F, typename G>
struct vee : F, G {
template <typename V>
bool operator()(V v) const {
return F::operator()(v) or G::operator()(v);
}
};
//! @brief Disjoins filters (and).
template <typename F, typename G>
struct wedge : F, G {
template <typename V>
bool operator()(V v) const {
return F::operator()(v) and G::operator()(v);
}
};
}
//! @brief Namespace for plot building tools.
namespace plot {
//! @cond INTERNAL
namespace details {
//! @brief Shortens a string.
std::string shorten(std::string s);
//! @brief Shortens a title string.
std::string multi_shorten(std::string s);
}
//! @endcond
//! @brief Tag for time information.
struct time {};
//! @brief Structure representing a point in a plot.
struct point {
//! @brief Default constructor.
point() = default;
//! @brief The unit of the measured value.
std::string unit;
//! @brief The source of the measured value.
std::string source;
//! @brief The measured value.
double value;
};
//! @brief Printing a single point.
template <typename O>
O& operator<<(O& o, point const& p) {
o << "(";
if (p.unit.size()) o << p.unit << ", ";
o << p.source << ", " << p.value << ")";
return o;
}
//! @brief Structure representing a single plot.
struct plot {
//! @brief Default constructor.
plot() = default;
//! @brief Title of the plot.
std::string title;
//! @brief Label of the x axis.
std::string xname;
//! @brief Label of the y axis.
std::string yname;
//! @brief Values of x coordinates.
std::vector<double> xvals;
//! @brief Values of y coordinates with labels.
std::vector<std::pair<std::string, std::vector<double>>> yvals;
};
//! @brief Printing a single plot.
template <typename O>
O& operator<<(O& o, plot const& p) {
o << "plot.put(plot.plot(name+\"-" << details::shorten(p.xname) << details::shorten(p.yname) << (p.title.size() ? "-" : "") << details::multi_shorten(p.title) << "\", \"" << p.title << "\", \"" << p.xname << "\", \"" << p.yname << "\", new string[] {";
bool first = true;
for (auto const& y : p.yvals) {
if (first) first = false;
else o << ", ";
o << "\"" << y.first << "\"";
}
o << "}, new pair[][] {";
first = true;
for (auto const& y : p.yvals) {
if (first) first = false;
else o << ", ";
o << "{";
for (size_t i=0; i<y.second.size(); ++i) {
if (i > 0) o << ", ";
o << "(" << p.xvals[i] << ", " << y.second[i] << ")";
}
o << "}";
}
o << "}));\n";
return o;
}
//! @brief Structure representing a page of plots.
struct page {
//! @brief Default constructor.
page() = default;
//! @brief Constructor with a vector of plots.
page(std::vector<plot> p) : title(), rows(1), cols(p.size()), plots(p) {}
//! @brief Constructor with an array of plots.
template <size_t N>
page(std::array<plot, N> p) : title(), rows(1), cols(N), plots(p.begin(), p.end()) {}
//! @brief Title of the page.
std::string title;
//! @brief Number of rows.
size_t rows;
//! @brief Number of columns.
size_t cols;
//! @brief Plot list.
std::vector<plot> plots;
};
//! @brief Printing a single page.
template <typename O>
O& operator<<(O& o, page const& p) {
if (p.title.size()) o << "// " << p.title << "\n\n";
o << "plot.ROWS = " << p.rows << ";\n";
o << "plot.COLS = " << p.cols << ";\n\n";
for (plot const& q : p.plots) o << q << "\n";
return o;
}
//! @brief Structure representing a whole file of plots.
struct file {
//! @brief Constructor with a vector of pages.
file(std::string title, std::vector<page> p) : title(title), pages(p) {}
//! @brief Constructor with an array of pages.
template <size_t N>
file(std::string title, std::array<page, N> p) : title(title), pages(p.begin(), p.end()) {}
//! @brief Constructor with a vector of plots.
file(std::string title, std::vector<plot> p) : title(title) {
pages.emplace_back(p);
}
//! @brief Constructor with an array of plots.
template <size_t N>
file(std::string title, std::array<plot, N> p) : title(title) {
pages.emplace_back(p);
}
//! @brief Title of the file.
std::string title;
//! @brief Page list.
std::vector<page> pages;
};
//! @brief Printing a file.
template <typename O>
O& operator<<(O& o, file const& f) {
o << "// " << f.title << "\n";
o << "string name = \"" << f.title << "\";\n\n";
o << "import \"plot.asy\" as plot;\n";
o << "unitsize(1cm);\n\n";
for (page const& p : f.pages) o << p << "\n";
o << "shipout(\"" << f.title << "\");\n";
return o;
}
//! @brief Empty class not producing a plot.
class none {
public:
//! @brief The internal build type.
using build_type = typename std::array<point, 0>;
//! @brief Default constructor.
none() = default;
//! @brief Row processing.
template <typename R>
none& operator<<(R const&) {
return *this;
}
//! @brief Plot building for internal use.
build_type build() const {
return {};
}
};
//! @cond INTERNAL
namespace details {
//! @brief Extract any multi-type option from a single type.
template <typename T>
struct option_types {
using type = common::type_sequence<>;
};
template <template<class...> class T, typename... Ts>
struct option_types<T<Ts...>> {
using type = common::type_sequence<Ts...>;
};
//! @brief Integer holding a bit for every type in a type sequence.
template <typename T>
struct integer_delta_type;
template <size_t n>
struct integer_delta_type<std::array<int, n>> {
using type = std::conditional_t<n <= 16,
std::conditional_t<n <= 8, uint8_t, uint16_t>,
std::conditional_t<n <= 32, uint32_t, uint64_t>
>;
};
template <typename... Ts>
struct integer_delta_type<common::type_sequence<Ts...>> {
using type = typename integer_delta_type<std::array<int, sizeof...(Ts)>>::type;
};
//! @brief Tagged tuple wrapper, serialising the difference with a reference tuple.
template <typename T>
class delta_tuple : public T {
//! @brief Type for storing deltas.
using delta_type = typename integer_delta_type<typename T::tags>::type;
public:
//! @brief Default constructor.
delta_tuple() : T(), m_ref(*this) {}
//! @brief Reference constructor.
delta_tuple(delta_tuple const& t) : T(), m_ref(t) {}
//! @brief Inherit assignment operators.
using T::operator=;
//! @brief Assignment with delta tuples.
delta_tuple& operator=(delta_tuple const& t) {
T::operator=(static_cast<T const&>(t));
return *this;
}
//! @brief Serialises the content from/to a given input/output stream.
template <typename S>
S& serialize(S& s) {
delta_type d = serialize_delta(s);
serialize_impl(s, d, typename T::tags{});
return s;
}
private:
//! @brief Serialises the delta bits.
delta_type serialize_delta(common::isstream& s) {
delta_type d;
s.read(d);
return d;
}
delta_type serialize_delta(common::type_sequence<>) {
return 0;
}
template <typename S, typename... Ss>
delta_type serialize_delta(common::type_sequence<S, Ss...>) {
return (serialize_delta(common::type_sequence<Ss...>{}) << 1) + (common::get<S>(*this) == common::get<S>(m_ref));
}
delta_type serialize_delta(common::osstream& s) {
delta_type d = serialize_delta(typename T::tags{});
s.write(d);
return d;
}
//! @brief Serialises a skipped field.
template <typename S>
void serialize_skip(common::isstream const&, common::type_sequence<S>) {
common::get<S>(*this) = common::get<S>(m_ref);
}
template <typename S>
void serialize_skip(common::osstream const&, common::type_sequence<S>) {}
//! @brief Serialises given delta and tags.
template <typename S>
void serialize_impl(S&, delta_type, common::type_sequence<>) {}
template <typename S, typename S1, typename... Ss>
void serialize_impl(S& s, delta_type d, common::type_sequence<S1, Ss...>) {
if (d & 1) serialize_skip(s, common::type_sequence<S1>{});
else s & common::get<S1>(*this);
serialize_impl(s, d >> 1, common::type_sequence<Ss...>{});
}
//! @brief Reference tuple.
delta_tuple const& m_ref;
};
}
//! @endcond
/**
* @brief Plotter storing all rows for later printing.
*
* @param C Tags and types to be delta-compressed upon serialisation.
* @param M Tags and types not compressed on serialisation.
* @param F Tags and types assumed constant and stored only once.
* @param max_size The maximum size in bytes allowed for the buffer (0 for no maximum size).
*/
template <typename C, typename M = void, typename F = void, size_t max_size = 0>
class rows {
public:
//! @brief Sequence of tags and types to be delta-compressed upon serialisation.
using compressible_tuple_type = details::delta_tuple<common::tagged_tuple_t<typename details::option_types<C>::type>>;
//! @brief Sequence of tags and types not compressed on serialisation.
using mutable_tuple_type = common::tagged_tuple_t<typename details::option_types<M>::type>;
//! @brief Sequence of tags and types assumed constant and stored only once.
using fixed_tuple_type = common::tagged_tuple_t<typename details::option_types<F>::type>;
//! @brief The expected limit size of the object.
static constexpr size_t limit_size = max_size;
//! @brief Default constructor.
rows() {
m_start = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
m_rows.data().reserve(max_size);
m_length = m_row_size = 0;
}
//! @brief Row processing.
template <typename R>
rows& operator<<(R const& row) {
size_t prev_size = m_rows.size();
if (max_size == 0 or prev_size + m_row_size < max_size) {
m_fixed = row;
compressible_tuple_type tc(m_last);
mutable_tuple_type tm;
tc = row;
tm = row;
(m_rows << tc << tm);
m_last = row;
m_row_size = std::max(m_row_size, m_rows.size() - prev_size);
++m_length;
}
return *this;
}
//! @brief The number of rows stored.
size_t size() const {
return m_length;
}
//! @brief The number of bytes occupied by the structure.
size_t byte_size() const {
return sizeof(rows) + m_rows.size();
}
//! @brief Prints the object's contents.
template <typename O>
void print(O& o) {
common::isstream rows({});
std::swap(rows.data(), m_rows.data());
std::string tstr = std::string(ctime(&m_start));
tstr.pop_back();
o << "########################################################\n";
o << "# FCPP execution started at: " << tstr << " #\n";
o << "########################################################\n# ";
m_fixed.print(o, common::assignment_tuple);
o << "\n#\n";
o << "# The columns have the following meaning:\n# ";
print_headers(o, typename mutable_tuple_type::tags{});
print_headers(o, typename compressible_tuple_type::tags{});
o << "\n";
m_last = compressible_tuple_type();
for (size_t i=0; i<m_length; ++i) {
compressible_tuple_type tc(m_last);
mutable_tuple_type tm;
rows >> tc >> tm;
m_last = tc;
print_output(o, tm, typename mutable_tuple_type::tags{});
print_output(o, tc, typename compressible_tuple_type::tags{});
o << "\n";
}
std::time_t m_end = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
tstr = std::string(ctime(&m_end));
tstr.pop_back();
o << "########################################################\n";
o << "# FCPP execution finished at: " << tstr << " #\n";
o << "########################################################" << std::endl;
std::swap(rows.data(), m_rows.data());
}
private:
//! @brief Prints the storage headers.
template <typename O>
void print_headers(O&, common::type_sequence<>) const {}
template <typename O, typename U, typename... Us>
void print_headers(O& o, common::type_sequence<U,Us...>) const {
o << common::details::strip_namespaces(common::type_name<U>()) << " ";
print_headers(o, common::type_sequence<Us...>{});
}
//! @brief Prints the storage values.
template <typename O, typename T>
void print_output(O&, T const&, common::type_sequence<>) const {}
template <typename O, typename T, typename U, typename... Us>
void print_output(O& o, T const& t, common::type_sequence<U,Us...>) const {
o << common::escape(common::get<U>(t)) << " ";
print_output(o, t, common::type_sequence<Us...>{});
}
//! @brief Start time.
std::time_t m_start;
//! @brief Fixed data.
fixed_tuple_type m_fixed;
//! @brief Last row of compressible data.
compressible_tuple_type m_last;
//! @brief Serialised rows.
common::osstream m_rows;
//! @brief Number of rows stored.
size_t m_length;
//! @brief Maximum size of a row ever recorded.
size_t m_row_size;
};
template <typename C, typename M, typename F, size_t max_size>
constexpr size_t rows<C,M,F,max_size>::limit_size;
//! @brief Filters values for column S according to property F in plotter P.
template <typename S, typename F, typename P>
class filter {
public:
//! @brief The internal build type.
using build_type = typename P::build_type;
//! @brief Default constructor.
filter() = default;
//! @brief Row processing.
template <typename R>
filter& operator<<(R const& row) {
if (m_filter(common::get<S>(row)))
(m_plotter << row);
return *this;
}
//! @brief Plot building for internal use.
build_type build() const {
return m_plotter.build();
}
private:
//! @brief The plotter.
P m_plotter;
//! @brief The callable filter class.
F m_filter;
};
//! @cond INTERNAL
namespace details {
//! @brief Concatenate vector and array types.
template <typename... Ts>
struct array_cat;
//! @brief Concatenate one vector type.
template <typename T>
struct array_cat<std::vector<T>> {
using type = std::vector<T>;
};
//! @brief Concatenate one array type.
template <typename T, size_t N>
struct array_cat<std::array<T,N>> {
using type = std::array<T,N>;
};
//! @brief Concatenate two compatible vector types.
template <typename T>
struct array_cat<std::vector<T>, std::vector<T>> {
using type = std::vector<T>;
};
//! @brief Concatenate vector and array types.
template <typename T, size_t N>
struct array_cat<std::vector<T>, std::array<T,N>> {
using type = std::vector<T>;
};
//! @brief Concatenate array and vector types.
template <typename T, size_t N>
struct array_cat<std::array<T,N>, std::vector<T>> {
using type = std::vector<T>;
};
//! @brief Concatenate two compatible array types.
template <typename T, size_t N, size_t M>
struct array_cat<std::array<T,N>, std::array<T,M>> {
using type = std::array<T,N+M>;
};
//! @brief Concatenate plots and pages arrays.
template <size_t N, size_t M>
struct array_cat<std::array<plot,N>, std::array<page,M>> {
using type = std::array<page,M+1>;
};
template <size_t N, size_t M>
struct array_cat<std::array<page,N>, std::array<plot,M>> {
using type = std::array<page,N+1>;
};
//! @brief Concatenate plots and pages vectors.
template <>
struct array_cat<std::vector<plot>, std::vector<page>> {
using type = std::vector<page>;
};
template <>
struct array_cat<std::vector<page>, std::vector<plot>> {
using type = std::vector<page>;
};
//! @brief Concatenate plots arrays and pages vectors.
template <size_t N>
struct array_cat<std::array<plot,N>, std::vector<page>> {
using type = std::vector<page>;
};
template <size_t N>
struct array_cat<std::vector<page>, std::array<plot,N>> {
using type = std::vector<page>;
};
//! @brief Concatenate plots vectors and pages arrays.
template <size_t N>
struct array_cat<std::vector<plot>, std::array<page,N>> {
using type = std::array<page,N+1>;
};
template <size_t N>
struct array_cat<std::array<page,N>, std::vector<plot>> {
using type = std::array<page,N+1>;
};
//! @brief Concatenate multiple vector and array types.
template <typename T, typename U, typename... Us>
struct array_cat<T, U, Us...> {
using type = typename array_cat<T, typename array_cat<U, Us...>::type>::type;
};
//! @brief Resizes a vector.
template <typename T>
void maybe_resize(std::vector<T>& v, size_t s) {
v.resize(s);
}
//! @brief Does not resize an array.
template <typename T, size_t N>
void maybe_resize(std::array<T,N>&, size_t) {}
//! @brief Does not convert a vector.
template <typename T>
inline std::vector<T> maybe_promote(common::type_sequence<T>, std::vector<T> v) {
return v;
}
//! @brief Does not convert an array.
template <typename T, size_t N>
inline std::array<T,N> maybe_promote(common::type_sequence<T>, std::array<T,N> v) {
return v;
}
//! @brief Converts a vector of plots.
inline std::array<page,1> maybe_promote(common::type_sequence<page>, std::vector<plot> v) {
return {v};
}
//! @brief Converts an array of plots.
template <size_t N>
inline std::array<page,1> maybe_promote(common::type_sequence<page>, std::array<plot,N> v) {
return {v};
}
}
//! @endcond
//! @brief Joins a sequence of plotters.
template <typename... Ps>
class join {
public:
//! @brief The internal build type.
using build_type = typename details::array_cat<typename Ps::build_type...>::type;
//! @brief Default constructor.
join() = default;
//! @brief Row processing.
template <typename R>
join& operator<<(R const& row) {
input_impl(row, std::make_index_sequence<sizeof...(Ps)>{});
return *this;
}
//! @brief Plot building for internal use.
build_type build() const {
build_type res;
build_impl(res, std::make_index_sequence<sizeof...(Ps)>{});
return res;
}
private:
//! @brief Forwarding rows to plotters.
template <typename R, size_t... is>
void input_impl(R const& row, std::index_sequence<is...>) {
common::details::ignore((std::get<is>(m_plotters) << row)...);
}
//! @brief Stop joining plotter builds.
void build_impl(build_type&, std::index_sequence<>, size_t) const {}
//! @brief Joining plotter builds.
template <size_t i, size_t... is>
void build_impl(build_type& res, std::index_sequence<i, is...>, size_t x = 0) const {
auto ri = details::maybe_promote(common::type_sequence<typename build_type::value_type>{}, std::get<i>(m_plotters).build());
details::maybe_resize(res, x+ri.size());
for (size_t j = 0; j < ri.size(); ++j)
res[x+j] = std::move(ri[j]);
build_impl(res, std::index_sequence<is...>{}, x + ri.size());
}
//! @brief The plotters.
std::tuple<Ps...> m_plotters;
};
//! @brief Optimised Join of a single plotter.
template <typename P>
class join<P> : public P {};
//! @cond INTERNAL
namespace details {
//! @brief Formats a type description.
inline std::string& format_type(std::string& s) {
for (size_t i=0; i<s.size(); ++i) if (s[i] == '_') s[i] = ' ';
return s;
}
//! @brief Formats a type description.
inline std::string format_type(std::string&& s) {
return format_type(s);
}
//! @brief Formats a type description.
inline std::string format_type(std::string const& s) {
return format_type(std::string(s));
}
//! @brief Checks whether C has a static name method.
template<typename C>
struct has_name_method {
private:
template <typename T>
static constexpr auto check(T*) -> typename std::is_same<
decltype(T::name()),
std::string
>::type;
template <typename>
static constexpr std::false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static constexpr bool value = type::value;
};
}
//! @endcond
//! @brief Maintains a value for the column S aggregated with A.
template <typename S, typename A = aggregator::mean<double>>
class value {
public:
//! @brief The internal build type.
using build_type = std::array<point, 1>;
//! @brief Default constructor.
value() = default;
//! @brief Row processing.
template <typename R>
value& operator<<(R const& row) {
common::lock_guard<true> l(m_mutex);
m_aggregator.insert(common::get<S>(row));
return *this;
}
//! @brief Plot building for internal use.
build_type build() const {
point p;
std::string t = tag_name(common::bool_pack<details::has_name_method<S>::value>{}); // tag name
size_t pos = t.find("<");
if (pos != std::string::npos) {
p.unit = common::details::strip_namespaces(t.substr(0, pos));
p.source = common::details::strip_namespaces(t.substr(pos+1, t.size()-pos-2));
} else {
pos = t.find("__");
if (pos != std::string::npos) {
p.source = common::details::strip_namespaces(t.substr(0, pos));
p.unit = t.substr(pos+2);
} else {
p.unit = "";
p.source = common::details::strip_namespaces(t);
}
}
details::format_type(p.unit);
details::format_type(p.source);
std::string ar = A::name(); // row aggregator
std::string ad = aggregator_name(common::bool_pack<details::has_name_method<S>::value>{}); // device aggregator
p.source += " (" + ad + ar + ")";
p.value = std::get<0>(m_aggregator.template result<S>());
return {p};
}
private:
//! @brief Device aggregator name (if present).
std::string aggregator_name(common::bool_pack<true>) const {
return S::name() + "-";
}
//! @brief Device aggregator name (if absent).
std::string aggregator_name(common::bool_pack<false>) const {
return "";
}
//! @brief Tag name (if aggregator present).
std::string tag_name(common::bool_pack<true>) const {
return common::type_name<typename S::type>();
}
//! @brief Tag name (if aggregator absent).
std::string tag_name(common::bool_pack<false>) const {
return common::type_name<S>();
}
//! @brief A mutex for synchronised access to the aggregator.
common::mutex<true> m_mutex;
//! @brief The aggregator.
A m_aggregator;
};
//! @brief Tag for declaring units to be extracted.
template <template<class> class... Ts>
struct unit;
//! @cond INTERNAL
namespace details {
//! @brief Smart append of a plotter to a join.
template <typename Q, typename... Ps>
struct appender {
using type = join<Ps..., Q>;
};
//! @brief Smart append of a join to a join.
template <typename... Qs, typename... Ps>
struct appender<join<Qs...>, Ps...> {
using type = join<Ps..., Qs...>;
};
//! @brief Smart join of plotters.
template <typename... Ps>
struct joiner;
//! @brief Smart join of one plotter.
template <typename P>
struct joiner<P> {
using type = P;
};
//! @brief Smart join of two plotters (first non-join).
template <typename P, typename Q>
struct joiner<P, Q> : public appender<Q, P> {};
//! @brief Smart join of two plotter (first join).
template <typename... Ps, typename Q>
struct joiner<join<Ps...>, Q> : public appender<Q, Ps...> {};
//! @brief Smart join of multiple plotters.
template <typename P, typename Q, typename... Qs>
struct joiner<P, Q, Qs...> : public joiner<typename joiner<P, Q>::type, Qs...> {};
//! @brief Searches type T within tags and aggregators in S (general form).
template <typename T, typename S>
struct field_grep;
//! @brief Searches type T within tags and aggregators in S.
template <typename T, typename... Ss, typename... As>
struct field_grep<T, common::tagged_tuple<common::type_sequence<Ss...>, common::type_sequence<As...>>> {
using type = common::type_cat<std::conditional_t<std::is_same<Ss,T>::value or std::is_same<As,T>::value, typename As::template result_type<Ss>::tags, common::type_sequence<>>...>;
};
//! @brief Searches template T within tags in S (general form).
template <template<class> class T, typename S>
struct unit_grep {
using type = common::type_sequence<bool>;
};
//! @brief Searches template T within tags in S.
template <template<class> class T, typename... Ss, typename... As>
struct unit_grep<T, common::tagged_tuple<common::type_sequence<Ss...>, common::type_sequence<As...>>> {
using type = common::type_cat<std::conditional_t<common::is_class_template<T,Ss>, typename As::template result_type<Ss>::tags, common::type_sequence<>>...>;
};
//! @brief Maintains values for multiple columns and aggregators (general form).
template <typename S, typename A, typename... Ts>
struct values;
//! @brief Maintains values for one explicit column and one aggregator.
template <template<class...> class S, typename S1, template<class...> class A, typename A1>
struct values<S<S1>, A<A1>> {
using type = value<S1, A1>;
};
//! @brief Maintains values for multiple explicit columns and one aggregator.
template <template<class...> class S, typename S1, typename... Ss, template<class...> class A, typename A1>
struct values<S<S1, Ss...>, A<A1>> {
using type = join<value<S1, A1>, value<Ss, A1>...>;
};
//! @brief Maintains values for multiple explicit columns and no aggregators (defaults to `mean<double>`).
template <typename S, template<class...> class A>
struct values<S, A<>> : public values<S, A<aggregator::mean<double>>> {};
//! @brief Maintains values for multiple explicit columns and multiple aggregators.
template <typename S, template<class...> class A, typename A1, typename... As>
struct values<S, A<A1, As...>> : public joiner<typename values<S, A<A1>>::type, typename values<S, A<As>>::type...> {};
//! @brief Maintains values for multiple columns and aggregators, defined through a single field.
template <template<class...> class S, typename... Ss, typename A, typename T>
struct values<S<Ss...>, A, T> : public values<typename field_grep<T, common::tagged_tuple_t<common::type_sequence<Ss...>>>::type, A> {};
//! @brief Maintains values for multiple columns and aggregators, defined through a single unit.
template <template<class...> class S, typename... Ss, typename A, template<class> class T>
struct values<S<Ss...>, A, unit<T>> : public values<typename unit_grep<T, common::tagged_tuple_t<common::type_sequence<Ss...>>>::type, A> {};
//! @brief Maintains values for multiple columns and aggregators, defined through multiple units.
template <typename S, typename A, template<class> class T, template<class> class... Ts>
struct values<S, A, unit<T, Ts...>> : public joiner<typename values<S, A, unit<T>>::type, typename values<S, A, unit<Ts>>::type...> {};
//! @brief Maintains values for multiple columns and aggregators, defined through multiple fields.
template <typename S, typename A, typename T1, typename T2, typename... Ts>
struct values<S, A, T1, T2, Ts...> : public joiner<typename values<S, A, T1>::type, typename values<S, A, T2>::type, typename values<S, A, Ts>::type...> {};
}
//! @endcond
/**
* @brief Maintains values for multiple columns and aggregators.
*
* @param S The sequence of tags and aggregators for logging (intertwined).
* @param A The sequence of row aggregators (if empty, `mean<double>` is assumed).
* @param Ts Description of fields to be extracted as tags, aggregators or units (if empty, S is interpreted as fields).
*/
template <typename S, typename A, typename... Ts>
using values = typename details::values<S, A, Ts...>::type;
namespace details {
//! @brief The type to be used for a single key.
template <typename S>
struct key_type {
using type = common::tagged_tuple_t<S, double>;
static constexpr bool single = true;
};
//! @brief The type to be used for multiple keys.
template <typename... Ss>
struct key_type<common::type_sequence<Ss...>> {
using type = common::tagged_tuple_cat<common::tagged_tuple_t<Ss, double>...>;
static constexpr bool single = (sizeof...(Ss) == 1);
};
//! @brief Inspects a build type.
template <typename T>
struct inspector;
//! @brief Whether a vector build type contains a single object.
template <typename T>
struct inspector<std::vector<T>> {
using type = T;
static constexpr bool single = false;
};
//! @brief Whether an array build type contains a single object.
template <typename T, size_t N>
struct inspector<std::array<T,N>> {
using type = T;
static constexpr bool single = (N == 1);
};
//! @brief Promotes a maximal build type after split.
template <typename P, bool single>
struct promote_impl {
using type = std::vector<page>;
};
//! @brief Promotes multiple plots after split.
template <>
struct promote_impl<plot, false> {
using type = std::array<page, 1>;
};
//! @brief Promotes a single plot after split.
template <>
struct promote_impl<plot, true> {
using type = std::vector<plot>;
};
//! @brief Promotes points after split.
template <bool single>
struct promote_impl<point, single> {
using type = std::array<plot, 1>;
};
//! @brief Promotes a build type after split.
template <typename P>
using promote = typename promote_impl<typename inspector<P>::type, inspector<P>::single>::type;
}
/**
* Split rows depending on
*
* @param S A column tag, or a `type_sequence` of column tags.
* @param P The plotter to be split.
* @param B A bucket size (as `std::ratio`, only for a single key).
*/
template <typename S, typename P, typename B = std::ratio<0>>
class split {
//! @brief The build type of dependent plotters.
using parent_build_type = typename P::build_type;
static_assert(details::key_type<S>::single or not std::is_same<typename details::inspector<parent_build_type>::type, point>::value, "cannot split points with multiple keys");
static_assert(details::key_type<S>::single or std::is_same<std::ratio<0>, B>::value, "cannot use bucket size with multiple keys");
//! @brief The type used for splitting keys.
using key_type = typename details::key_type<S>::type;
public:
//! @brief The internal build type.
using build_type = details::promote<parent_build_type>;
//! @brief Default constructor.
split() = default;
//! @brief Row processing.
template <typename R>
split& operator<<(R const& row) {
static_assert(common::type_intersect<typename R::tags, typename key_type::tags>::size == key_type::tags::size, "splitting key not in plot row");
key_type k = approx_impl(row, B{});
P* p;
{
common::lock_guard<true> l(m_mutex);
p = &m_plotters[k];
}
*p << row;
return *this;
}
//! @brief Plot building for internal use.
build_type build() const {
std::map<key_type, parent_build_type> m;
for (auto const& x : m_plotters)
m.emplace(x.first, x.second.build());
build_type res;
build_impl(res, m);
return res;
}
private:
//! @brief No approximations without buckets.
template <typename R>
key_type approx_impl(R const& row, std::ratio<0>) const {
return row;
}
//! @brief Approximating the key to the closest bucket multiple.
template <typename R, intmax_t num, intmax_t den, typename = std::enable_if_t<num != 0>>
key_type approx_impl(R const& row, std::ratio<num,den>) const {
key_type k = row;
intmax_t n = std::get<0>(k) * den / num + 0.5;
std::get<0>(k) = double(n*num)/den;
return k;
}
//! @brief Single plot building.
void build_impl(std::array<plot, 1>& res, std::map<key_type, parent_build_type>& m) const {
res[0].xname = details::format_type(common::details::strip_namespaces(common::type_name<S>()));
std::set<std::string> units;
if (m.size()) for (point const& q : m.begin()->second) {
if (q.unit.size()) units.insert(q.unit);
res[0].yvals.emplace_back(q.source, std::vector<double>{});
}
for (std::string const& s : units) {
res[0].yname += (res[0].yname.size() ? "/" : "") + s;
}
if (units.empty()) res[0].yname = "y";
for (auto const& p : m) {
res[0].xvals.push_back(std::get<0>(p.first));
for (size_t i = 0; i < p.second.size(); ++i)
res[0].yvals[i].second.push_back(p.second[i].value);
}
}
//! @brief Multiple plot building.
void build_impl(std::vector<plot>& res, std::map<key_type, parent_build_type>& m) const {
for (auto& p : m) {
std::stringstream ss;
p.first.print(ss, common::assignment_tuple);
p.second[0].title = details::format_type(ss.str());
res.push_back(std::move(p.second[0]));
}
}
//! @brief Single page building.
void build_impl(std::array<page, 1>& res, std::map<key_type, parent_build_type>& m) const {
res[0].rows = m.size();
res[0].cols = m.size() ? m.begin()->second.size() : 0;
for (auto& p : m) {
std::stringstream ss;
p.first.print(ss, common::assignment_tuple);
for (auto& q : p.second) {
q.title = details::format_type(ss.str()) + (q.title.size() ? ", " : "") + q.title;
res[0].plots.push_back(std::move(q));
}
}
}
//! @brief Multiple page building.
void build_impl(std::vector<page>& res, std::map<key_type, parent_build_type>& m) const {
for (auto& p : m) {
std::stringstream ss;
p.first.print(ss, common::assignment_tuple);
for (auto& q : p.second) {
q.title = details::format_type(ss.str()) + (q.title.size() ? ", " : "") + q.title;
res.push_back(std::move(q));
}
}
}
//! @brief A mutex for synchronised access to the map.
common::mutex<true> m_mutex;
//! @brief The plotter.
std::map<key_type, P> m_plotters;
};
/**
* @brief Produces a single plot.
*
* @param S The sequence of tags and aggregators for logging (intertwined).
* @param X The tag to be used for the x axis.
* @param Y The unit to be used for the y axis.
* @param A The sequence of row aggregators (defaults to `mean<double>`).
*/
template <typename S, typename X, template<class> class Y, typename A = common::type_sequence<>>
using plotter = split<X, values<S, A, unit<Y>>>;
}
}
#endif // FCPP_COMMON_PLOT_H_
| 35.13586 | 256 | 0.596759 | bitslow |
2dc4e4cb46a5dd1873cabba2295667b28bf3060d | 833 | cpp | C++ | IGC/VectorCompiler/lib/Utils/GenX/Intrinsics.cpp | frantisekz/intel-graphics-compiler | 77af69c509916dfaefb1d7fa4549492824ecf606 | [
"Intel",
"MIT"
] | 3 | 2017-09-29T20:02:18.000Z | 2017-11-01T17:33:57.000Z | IGC/VectorCompiler/lib/Utils/GenX/Intrinsics.cpp | intel/intelgraphicscompiler | f7a20c6e6bed56933cfbb910a01da77a1d6ae6e4 | [
"Intel",
"MIT"
] | null | null | null | IGC/VectorCompiler/lib/Utils/GenX/Intrinsics.cpp | intel/intelgraphicscompiler | f7a20c6e6bed56933cfbb910a01da77a1d6ae6e4 | [
"Intel",
"MIT"
] | null | null | null | /*========================== begin_copyright_notice ============================
Copyright (C) 2022 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "vc/Utils/GenX/Intrinsics.h"
#include "vc/Utils/GenX/IntrinsicsWrapper.h"
using namespace llvm;
CallInst *vc::createAnyIntrinsic(IRBuilder<> &Builder,
ArrayRef<Value *> Operands,
unsigned IID,
ArrayRef<Type *> Types,
const Twine &Name) {
Module *M = Builder.GetInsertBlock()->getModule();
Function *Fn = vc::getAnyDeclaration(M, IID, Types);
IGC_ASSERT_MESSAGE(Fn, "not found correct intrinsic");
return Builder.CreateCall(Fn, Operands, Name);
}
| 34.708333 | 80 | 0.530612 | frantisekz |
2dc6c98bf7f3f730f0d612f9c46454bd0ea6af8d | 6,871 | hh | C++ | emu-ex-plus-alpha/imagine/src/gfx/Projector.hh | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | 1 | 2018-11-14T23:40:35.000Z | 2018-11-14T23:40:35.000Z | emu-ex-plus-alpha/imagine/src/gfx/Projector.hh | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | emu-ex-plus-alpha/imagine/src/gfx/Projector.hh | damoonvisuals/GBA4iOS | 95bfce0aca270b68484535ecaf0d3b2366739c77 | [
"MIT"
] | null | null | null | #pragma once
#include "defs.hh"
#include "viewport.hh"
#include <util/Matrix4x4.hh>
#include <util/rectangle2.h>
namespace Gfx
{
struct Projector
{
Rect2<GC> rect;
GC w = 0, h = 0,
focal = 0,
xToPixScale = 0, yToPixScale = 0, // screen -> projection space at focal z
pixToXScale = 0, pixToYScale = 0, // projection -> screen space at focal z
mmToXScale = 0, mmToYScale = 0, // MM of screen -> projection space at focal z
#ifdef CONFIG_BASE_ANDROID
smmToXScale = 0, smmToYScale = 0,
#endif
aspectRatio = 0;
Matrix4x4<GC> mat, matInv;
constexpr Projector() { }
GC wHalf() const
{
return rect.x2;
}
GC hHalf() const
{
return rect.y;
}
void updateMMSize()
{
mmToXScale = w/(GC)viewMMWidth();
mmToYScale = h/(GC)viewMMHeight();
#ifdef CONFIG_BASE_ANDROID
smmToXScale = w/(GC)viewSMMWidth();
smmToYScale = h/(GC)viewSMMHeight();
#endif
//logMsg("projector to mm %fx%f", (double)mmToXScale, (double)mmToYScale);
}
void setMatrix(Matrix4x4<GC> &mat, bool isSideways)
{
var_selfs(mat);
mat.invert(matInv);
GC x = 0,y = 0,z = .5;
unProject(x,y,z);
//logMsg("Lower-left projection point %f %f %f",x,y,z);
GC x2 = viewPixelWidth(),y2 = viewPixelHeight(),z2 = .5;
unProject(x2,y2,z2);
//logMsg("Upper-right projection point %f %f %f",x2,y2,z2);
w = x2 - x, h = y2 - y;
/*if(isSideways)
IG::swap(w, h);*/
rect.x = -w/2.;
rect.y = h/2.;
rect.x2 = w/2.;
rect.y2 = -h/2.;
pixToXScale = w / (GC)viewPixelWidth();
pixToYScale = h / (GC)viewPixelHeight();
xToPixScale = (GC)viewPixelWidth() / w;
yToPixScale = (GC)viewPixelHeight() / h;
logMsg("projector size %fx%f, to pix %fx%f, to view %fx%f",
(double)w, (double)h, (double)xToPixScale, (double)yToPixScale, (double)pixToXScale, (double)pixToYScale);
}
bool project(GC objx, GC objy, GC objz, GC &winx, GC &winy, GC &winz)
{
const Vector4d<GC> in = { { { objx, objy, objz, 1.0 } } };
Vector4d<GC> out;
mat.mult(in, out);
if (out[3] == 0.0)
{
logErr("projection failed, output %f, %f, %f, %f", (double)out.x, (double)out.y, (double)out.z, (double)out.w);
return 0;
}
//logMsg("vec x proj, %f, %f, %f, %f", out.x, out.y, out.z, out.w);
out[0] /= out[3];
out[1] /= out[3];
out[2] /= out[3];
out[0] = out[0] * 0.5 + 0.5;
out[1] = out[1] * 0.5 + 0.5;
out[2] = out[2] * 0.5 + 0.5;
//logMsg("mapped to range 0-1, %f, %f, %f, %f", out.x, out.y, out.z, out.w);
out[0] = out[0] * viewPixelWidth() + 0; // X viewport
out[1] = out[1] * viewPixelHeight() + 0; // Y viewport
//logMsg("mapped to viewport, %f, %f, %f, %f", out.x, out.y, out.z, out.w);
winx=out[0];
winy=out[1];
winz=out[2];
return 1;
}
bool project(GC &objx, GC &objy, GC &objz)
{
return project(objx, objy, objz, objx, objy, objz);
}
bool unProject(GC winx, GC winy, GC winz, GC &objx, GC &objy, GC &objz)
{
Vector4d<GC> in = { { { winx, winy, winz, 1.0 } } };
Vector4d<GC> out;
// Map x and y from window coordinates
in[0] = (in[0] - 0) / viewPixelWidth(); // X viewport
in[1] = (in[1] - 0) / viewPixelHeight(); // Y viewport
// Map to range -1 to 1
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;
matInv.mult(in, out);
if (out[3] == 0.0) return 0;
out[0] /= out[3];
out[1] /= out[3];
out[2] /= out[3];
objx = out[0];
objy = out[1];
objz = out[2];
return 1;
}
bool unProject(GC &objx, GC &objy, GC &objz)
{
return unProject(objx, objy, objz, objx, objy, objz);
}
Rect2<GC> relRect(GC newX, GC newY, GC xSize, GC ySize, _2DOrigin posOrigin, _2DOrigin screenOrigin)
{
// adjust to the requested origin on the screen
newX = C2DO.adjustX(newX, w, screenOrigin);
newY = C2DO.adjustY(newY, h, screenOrigin);
Rect2<GC> rect;
rect.setPosRel(newX, newY, xSize, ySize, posOrigin);
return rect;
}
};
extern Projector proj;
// convert screen/input-space to projection-space
static GC iXSize(int x)
{
GC r = (GC)x * proj.pixToXScale;
//logMsg("project x %d, to %f", x, r);
return r;
}
static GC iYSize(int y)
{
GC r = (GC)y * proj.pixToYScale;
//logMsg("project y %d, to %f", y, r);
return r;
}
static GC iXPos(int x)
{
return iXSize(x) - proj.wHalf();
//return x - GC(viewPixelWidth())/GC(2);
}
static GC iYPos(int y)
{
return -iYSize(y) + proj.hHalf();
//return -y + GC(viewPixelHeight())/GC(2);
}
// convert projection-space to screen/input-space
static int toIXSize(GC x)
{
int r = int(roundf(x * proj.xToPixScale));
//if(r) logMsg("unproject x %f, to %d", x, r);
return r;
}
static int toIYSize(GC y)
{
int r = int(roundf(y * proj.yToPixScale));
//if(r) logMsg("unproject y %f, to %d", y, r);
return r;
}
static int toIXPos(GC x)
{
//logMsg("unproject x %f", x);
return toIXSize(x + proj.wHalf());
//return x + GC(viewPixelWidth())/GC(2);
}
static int toIYPos(GC y)
{
//logMsg("unproject y %f", y);
return toIYSize(-(y - proj.hHalf()));
//return -(y - GC(viewPixelHeight())/GC(2));
}
// TODO: remove
static Rect2<GC> unProjectRect(int x, int y, int x2, int y2)
{
Rect2<GC> r;
r.x = Gfx::iXPos(x);
r.y = Gfx::iYPos(y2); // flip y-axis
r.x2 = Gfx::iXPos(x2);
r.y2 = Gfx::iYPos(y);
return r;
}
// TODO: remove
static Rect2<GC> unProjectRect(const Rect2<int> &src)
{
return unProjectRect(src.x, src.y, src.x2, src.y2);
}
static Rect2<int> projectRect2(const Rect2<GC> &src)
{
Rect2<int> r;
r.x = Gfx::toIXPos(src.x);
r.y = Gfx::toIYPos(src.y);
r.x2 = Gfx::toIXPos(src.x2);
r.y2 = Gfx::toIYPos(src.y2);
return r;
}
static Rect2<GC> unProjectRect2(const Rect2<int> &src)
{
Rect2<GC> r;
r.x = Gfx::iXPos(src.x);
r.y = Gfx::iYPos(src.y);
r.x2 = Gfx::iXPos(src.x2);
r.y2 = Gfx::iYPos(src.y2);
return r;
}
static GC alignXToPixel(GC x)
{
return iXPos(toIXPos(x));
}
static GC alignYToPixel(GC y)
{
return iYPos(toIYPos(y));
}
static GC xMMSize(GC mm) { return mm * proj.mmToXScale; }
static GC yMMSize(GC mm) { return mm * proj.mmToYScale; }
#ifdef CONFIG_BASE_ANDROID
static GC xSMMSize(GC mm) { return mm * proj.smmToXScale; }
static GC ySMMSize(GC mm) { return mm * proj.smmToYScale; }
#else
static GC xSMMSize(GC mm) { return xMMSize(mm); }
static GC ySMMSize(GC mm) { return yMMSize(mm); }
#endif
static Coordinate gXSize(const Rect2<int> &r) { return iXSize(r.xSize()); }
static Coordinate gYSize(const Rect2<int> &r) { return iYSize(r.ySize()); }
static Coordinate gXPos(const Rect2<int> &r, _2DOrigin o)
{
int pos = r.xPos(o);
if(o.xScaler() == 1)
pos++;
return iXPos(pos);
}
static Coordinate gYPos(const Rect2<int> &r, _2DOrigin o)
{
int pos = r.yPos(o);
if(o.invertYIfCartesian().yScaler() == 1)
pos++;
return iYPos(pos);
}
static Coordinate gXPos(const Rect2<int> &r, Coordinate scale, _2DOrigin o) { return gXPos(r, o) + (gXSize(r) * (scale)); }
static Coordinate gYPos(const Rect2<int> &r, Coordinate scale, _2DOrigin o) { return gYPos(r, o) + (gYSize(r) * (scale)); }
}
| 23.940767 | 123 | 0.622471 | damoonvisuals |
2dc6d48ed411a33bed7e1d80ea61f53424157986 | 876 | hpp | C++ | pythran/pythonic/include/types/cfun.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,647 | 2015-01-13T01:45:38.000Z | 2022-03-28T01:23:41.000Z | pythran/pythonic/include/types/cfun.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 1,116 | 2015-01-01T09:52:05.000Z | 2022-03-18T21:06:40.000Z | pythran/pythonic/include/types/cfun.hpp | davidbrochart/pythran | 24b6c8650fe99791a4091cbdc2c24686e86aa67c | [
"BSD-3-Clause"
] | 180 | 2015-02-12T02:47:28.000Z | 2022-03-14T10:28:18.000Z | #ifndef PYTHONIC_INCLUDE_TYPES_CFUN_HPP
#define PYTHONIC_INCLUDE_TYPES_CFUN_HPP
PYTHONIC_NS_BEGIN
namespace types
{
template <class T>
struct cfun;
template <class ReturnType, class... ArgsType>
struct cfun<ReturnType(ArgsType...)> {
using callable = void;
cfun(ReturnType (*fun)(ArgsType...));
ReturnType (*ptr)(ArgsType...);
ReturnType operator()(ArgsType... args) const;
};
}
PYTHONIC_NS_END
#ifdef ENABLE_PYTHON_MODULE
#include "pythonic/python/core.hpp"
PYTHONIC_NS_BEGIN
template <class R, class... Args>
struct to_python<types::cfun<R(Args...)>> {
static PyObject *convert(types::cfun<R(Args...)> const &v);
};
template <class R, class... Args>
struct from_python<types::cfun<R(Args...)>> {
static bool is_convertible(PyObject *obj);
static types::cfun<R(Args...)> convert(PyObject *obj);
};
PYTHONIC_NS_END
#endif
#endif
| 18.638298 | 61 | 0.708904 | davidbrochart |
2dc9d69e1e110f26c3e825995142eec7fcd7f432 | 4,232 | cpp | C++ | mechanics/src/core/NetVarManager.cpp | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | mechanics/src/core/NetVarManager.cpp | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | mechanics/src/core/NetVarManager.cpp | robindittmar/mechanics | ea62f750d3cd448cbd708dee972d5a5b9a1464a0 | [
"MIT"
] | null | null | null | #include "NetVarManager.h"
CNetVarManager::CNetVarManager()
{
m_bSummarizeOffsets = false;
}
CNetVarManager::~CNetVarManager()
{
CNetVar* pCurrent;
for (std::map<uint32_t, CNetVar*>::iterator it = m_mapNetVars.begin(); it != m_mapNetVars.end(); it++)
{
pCurrent = it->second;
if (pCurrent)
delete pCurrent;
}
}
void CNetVarManager::AddTable(const char* pTable)
{
#ifdef _DEBUG
g_pConsole->Write(LOGLEVEL_INFO, "Added '%s' to NetVarMgr\n", pTable);
#endif
uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5);
m_mapTablesToLoad[iHash] = true;
}
void CNetVarManager::LoadTables(ClientClass* pClass, bool bRecursive)
{
uint32_t iHash;
RecvTable* pTable;
CNetVar* pNetVar;
// Iterate over list
while(pClass)
{
// Grab current table
pTable = pClass->m_pRecvTable;
// Build hash from name & 'load' if necessary
iHash = murmurhash(pTable->m_pNetTableName, strlen(pTable->m_pNetTableName), 0xB16B00B5);
if(m_mapTablesToLoad[iHash])
{
// Init and load netvar
pNetVar = new CNetVar();
pNetVar->LoadTable(pTable, bRecursive);
// Add netvar to map
m_mapNetVars[iHash] = pNetVar;
}
// Next element
pClass = pClass->m_pNext;
}
}
CNetVar* CNetVarManager::GetNetVar(const char* pTable, const char* pNetVarName)
{
if (!pNetVarName)
{
return m_mapNetVars[murmurhash(pTable, strlen(pTable), 0xB16B00B5)];
}
return this->GetNetVar(1, pTable, pNetVarName);
}
CNetVar* CNetVarManager::GetNetVar(int iCountToResolve, const char* pTable, ...)
{
uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5);
CNetVar* pNetVar = m_mapNetVars[iHash];
const char* pCurArg;
va_list pArgList;
va_start(pArgList, pTable);
for (int i = 0; i < iCountToResolve; i++)
{
if (!pNetVar->GetIsTable())
{
break;
}
pCurArg = va_arg(pArgList, const char*);
pNetVar = pNetVar->GetChild(pCurArg);
if (!pNetVar)
return NULL;
}
va_end(pArgList);
return pNetVar;
}
int CNetVarManager::GetOffset(const char* pTable, const char* pNetVarName)
{
return this->GetOffset(1, pTable, pNetVarName);
}
int CNetVarManager::GetOffset(int iCountToResolve, const char* pTable, ...)
{
int iOffset = 0;
uint32_t iHash = murmurhash(pTable, strlen(pTable), 0xB16B00B5);
CNetVar* pNetVar = m_mapNetVars[iHash];
const char* pCurArg;
va_list pArgList;
va_start(pArgList, pTable);
for(int i = 0; i < iCountToResolve; i++)
{
if (!pNetVar->GetIsTable())
{
iOffset = -1;
break;
}
pCurArg = va_arg(pArgList, const char*);
pNetVar = pNetVar->GetChild(pCurArg);
if (!pNetVar)
{
iOffset = -1;
break;
}
if (m_bSummarizeOffsets)
iOffset += pNetVar->GetOffset();
else
iOffset = pNetVar->GetOffset();
}
va_end(pArgList);
return iOffset;
}
void CNetVarManager::DumpAll(FILE* pFile, ClientClass* pClass)
{
while(pClass)
{
DumpTable(pFile, pClass->m_pRecvTable);
pClass = pClass->m_pNext;
}
}
void CNetVarManager::DumpTable(FILE* pFile, ClientClass* pClass, const char* pTableName)
{
RecvTable* pTable;
while(pClass)
{
pTable = pClass->m_pRecvTable;
if(!strcmp(pTable->m_pNetTableName, pTableName))
{
DumpTable(pFile, pTable);
}
pClass = pClass->m_pNext;
}
}
void CNetVarManager::DumpClientClasses(FILE* pFile, ClientClass* pClass)
{
std::map<int, const char*> mapTest;
while (pClass)
{
mapTest[pClass->m_ClassID] = pClass->m_pNetworkName;
pClass = pClass->m_pNext;
}
for (std::map<int, const char*>::iterator it = mapTest.begin(); it != mapTest.end(); it++)
{
fprintf(pFile, "%s = %d,\n", it->second, it->first);
}
}
void printTabs(FILE* pFile, int iCount)
{
for(int i = 0; i < iCount; i++)
{
fputs(" ", pFile);
}
}
void CNetVarManager::DumpTable(FILE* pFile, RecvTable* pTable, int iLevel)
{
RecvProp* pProp;
fprintf(pFile, "%s\n", pTable->m_pNetTableName);
for (int i = 0; i < pTable->m_nProps; i++)
{
pProp = pTable->m_pProps + i;
if (pProp->m_RecvType == SendPropType::DPT_DataTable)
{
printTabs(pFile, iLevel + 1);
fprintf(pFile, "[%s (0x%X)] ", pProp->m_pVarName, pProp->m_Offset);
DumpTable(pFile, pProp->m_pDataTable, iLevel + 1);
}
else
{
printTabs(pFile, iLevel + 1);
fprintf(pFile, "%s (0x%X)\n", pProp->m_pVarName, pProp->m_Offset);
}
}
}
| 20.543689 | 103 | 0.681947 | robindittmar |
2dcbcce595687f861aba1ee80bb0510da3f94348 | 866 | cpp | C++ | src/io/KegType.cpp | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | 1 | 2018-10-17T06:37:17.000Z | 2018-10-17T06:37:17.000Z | src/io/KegType.cpp | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | null | null | null | src/io/KegType.cpp | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "io/KegType.h"
#include "io/Keg.h"
keg::Type::Type() :
m_sizeInBytes(0),
m_values() {
// Empty
}
keg::Type::Type(const nString& name, Environment* env) {
if (env) env->addType(name, this);
keg::getGlobalEnvironment()->addType(name, this);
}
void keg::Type::addValue(const nString& name, const Value& type) {
m_values[name] = type;
}
void keg::Type::addSuper(const Type* type, size_t offset /*= 0*/) {
for (auto kvPair : type->m_values) {
kvPair.second.offset += offset;
m_values[kvPair.first] = kvPair.second;
}
}
void keg::Type::construct(void* data) {
m_ctor(data);
}
void* keg::Type::alloc() {
return m_alloc();
}
void* keg::Type::allocArray(size_t s) {
return m_allocArray(s);
}
keg::DeallocatorFunction keg::Type::getDeallocator() const {
return m_deallocArray;
}
| 22.789474 | 67 | 0.642032 | caseymcc |
2dcdb536cc76486ed6b6a0e50b7edd0134ce6491 | 2,512 | hpp | C++ | engine/include/game_object.hpp | antonkanin/potatoengine | 9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd | [
"MIT"
] | null | null | null | engine/include/game_object.hpp | antonkanin/potatoengine | 9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd | [
"MIT"
] | null | null | null | engine/include/game_object.hpp | antonkanin/potatoengine | 9c8cfe03381ddc2b266c2320bb9c87fabf9d11dd | [
"MIT"
] | 1 | 2020-01-29T10:18:23.000Z | 2020-01-29T10:18:23.000Z | #pragma once
#include "mesh.hpp"
#include "model.hpp"
#include "ptm/vec3.hpp"
#include "transformation.hpp"
#include <BulletDynamics/Dynamics/btRigidBody.h>
#include <engine.hpp>
#include <memory>
namespace pt
{
class component;
class game_object
{
public:
explicit game_object(std::string name);
virtual ~game_object();
/** called once for each game object before the main loop */
virtual void start(){};
/** called every frame */
virtual void update(){};
/** add custom GUI */
virtual void on_gui(){};
[[nodiscard]] virtual bool is_serializable() const { return false; }
void set_transform(const transformation& transform);
[[nodiscard]] const transformation& get_transformation() const;
game_object* set_position(const ptm::vec3& position);
[[nodiscard]] ptm::vec3 get_position() const;
game_object* set_scale(const ptm::vec3& scale);
[[nodiscard]] ptm::vec3 get_scale() const;
game_object* set_rotation(const ptm::vec3& rotation_vector, float angle);
[[nodiscard]] const model& get_model() const;
void set_model(std::unique_ptr<model>&);
game_object* load_model(const std::string& path);
game_object* add_body(bool is_dynamic);
// physics
btRigidBody* body_ = nullptr;
btMotionState* motion_state_ = nullptr;
[[nodiscard]] std::string get_name() const;
void self_destroy();
engine& get_engine();
void add_component(std::unique_ptr<component> component);
private:
void set_position_forced(const ptm::vec3& position);
void set_rotation_forced(const ptm::vec3& rotation_vector, float angle);
void set_name(const std::string& name);
void destroy_forced();
friend engine;
friend engine_impl;
friend game_objects_list;
engine* engine_ = nullptr;
bool has_model_ = false;
std::unique_ptr<model> model_;
transformation transformation_ = { .position = ptm::vec3::zero(),
.rotation_vector = ptm::vec3::up(),
.rotation_angle = 0.0f,
.scale = { 1.f, 1.f, 1.f } };
std::string name_ = "NoName";
bool to_be_destroyed_ = false;
std::vector<std::unique_ptr<component>> components_;
};
template <typename T>
game_object* make_object(engine& e, std::string_view object_name)
{
return e.add_object<T>(object_name);
}
} // namespace pt | 24.627451 | 78 | 0.636943 | antonkanin |
2dcdd25b4e25abf12c26b7141086a50240ac99fc | 2,096 | cpp | C++ | Source Files/Application/Scripts/Managers/FadeManager.cpp | ZackaryCowled/C-Game-Engine | ea26370036f348058000f007fe3c9a8a792e8db4 | [
"MIT"
] | null | null | null | Source Files/Application/Scripts/Managers/FadeManager.cpp | ZackaryCowled/C-Game-Engine | ea26370036f348058000f007fe3c9a8a792e8db4 | [
"MIT"
] | null | null | null | Source Files/Application/Scripts/Managers/FadeManager.cpp | ZackaryCowled/C-Game-Engine | ea26370036f348058000f007fe3c9a8a792e8db4 | [
"MIT"
] | null | null | null | //Internal includes
#include "ApplicationHeaders.h"
//Fades in all registered GUI objects
//Function returns true when all registered GUI objects are fully faded in
const bool FadeManager::FadeInGUIObjects(const float fadeSpeed)
{
//Flag representing whether all registered GUI objects are fully faded in
bool fadeStatus = true;
//For each registered GUI object
for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex)
{
//Fade in the GUI object
if (!guiObjectContainer[guiObjectIndex]->FadeIn(fadeSpeed))
{
//Set the fade status flag to false
fadeStatus = false;
}
}
//Return the fade status
return fadeStatus;
}
//Fades out all registered GUI objects
//Function reutrns true when all registered GUI objects are fully faded out
const bool FadeManager::FadeOutGUIObjects(const float fadeSpeed)
{
//Flag representing whether all registered GUI objects are fully faded out
bool fadeStatus = true;
//For each registered GUI object
for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex)
{
//Fade out the GUI object
if (!guiObjectContainer[guiObjectIndex]->FadeOut(fadeSpeed))
{
//Set the fade status flag to false
fadeStatus = false;
}
}
//Return the fade status
return fadeStatus;
}
//Registers the specified GUI object
void FadeManager::RegisterGUIObject(GUIObject* p_guiObject)
{
//Register the specified GUI object
guiObjectContainer.push_back(p_guiObject);
}
//Unregisters the specified GUI object
void FadeManager::UnregisterGUIObject(GUIObject* p_guiObject)
{
//For each registered GUI object
for (unsigned int guiObjectIndex = 0; guiObjectIndex < guiObjectContainer.size(); ++guiObjectIndex)
{
//If the address of the registered GUI object is the same as the specified GUI object
if (guiObjectContainer[guiObjectIndex] == p_guiObject)
{
//Erase the GUI object from the GUI object container (Unregister GUI object)
guiObjectContainer.erase(guiObjectContainer.begin() + guiObjectIndex);
//Return from the function
return;
}
}
} | 29.521127 | 100 | 0.761927 | ZackaryCowled |
2dd337a073373ec7ffd812049adc1d75e543a980 | 2,426 | cpp | C++ | src/Mahi/Com/MelShare.cpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 1 | 2021-09-22T08:37:01.000Z | 2021-09-22T08:37:01.000Z | src/Mahi/Com/MelShare.cpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 1 | 2020-11-16T04:05:47.000Z | 2020-11-16T04:05:47.000Z | src/Mahi/Com/MelShare.cpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 2 | 2020-12-21T09:28:26.000Z | 2021-09-17T03:08:19.000Z | #include <Mahi/Com/MelShare.hpp>
#include <Mahi/Util/Types.hpp>
#include <Mahi/Com/Packet.hpp>
// #include <Mahi/Util.hpp>
// #include <Mahi/Com.hpp>
using namespace mahi::util;
namespace mahi {
namespace com {
//==============================================================================
// CLASS DEFINITIONS
//==============================================================================
MelShare::MelShare(const std::string& name, OpenMode mode, std::size_t max_bytes) :
shm_(name, mode, max_bytes),
mutex_(name + "_mutex", mode)
{
}
void MelShare::write(Packet& packet) {
Lock lock(mutex_);
std::size_t size = 0;
const void* data = packet.on_send(size);
uint32 size32 = static_cast<uint32>(size);
shm_.write(&size32, sizeof(uint32));
shm_.write(data, size, sizeof(uint32));
}
void MelShare::read(Packet& packet) {
Lock lock(mutex_);
uint32 size32 = get_size();
std::size_t size = static_cast<std::size_t>(size32);
if (size > 0) {
std::vector<char> data(size);
shm_.read(&data[0], size, sizeof(uint32));
packet.on_receive(&data[0], size);
}
}
void MelShare::write_data(const std::vector<double>& data) {
Lock lock(mutex_);
uint32 size = static_cast<uint32>(data.size() * sizeof(double));
shm_.write(&size, sizeof(uint32));
shm_.write(&data[0], size, sizeof(uint32));
}
std::vector<double> MelShare::read_data() {
Lock lock(mutex_);
uint32 size = get_size();
if (size > 0) {
std::vector<double> data(size / sizeof(double));
shm_.read(&data[0], size, sizeof(uint32));
return data;
}
else
return std::vector<double>();
}
void MelShare::write_message(const std::string &message) {
Lock lock(mutex_);
uint32 size = static_cast<uint32>(message.length() + 1);
shm_.write(&size, sizeof(uint32));
shm_.write(message.c_str(), size, sizeof(uint32));
}
std::string MelShare::read_message() {
Lock lock(mutex_);
uint32 size = get_size();
if (size > 0) {
std::vector<char> message(size);
shm_.read(&message[0], size, sizeof(uint32));
return std::string(&message[0]);
}
else
return std::string();
}
bool MelShare::is_mapped() const {
return shm_.is_mapped();
}
uint32 MelShare::get_size() {
uint32 size;
shm_.read(&size, sizeof(uint32));
return size;
}
} // namespace mahi
} // namespace com
| 26.086022 | 83 | 0.589448 | chip5441 |
2dd35e9c6291a88fe722124cd581c24456425036 | 1,642 | cpp | C++ | Atomic/AtObjId.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 4 | 2019-11-10T21:56:40.000Z | 2021-12-11T20:10:55.000Z | Atomic/AtObjId.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | null | null | null | Atomic/AtObjId.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 1 | 2019-11-11T08:38:59.000Z | 2019-11-11T08:38:59.000Z | #include "AtIncludes.h"
#include "AtObjId.h"
namespace At
{
ObjId ObjId::None(0, 0);
ObjId ObjId::Root(1, 0);
byte* ObjId::EncodeBin_Ptr(byte* p) const
{
memcpy(p, &m_index, 8); p += 8;
memcpy(p, &m_uniqueId, 8); p += 8;
return p;
}
void ObjId::EncodeBin(Enc& enc) const
{
Enc::Write write = enc.IncWrite(16);
memcpy(write.Ptr(), &m_index, 8);
memcpy(write.Ptr()+8, &m_uniqueId, 8);
write.Add(16);
}
bool ObjId::DecodeBin(Seq& s)
{
if (s.n < 16)
return false;
memcpy(&m_index, s.p, 8);
memcpy(&m_uniqueId, s.p+8, 8);
s.DropBytes(16);
return true;
}
bool ObjId::SkipDecodeBin(Seq& s)
{
if (s.n < 16)
return false;
s.DropBytes(16);
return true;
}
void ObjId::EncObj(Enc& s) const
{
if (*this == ObjId::None) s.Add("[None]");
else if (*this == ObjId::Root) s.Add("[Root]");
else s.Add("[").UInt(m_uniqueId).Add(".").UInt(m_index).Add("]");
}
bool ObjId::ReadStr(Seq& s)
{
m_uniqueId = 0;
m_index = 0;
if (s.StartsWithInsensitive("[None]"))
{
s.DropBytes(6);
return true;
}
if (s.StartsWithInsensitive("[Root]"))
{
m_uniqueId = 1;
s.DropBytes(6);
return true;
}
Seq reader { s };
if (reader.ReadByte() == '[')
{
uint64 u = reader.ReadNrUInt64Dec();
if (reader.ReadByte() == '.')
{
uint64 i = reader.ReadNrUInt64Dec();
if (reader.ReadByte() == ']')
{
m_uniqueId = u;
m_index = i;
s = reader;
return true;
}
}
}
return false;
}
}
| 16.42 | 94 | 0.517052 | denisbider |
2dd5f6e49c97439ac4a1deed6039f2b8b9ae39ad | 675 | hpp | C++ | src/vulkan_helper/single_time_command.hpp | LesleyLai/Vulkan-Renderer | fd03a69fbc21bfaf3177e43811d21dba634a1949 | [
"Apache-2.0"
] | 4 | 2019-04-17T17:44:23.000Z | 2020-09-14T04:24:37.000Z | src/vulkan_helper/single_time_command.hpp | LesleyLai/Vulkan-Renderer | fd03a69fbc21bfaf3177e43811d21dba634a1949 | [
"Apache-2.0"
] | 3 | 2020-06-10T00:43:44.000Z | 2020-06-10T00:59:47.000Z | src/vulkan_helper/single_time_command.hpp | LesleyLai/Vulkan-Renderer | fd03a69fbc21bfaf3177e43811d21dba634a1949 | [
"Apache-2.0"
] | null | null | null | #ifndef VULKAN_HELPER_SINGLE_TIME_COMMAND_HPP
#define VULKAN_HELPER_SINGLE_TIME_COMMAND_HPP
#include <beyond/utils/function_ref.hpp>
#include "vulkan/vulkan_core.h"
namespace vkh {
/**
* @brief Executes one-shot GPU command
* @param device The Vulkan Device to execute the command on
* @param command_pool The command to send the command
* @param queue The queue to send the command
* @param func A function that record the command
*/
auto execute_single_time_command(
VkDevice device, VkCommandPool command_pool, VkQueue queue,
beyond::function_ref<void(VkCommandBuffer)> func) -> void;
} // namespace vkh
#endif // VULKAN_HELPER_SINGLE_TIME_COMMAND_HPP
| 28.125 | 63 | 0.783704 | LesleyLai |
2ddddc59443b5f0d3f200d2921df49848f187208 | 6,693 | cpp | C++ | src/xrGame/DynamicHeightMap.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrGame/DynamicHeightMap.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrGame/DynamicHeightMap.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | // DynamicHeightMap.cpp: implementation of the CDynamicHeightMap class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "DynamicHeightMap.h"
#include "xrCDB/Intersect.hpp"
const int tasksPerFrame = 1;
const float limit_up = 100.f;
const float limit_down = 20.f;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHM_Static::CHM_Static()
{
// Initialize slots
Slot* slt = pool;
for (u32 i = 0; i < dhm_matrix; ++i)
for (u32 j = 0; j < dhm_matrix; ++j, ++slt)
data[i][j] = slt;
// Center
c_x = c_z = 0;
task.clear();
}
void CHM_Static::Update()
{
Fvector& view = Device.vCameraPosition;
int v_x = iFloor(view.x / dhm_size);
int v_z = iFloor(view.z / dhm_size);
// ***** SCROLL
if (v_x != c_x)
{
if (v_x > c_x)
{
// scroll matrix to left
++c_x;
for (int z = 0; z < dhm_matrix; ++z)
{
Slot* S = data[z][0];
if (S->bReady)
{
S->bReady = FALSE;
task.push_back(S);
}
for (int x = 1; x < dhm_matrix; ++x)
data[z][x - 1] = data[z][x];
data[z][dhm_matrix - 1] = S;
S->set(c_x - dhm_line + dhm_matrix - 1, c_z - dhm_line + z);
}
}
else
{
// scroll matrix to right
--c_x;
for (int z = 0; z < dhm_matrix; ++z)
{
Slot* S = data[z][dhm_matrix - 1];
if (S->bReady)
{
S->bReady = FALSE;
task.push_back(S);
}
for (int x = dhm_matrix - 1; x > 0; --x)
data[z][x] = data[z][x - 1];
data[z][0] = S;
S->set(c_x - dhm_line + 0, c_z - dhm_line + z);
}
}
}
if (v_z != c_z)
{
if (v_z > c_z)
{
// scroll matrix down a bit
++c_z;
for (int x = 0; x < dhm_matrix; ++x)
{
Slot* S = data[dhm_matrix - 1][x];
if (S->bReady)
{
S->bReady = FALSE;
task.push_back(S);
}
for (int z = dhm_matrix - 1; z > 0; --z)
data[z][x] = data[z - 1][x];
data[0][x] = S;
S->set(c_x - dhm_line + x, c_z - dhm_line + 0);
}
}
else
{
// scroll matrix up
--c_z;
for (int x = 0; x < dhm_matrix; ++x)
{
Slot* S = data[0][x];
if (S->bReady)
{
S->bReady = FALSE;
task.push_back(S);
}
for (int z = 0; z < dhm_matrix; ++z)
data[z - 1][x] = data[z][x];
data[dhm_matrix - 1][x] = S;
S->set(c_x - dhm_line + x, c_z - dhm_line + dhm_matrix - 1);
}
}
}
// ***** perform TASKs
for (int taskid = 0; (taskid < tasksPerFrame) && (!task.empty()); ++taskid)
{
Slot* S = task.back();
task.pop_back();
S->bReady = TRUE;
// Build BBox
Fbox bb;
bb.min.set(S->x * dhm_size, view.y - limit_down, S->z * dhm_size);
bb.max.set(bb.min.x + dhm_size, view.y + limit_up, bb.min.z + dhm_size);
bb.grow(EPS_L);
// Select polygons
XRC.BBoxMode(0); // BBOX_TRITEST
XRC.BBoxCollide(precalc_identity, g_pGameLevel->ObjectSpace.GetStaticModel(), precalc_identity, bb);
u32 triCount = XRC.GetBBoxContactCount();
if (0 == triCount)
{
S->clear();
continue;
}
// Cull polys
RAPID::tri* tris = g_pGameLevel->ObjectSpace.GetStaticTris();
Fvector vecUP;
vecUP.set(0, 1, 0);
for (u32 tid = 0; tid < triCount; ++tid)
{
RAPID::tri& T = tris[XRC.BBoxContact[tid].id];
Poly P;
Fvector N;
P.v[0].set(*T.verts[0]);
P.v[1].set(*T.verts[1]);
P.v[2].set(*T.verts[2]);
N.mknormal(P.v[0], P.v[1], P.v[2]);
if (N.dotproduct(vecUP) <= 0)
continue;
polys.push_back(P);
}
// Perform testing
for (int z = 0; z < dhm_precision; ++z)
{
for (int x = 0; x < dhm_precision; ++x)
{
float rx = (float(x) / float(dhm_precision)) * dhm_size + bb.min.x;
float rz = (float(z) / float(dhm_precision)) * dhm_size + bb.min.z;
float ry = bb.min.y - 5;
Fvector pos;
pos.set(rx, bb.max.y, rz);
Fvector dir;
dir.set(0, -1, 0);
float r_u, r_v, r_range;
for (u32 tid = 0; tid < polys.size(); ++tid)
{
if (RAPID::TestRayTri(pos, dir, polys[tid].v, r_u, r_v, r_range, TRUE))
{
if (r_range >= 0)
{
float y_test = pos.y - r_range;
if (y_test > ry)
ry = y_test;
}
}
}
S->data[z][x] = ry;
}
}
}
}
float CHM_Static::Query(float x, float z)
{
// base slot
int v_x = iFloor(x / dhm_size);
int v_z = iFloor(z / dhm_size);
int dx = v_x - c_x;
int dz = v_z - c_z;
int gx = dx - dhm_line;
clamp(gx, 0, dhm_matrix - 1);
int gz = dz - dhm_line;
clamp(gz, 0, dhm_matrix - 1);
Slot* S = data[gz][gx];
// precision
float ostX = x - v_x * dhm_size;
float ostZ = z - v_z * dhm_size;
int px = iFloor(dhm_precision * ostX / dhm_size);
clamp(px, 0, dhm_precision - 1);
int pz = iFloor(dhm_precision * ostZ / dhm_size);
clamp(pz, 0, dhm_precision - 1);
return S->data[pz][px];
}
//
void CHM_Dynamic::Update() {}
float CHM_Dynamic::Query(float x, float z) { return flt_min; }
//
float CHeightMap::Query(float x, float z)
{
if (dwFrame != Device.dwFrame)
{
dwFrame = Device.dwFrame;
hm_static.Update();
hm_dynamic.Update();
}
float q1 = hm_static.Query(x, z);
float q2 = hm_dynamic.Query(x, z);
return _max(q1, q2);
}
| 29.355263 | 108 | 0.412819 | clayne |
2dde8d70e8073f5f6f676d86915b244e62d384b3 | 13,999 | cc | C++ | example_cpp_smart_card_client_app/src/pp_module.cc | FabianHenneke/poc-smart-sign | 14d598a60e007293633df129771e4ca44b798846 | [
"Apache-2.0"
] | 2 | 2021-03-29T20:39:42.000Z | 2021-10-17T16:48:16.000Z | example_cpp_smart_card_client_app/src/pp_module.cc | ermuur/chromeos_smart_card_connector | 3e1f6744f8e731a824320a5bca7066677de9c249 | [
"Apache-2.0"
] | null | null | null | example_cpp_smart_card_client_app/src/pp_module.cc | ermuur/chromeos_smart_card_connector | 3e1f6744f8e731a824320a5bca7066677de9c249 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 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.
// This file contains implementation of the NaCl module entry point
// pp::CreateModule, which creates an instance of class inherited from the
// pp::Instance class (see
// <https://developer.chrome.com/native-client/devguide/coding/application-structure#native-client-modules-a-closer-look>
// for reference).
#include <stdint.h>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <ppapi/c/ppb_instance.h>
#include <ppapi/cpp/core.h>
#include <ppapi/cpp/instance.h>
#include <ppapi/cpp/module.h>
#include <ppapi/cpp/var.h>
#include <google_smart_card_common/logging/logging.h>
#include <google_smart_card_common/messaging/typed_message.h>
#include <google_smart_card_common/messaging/typed_message_router.h>
#include <google_smart_card_common/pp_var_utils/debug_dump.h>
#include <google_smart_card_pcsc_lite_client/global.h>
#include <google_smart_card_pcsc_lite_cpp_demo/demo.h>
#include "chrome_certificate_provider/api_bridge.h"
#include "chrome_certificate_provider/types.h"
#include "pin-dialog/pin_dialog_server.h"
namespace scc = smart_card_client;
namespace ccp = scc::chrome_certificate_provider;
namespace gsc = google_smart_card;
namespace smart_card_client {
namespace {
// This class contains the actual NaCl module implementation.
//
// The implementation presented here is a skeleton that initializes all pieces
// necessary for PC/SC-Lite client API initialization,
// chrome.certificateProvider JavaScript API integration and PIN dialog
// execution.
//
// As an example, this implementation starts a background thread running the
// Work method after the initialization happens.
//
// Please note that all blocking operations (for example, PC/SC-Lite API calls
// or PIN requests) should be never executed on the main thread. This is because
// all communication with the JavaScript side works through exchanging of
// messages between NaCl module and JavaScript side, and the incoming messages
// are passed by the NaCl framework to the HandleMessage method of this class
// always on the main thread (see
// <https://developer.chrome.com/native-client/devguide/coding/message-system>).
// Actually, most of the blocking operations implemented in this code contain
// assertions that they are not called on the main thread.
class PpInstance final : public pp::Instance {
public:
// The constructor that is executed during the NaCl module startup.
//
// The implementation presented here does the following:
// * creates a google_smart_card::TypedMessageRouter class instance that will
// be used for handling messages received from the JavaScript side (see the
// HandleMessage method);
// * creates a google_smart_card::PcscLiteClientNaclGlobal class instance that
// initializes the internal state required for PC/SC-Lite API functions
// implementation;
// * creates a PinDialogServer class instance that allows to perform PIN
// dialog requests;
// * creates a chrome_certificate_provider::ApiBridge class instance that can
// be used to handle requests received from the chrome.certificateProvider
// JavaScript API event listeners (see
// <https://developer.chrome.com/extensions/certificateProvider#events>).
explicit PpInstance(PP_Instance instance)
: pp::Instance(instance),
pcsc_lite_over_requester_global_(
new gsc::PcscLiteOverRequesterGlobal(
&typed_message_router_, this, pp::Module::Get()->core())),
pin_dialog_server_(new PinDialogServer(
&typed_message_router_, this, pp::Module::Get()->core())),
chrome_certificate_provider_api_bridge_(
&typed_message_router_,
this,
/* execute_requests_sequentially */ false),
certificates_request_handler_(new ClientCertificatesRequestHandler),
sign_digest_request_handler_(new ClientSignDigestRequestHandler(
pin_dialog_server_)) {
chrome_certificate_provider_api_bridge_.SetCertificatesRequestHandler(
certificates_request_handler_);
chrome_certificate_provider_api_bridge_.SetSignDigestRequestHandler(
sign_digest_request_handler_);
StartWorkInBackgroundThread();
}
// The destructor that is executed when the NaCl framework is about to destroy
// the NaCl module (though, actually, it's not guaranteed to be executed at
// all - the NaCl module can be just shut down by the browser).
//
// The implementation presented here essentially leaves the previously
// allocated google_smart_card::PcscLiteOverRequesterGlobal not destroyed
// (i.e. leaves it as a leaked pointer). This is done intentionally: there may
// be still PC/SC-Lite API function calls being executed, and they are using
// the common state provided by this
// google_smart_card::PcscLiteOverRequesterGlobal object. So, instead of
// deleting it (which may lead to undefined behavior), the Detach method of
// this class is called - which prevents it from using pointer to this
// instance of PpInstance class.
~PpInstance() override {
pcsc_lite_over_requester_global_->Detach();
pcsc_lite_over_requester_global_.release();
pin_dialog_server_->Detach();
}
// This method is called with each message received by the NaCl module from
// the JavaScript side.
//
// All the messages are processed through the
// google_smart_card::TypedMessageRouter class instance, which routes them to
// the objects that subscribed for receiving them. The routing is based on the
// "type" key of the message (for the description of the typed messages, see
// header common/cpp/src/google_smart_card_common/messaging/typed_message.h).
//
// In the implementation presented here, the following messages are received
// and handled here:
// * results of the submitted PC/SC-Lite API calls (see the
// google_smart_card::PcscLiteOverRequesterGlobal class);
// * results returned from PIN dialogs (see the PinDialogServer class);
// * requests received from chrome.certificateProvider API event handlers (see
// the chrome_certificate_provider::ApiBridge class).
//
// Note that this method should not perform any long operations or
// blocking operations that wait for responses received from the JavaScript
// side - because this method is called by NaCl framework on the main thread,
// and blocking it prevents the NaCl module from receiving new incoming
// messages (see
// <https://developer.chrome.com/native-client/devguide/coding/message-system>).
void HandleMessage(const pp::Var& message) override {
if (!typed_message_router_.OnMessageReceived(message)) {
GOOGLE_SMART_CARD_LOG_FATAL << "Unexpected message received: " <<
gsc::DebugDumpVar(message);
}
}
private:
// This class is the implementation of the onCertificatesRequested request
// from the chrome.certificateProvider JavaScript API (see
// <https://developer.chrome.com/extensions/certificateProvider#event-onCertificatesRequested>).
class ClientCertificatesRequestHandler final
: public ccp::CertificatesRequestHandler {
public:
// Handles the received certificates request.
//
// Returns whether the operation finished successfully. In case of success,
// the resulting certificates information should be returned through the
// result output argument.
//
// Note that this method is executed by
// chrome_certificate_provider::ApiBridge object on a separate background
// thread. Multiple requests can be executed simultaneously (they will run
// in different background threads).
bool HandleRequest(std::vector<ccp::CertificateInfo>* result) override {
//
// CHANGE HERE:
// Place your custom code here:
//
ccp::CertificateInfo certificate_info_1;
certificate_info_1.certificate.assign({1, 2, 3});
certificate_info_1.supported_hashes.push_back(ccp::Hash::kMd5Sha1);
ccp::CertificateInfo certificate_info_2;
certificate_info_2.supported_hashes.push_back(ccp::Hash::kSha512);
result->push_back(certificate_info_1);
result->push_back(certificate_info_2);
return true;
}
};
// This class is the implementation of the onSignDigestRequested request
// from the chrome.certificateProvider JavaScript API (see
// <https://developer.chrome.com/extensions/certificateProvider#event-onSignDigestRequested>).
class ClientSignDigestRequestHandler final
: public ccp::SignDigestRequestHandler {
public:
explicit ClientSignDigestRequestHandler(
std::weak_ptr<PinDialogServer> pin_dialog_server)
: pin_dialog_server_(pin_dialog_server) {}
// Handles the received sign digest request (the request data is passed
// through the sign_request argument).
//
// Returns whether the operation finished successfully. In case of success,
// the resulting signature should be returned through the result output
// argument.
//
// Note that this method is executed by
// chrome_certificate_provider::ApiBridge object on a separate background
// thread. Multiple requests can be executed simultaneously (they will run
// in different background threads).
bool HandleRequest(
const ccp::SignRequest& sign_request,
std::vector<uint8_t>* result) override {
//
// CHANGE HERE:
// Place your custom code here:
//
*result = sign_request.digest;
const std::shared_ptr<PinDialogServer> locked_pin_dialog_server =
pin_dialog_server_.lock();
if (!locked_pin_dialog_server) {
GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] Skipped PIN dialog " <<
"demo: the shutdown process has started";
return false;
}
GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] Running PIN dialog " <<
"demo...";
std::string pin;
if (locked_pin_dialog_server->RequestPin(&pin)) {
GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] demo finished: " <<
"received PIN enter by the user.";
} else {
GOOGLE_SMART_CARD_LOG_INFO << "[PIN Dialog DEMO] demo finished: " <<
"dialog was canceled.";
}
return true;
}
private:
const std::weak_ptr<PinDialogServer> pin_dialog_server_;
};
// This method is called by the constructor once all of the initialization
// steps finish.
void StartWorkInBackgroundThread() {
std::thread(&PpInstance::Work).detach();
}
// This method is executed on a background thread after all of the
// initialization steps finish.
static void Work() {
//
// CHANGE HERE:
// Place your custom code here:
//
GOOGLE_SMART_CARD_LOG_INFO << "[PC/SC-Lite DEMO] Starting PC/SC-Lite " <<
"demo...";
if (gsc::ExecutePcscLiteCppDemo()) {
GOOGLE_SMART_CARD_LOG_INFO << "[PC/SC-Lite DEMO] demo finished " <<
"successfully.";
} else {
GOOGLE_SMART_CARD_LOG_ERROR << "[PC/SC-Lite DEMO] demo failed.";
}
}
// Router of the incoming typed messages that passes incoming messages to the
// appropriate handlers according the the special type field of the message
// (see common/cpp/src/google_smart_card_common/messaging/typed_message.h).
gsc::TypedMessageRouter typed_message_router_;
// Object that initializes the global common state used by the PC/SC-Lite
// client API functions.
//
// The stored pointer is leaked intentionally in the class destructor - see
// its comment for the justification.
std::unique_ptr<gsc::PcscLiteOverRequesterGlobal>
pcsc_lite_over_requester_global_;
// Object that allows to perform PIN dialog requests.
std::shared_ptr<PinDialogServer> pin_dialog_server_;
// Object that allows to receive and handle requests received from the
// chrome.certificateProvider JavaScript API event listeners (see
// <https://developer.chrome.com/extensions/certificateProvider#events>).
ccp::ApiBridge chrome_certificate_provider_api_bridge_;
// Handler of the onCertificatesRequested request
// from the chrome.certificateProvider JavaScript API (see
// <https://developer.chrome.com/extensions/certificateProvider#event-onCertificatesRequested>).
const std::shared_ptr<ClientCertificatesRequestHandler>
certificates_request_handler_;
// Handler of the onSignDigestRequested request
// from the chrome.certificateProvider JavaScript API (see
// <https://developer.chrome.com/extensions/certificateProvider#event-onSignDigestRequested>).
const std::shared_ptr<ClientSignDigestRequestHandler>
sign_digest_request_handler_;
};
// This class represents the NaCl module for the NaCl framework.
//
// Note that potentially the NaCl framework can request creating multiple
// pp::Instance objects through this module object, though, actually, this never
// happens with the current NaCl framework (and with no exact plans to change it
// in the future: see <http://crbug.com/385783>).
class PpModule final : public pp::Module {
public:
pp::Instance* CreateInstance(PP_Instance instance) override {
return new PpInstance(instance);
}
};
} // namespace
} // namespace smart_card_client
namespace pp {
// Entry point of the NaCl module, that is called by the NaCl framework when the
// module is being loaded.
Module* CreateModule() {
return new scc::PpModule;
}
} // namespace pp
| 42.550152 | 121 | 0.739339 | FabianHenneke |
2ddec34b6d5e53a1b5d8610eecf21202dda772e0 | 224 | cpp | C++ | test_utreexo.cpp | kcalvinalvin/libutreexo | 097504080e504b65946a7a98e918dbc1c843fd35 | [
"MIT"
] | null | null | null | test_utreexo.cpp | kcalvinalvin/libutreexo | 097504080e504b65946a7a98e918dbc1c843fd35 | [
"MIT"
] | null | null | null | test_utreexo.cpp | kcalvinalvin/libutreexo | 097504080e504b65946a7a98e918dbc1c843fd35 | [
"MIT"
] | null | null | null | #include <crypto/sha256.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
(void)argc;
(void)argv;
std::string sha2_impl = SHA256AutoDetect();
printf("sha2 implementation: %s\n", sha2_impl.c_str());
}
| 20.363636 | 59 | 0.647321 | kcalvinalvin |
2de12807719cb1fc8175ec6342141f619f4a5179 | 15,121 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/accessibilityservice/AccessibilityService.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/accessibilityservice/AccessibilityService.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/accessibilityservice/AccessibilityService.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/accessibilityservice/AccessibilityService.h"
#include "elastos/droid/accessibilityservice/CAccessibilityServiceClientWrapper.h"
#include "elastos/droid/view/accessibility/CAccessibilityInteractionClient.h"
#include "elastos/droid/internal/os/CHandlerCaller.h"
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Droid::Internal::Os::CHandlerCaller;
using Elastos::Droid::Internal::Os::EIID_IHandlerCallerCallback;
using Elastos::Droid::Content::EIID_IContext;
using Elastos::Droid::View::Accessibility::IAccessibilityRecord;
using Elastos::Droid::View::Accessibility::CAccessibilityInteractionClient;
using Elastos::Droid::View::Accessibility::IAccessibilityInteractionClient;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace AccessibilityService {
//==============================================================================
// IAccessibilityServiceClientWrapper
//==============================================================================
const Int32 IAccessibilityServiceClientWrapper::DO_SET_SET_CONNECTION = 1;
const Int32 IAccessibilityServiceClientWrapper::DO_ON_INTERRUPT = 2;
const Int32 IAccessibilityServiceClientWrapper::DO_ON_ACCESSIBILITY_EVENT = 3;
const Int32 IAccessibilityServiceClientWrapper::DO_ON_GESTURE = 4;
const Int32 IAccessibilityServiceClientWrapper::DO_CLEAR_ACCESSIBILITY_CACHE = 5;
const Int32 IAccessibilityServiceClientWrapper::DO_ON_KEY_EVENT = 6;
CAR_INTERFACE_IMPL_3(IAccessibilityServiceClientWrapper, Object, IIAccessibilityServiceClient,
IBinder, IHandlerCallerCallback)
IAccessibilityServiceClientWrapper::IAccessibilityServiceClientWrapper()
: mConnectionId(0)
{}
IAccessibilityServiceClientWrapper::~IAccessibilityServiceClientWrapper()
{}
ECode IAccessibilityServiceClientWrapper::constructor()
{
return NOERROR;
}
ECode IAccessibilityServiceClientWrapper::constructor(
/* [in] */ IContext* context,
/* [in] */ ILooper* looper,
/* [in] */ IAccessibilityServiceCallbacks* callback)
{
mCallback = callback;
CHandlerCaller::New(context, looper, this, TRUE, FALSE,
(IHandlerCaller**)&mCaller);
return NOERROR;
}
ECode IAccessibilityServiceClientWrapper::SetConnection(
/* [in] */ IIAccessibilityServiceConnection* connection,
/* [in] */ Int32 connectionId)
{
AutoPtr<IMessage> message;
mCaller->ObtainMessageIO(DO_SET_SET_CONNECTION, connectionId, connection, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::OnInterrupt()
{
AutoPtr<IMessage> message;
mCaller->ObtainMessage(DO_ON_INTERRUPT, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::OnAccessibilityEvent(
/* [in] */ IAccessibilityEvent* event)
{
AutoPtr<IMessage> message;
mCaller->ObtainMessageO(DO_ON_ACCESSIBILITY_EVENT, event, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::OnGesture(
/* [in] */ Int32 gestureId)
{
AutoPtr<IMessage> message;
mCaller->ObtainMessageI(DO_ON_GESTURE, gestureId, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::ClearAccessibilityCache()
{
AutoPtr<IMessage> message;
mCaller->ObtainMessage(DO_CLEAR_ACCESSIBILITY_CACHE, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::OnKeyEvent(
/* [in] */ IKeyEvent* event,
/* [in] */ Int32 sequence)
{
AutoPtr<IMessage> message;
mCaller->ObtainMessageIO(DO_ON_KEY_EVENT, sequence, event, (IMessage**)&message);
return mCaller->SendMessage(message);
}
ECode IAccessibilityServiceClientWrapper::ExecuteMessage(
/* [in] */ IMessage* message)
{
Int32 what, arg1;
message->GetWhat(&what);
message->GetArg1(&arg1);
switch (what) {
case DO_ON_ACCESSIBILITY_EVENT : {
AutoPtr<IInterface> obj;
message->GetObj((IInterface**)&obj);
IAccessibilityEvent* event = IAccessibilityEvent::Probe(obj);
if (event != NULL) {
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
client->OnAccessibilityEvent(event);
mCallback->OnAccessibilityEvent(event);
// Make sure the event is recycled.
// try {
IAccessibilityRecord::Probe(event)->Recycle();
// } catch (IllegalStateException ise) {
// /* ignore - best effort */
// }
}
return NOERROR;
}
case DO_ON_INTERRUPT :
mCallback->OnInterrupt();
return NOERROR;
case DO_SET_SET_CONNECTION : {
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
mConnectionId = arg1;
AutoPtr<IInterface> obj;
message->GetObj((IInterface**)&obj);
IIAccessibilityServiceConnection* connection = IIAccessibilityServiceConnection::Probe(obj);
if (connection != NULL) {
client->AddConnection(mConnectionId, connection);
mCallback->OnSetConnectionId(mConnectionId);
mCallback->OnServiceConnected();
}
else {
client->RemoveConnection(mConnectionId);
client->ClearCache();
mCallback->OnSetConnectionId(IAccessibilityInteractionClient::NO_ID);
}
return NOERROR;
}
case DO_ON_GESTURE : {
Boolean result;
mCallback->OnGesture(arg1, &result);
break;
}
case DO_CLEAR_ACCESSIBILITY_CACHE : {
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
client->ClearCache();
return NOERROR;
}
case DO_ON_KEY_EVENT : {
AutoPtr<IInterface> obj;
message->GetObj((IInterface**)&obj);
AutoPtr<IKeyEvent> event = IKeyEvent::Probe(obj);
// try {
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
AutoPtr<IIAccessibilityServiceConnection> connection;
client->GetConnection(mConnectionId, (IIAccessibilityServiceConnection**)&connection);
if (connection != NULL) {
Boolean result;
mCallback->OnKeyEvent(event, &result);
Int32 sequence = arg1;
// try {
connection->SetOnKeyEventResult(result, sequence);
// } catch (RemoteException re) {
/* ignore */
// }
}
// } finally {
// Make sure the event is recycled.
// try {
IAccessibilityRecord::Probe(event)->Recycle();
// } catch (IllegalStateException ise) {
/* ignore - best effort */
// // }
// }
return NOERROR;
}
default :
Logger::W("IAccessibilityServiceClientWrapper", "Unknown message type %d", what);
return NOERROR;
}
return NOERROR;
}
ECode IAccessibilityServiceClientWrapper::ToString(
/* [out] */ String* info)
{
VALIDATE_NOT_NULL(info);
*info = String("IAccessibilityServiceClientWrapper");
return NOERROR;
}
//==============================================================================
// AccessibilityService::MyAccessibilityServiceCallbacks
//==============================================================================
CAR_INTERFACE_IMPL(AccessibilityService::MyAccessibilityServiceCallbacks, Object, IAccessibilityServiceCallbacks)
AccessibilityService::MyAccessibilityServiceCallbacks::MyAccessibilityServiceCallbacks(
/* [in] */ AccessibilityService* host)
: mHost(host)
{
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnAccessibilityEvent(
/* [in] */ IAccessibilityEvent* event)
{
return mHost->OnAccessibilityEvent(event);
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnInterrupt()
{
return mHost->OnInterrupt();
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnServiceConnected()
{
return mHost->OnServiceConnected();
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnSetConnectionId(
/* [in] */ Int32 connectionId)
{
mHost->mConnectionId = connectionId;
return NOERROR;
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnGesture(
/* [in] */ Int32 gestureId,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
return mHost->OnGesture(gestureId, result);
}
ECode AccessibilityService::MyAccessibilityServiceCallbacks::OnKeyEvent(
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
return mHost->OnKeyEvent(event, result);
}
//==============================================================================
// AccessibilityService
//==============================================================================
const String AccessibilityService::TAG("AccessibilityService");
CAR_INTERFACE_IMPL(AccessibilityService, Service, IAccessibilityService)
AccessibilityService::AccessibilityService()
: mConnectionId(0)
{}
AccessibilityService::~AccessibilityService()
{}
ECode AccessibilityService::OnAccessibilityEvent(
/* [in] */ IAccessibilityEvent* event)
{
return NOERROR;
}
ECode AccessibilityService::OnInterrupt()
{
return NOERROR;
}
ECode AccessibilityService::GetWindows(
/* [out] */ IList** windows)
{
VALIDATE_NOT_NULL(windows)
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
return client->GetWindows(mConnectionId, windows);
}
ECode AccessibilityService::GetRootInActiveWindow(
/* [out] */ IAccessibilityNodeInfo** info)
{
VALIDATE_NOT_NULL(info);
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
return client->GetRootInActiveWindow(mConnectionId, info);
}
ECode AccessibilityService::PerformGlobalAction(
/* [in] */ Int32 action,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
AutoPtr<IIAccessibilityServiceConnection> connection;
client->GetConnection(mConnectionId, (IIAccessibilityServiceConnection**)&connection);
if (connection != NULL) {
// try {
ECode ec = connection->PerformGlobalAction(action, result);
if (SUCCEEDED(ec)) return NOERROR;
Logger::W(TAG, "Error while calling performGlobalAction. 0x%08x", ec);
// } catch (RemoteException re) {
// Log.w(TAG, "Error while calling performGlobalAction", re);
// }
}
*result = FALSE;
return NOERROR;
}
ECode AccessibilityService::FindFocus(
/* [in] */ Int32 focus,
/* [out] */ IAccessibilityNodeInfo** ret)
{
VALIDATE_NOT_NULL(ret);
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
return client->FindFocus(mConnectionId,
IAccessibilityNodeInfo::ANY_WINDOW_ID,
IAccessibilityNodeInfo::ROOT_NODE_ID, focus, ret);
}
ECode AccessibilityService::GetServiceInfo(
/* [out] */ IAccessibilityServiceInfo** info)
{
VALIDATE_NOT_NULL(info);
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
AutoPtr<IIAccessibilityServiceConnection> connection;
client->GetConnection(mConnectionId, (IIAccessibilityServiceConnection**)&connection);
if (connection != NULL) {
// try {
ECode ec = connection->GetServiceInfo(info);
if (SUCCEEDED(ec)) return NOERROR;
Logger::W(TAG, "Error while getting AccessibilityServiceInfo. 0x%08x", ec);
// } catch (RemoteException re) {
// Log.w(TAG, "Error while getting AccessibilityServiceInfo", re);
// }
}
*info = NULL;
return NOERROR;
}
ECode AccessibilityService::SetServiceInfo(
/* [in] */ IAccessibilityServiceInfo* info)
{
mInfo = info;
SendServiceInfo();
return NOERROR;
}
ECode AccessibilityService::OnBind(
/* [in] */ IIntent* intent,
/* [out] */ IBinder** binder)
{
VALIDATE_NOT_NULL(binder);
*binder = NULL;
AutoPtr<ILooper> looper;
Service::GetMainLooper((ILooper**)&looper);
AutoPtr<MyAccessibilityServiceCallbacks> callbacks = new MyAccessibilityServiceCallbacks(this);
AutoPtr<IIAccessibilityServiceClient> wrapper;
CAccessibilityServiceClientWrapper::New(this, looper, callbacks,
(IIAccessibilityServiceClient**)&wrapper);
*binder = IBinder::Probe(wrapper);
REFCOUNT_ADD(*binder);
return NOERROR;
}
ECode AccessibilityService::OnServiceConnected()
{
return NOERROR;
}
ECode AccessibilityService::OnGesture(
/* [in] */ Int32 gestureId,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
return NOERROR;
}
ECode AccessibilityService::OnKeyEvent(
/* [in] */ IKeyEvent* event,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
*result = FALSE;
return NOERROR;
}
void AccessibilityService::SendServiceInfo()
{
AutoPtr<IAccessibilityInteractionClient> client = CAccessibilityInteractionClient::GetInstance();
AutoPtr<IIAccessibilityServiceConnection> connection;
client->GetConnection(mConnectionId, (IIAccessibilityServiceConnection**)&connection);
if (mInfo != NULL && connection != NULL) {
// try {
ECode ec = connection->SetServiceInfo(mInfo);
if (ec == (ECode)E_REMOTE_EXCEPTION) {
Logger::W(TAG, "Error while setting AccessibilityServiceInfo. 0x%08x", ec);
}
mInfo = NULL;
client->ClearCache();
// } catch (RemoteException re) {
// Log.w(TAG, "Error while setting AccessibilityServiceInfo", re);
// }
}
}
}
}
}
| 33.527716 | 113 | 0.658753 | jingcao80 |
2de1e63d7c6598ad8eabf00967b3dad0bce691bb | 3,985 | hpp | C++ | src/storage/tree/Accounts.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | src/storage/tree/Accounts.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | src/storage/tree/Accounts.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// 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/.
#pragma once
#include "Internal.hpp"
#include "opentxs/core/Identifier.hpp"
#include "Node.hpp"
#include <map>
#include <set>
namespace opentxs::storage
{
class Accounts : public Node
{
public:
OTIdentifier AccountContract(const Identifier& accountID) const;
OTIdentifier AccountIssuer(const Identifier& accountID) const;
OTIdentifier AccountOwner(const Identifier& accountID) const;
OTIdentifier AccountServer(const Identifier& accountID) const;
OTIdentifier AccountSigner(const Identifier& accountID) const;
proto::ContactItemType AccountUnit(const Identifier& accountID) const;
std::set<OTIdentifier> AccountsByContract(const Identifier& unit) const;
std::set<OTIdentifier> AccountsByIssuer(const Identifier& issuerNym) const;
std::set<OTIdentifier> AccountsByOwner(const Identifier& ownerNym) const;
std::set<OTIdentifier> AccountsByServer(const Identifier& server) const;
std::set<OTIdentifier> AccountsByUnit(
const proto::ContactItemType unit) const;
std::string Alias(const std::string& id) const;
bool Load(
const std::string& id,
std::string& output,
std::string& alias,
const bool checking) const;
bool Delete(const std::string& id);
bool SetAlias(const std::string& id, const std::string& alias);
bool Store(
const std::string& id,
const std::string& data,
const std::string& alias,
const Identifier& ownerNym,
const Identifier& signerNym,
const Identifier& issuerNym,
const Identifier& server,
const Identifier& contract,
const proto::ContactItemType unit);
~Accounts() = default;
private:
friend class Tree;
using Index = std::map<OTIdentifier, std::set<OTIdentifier>>;
using UnitIndex = std::map<proto::ContactItemType, std::set<OTIdentifier>>;
/** owner, signer, issuer, server, contract, unit */
using AccountData = std::tuple<
OTIdentifier,
OTIdentifier,
OTIdentifier,
OTIdentifier,
OTIdentifier,
proto::ContactItemType>;
using ReverseIndex = std::map<OTIdentifier, AccountData>;
Index owner_index_{};
Index signer_index_{};
Index issuer_index_{};
Index server_index_{};
Index contract_index_{};
UnitIndex unit_index_{};
mutable ReverseIndex account_data_{};
static bool add_set_index(
const Identifier& accountID,
const Identifier& argID,
Identifier& mapID,
Index& index);
template <typename K, typename I>
static void erase(const Identifier& accountID, const K& key, I& index)
{
try {
auto& set = index.at(key);
set.erase(accountID);
if (0 == set.size()) { index.erase(key); }
} catch (...) {
}
}
AccountData& get_account_data(
const Lock& lock,
const OTIdentifier& accountID) const;
proto::StorageAccounts serialize() const;
bool check_update_account(
const Lock& lock,
const OTIdentifier& accountID,
const Identifier& ownerNym,
const Identifier& signerNym,
const Identifier& issuerNym,
const Identifier& server,
const Identifier& contract,
const proto::ContactItemType unit);
void init(const std::string& hash) override;
bool save(const Lock& lock) const override;
Accounts(
const opentxs::api::storage::Driver& storage,
const std::string& key);
Accounts() = delete;
Accounts(const Accounts&) = delete;
Accounts(Accounts&&) = delete;
Accounts operator=(const Accounts&) = delete;
Accounts operator=(Accounts&&) = delete;
};
} // namespace opentxs::storage
| 32.137097 | 79 | 0.667503 | nopdotcom |
2de7b3ef8326c522e40ae0b536ed385a76b4f9c9 | 810 | cc | C++ | solutions/tests/cache/CacheTest.cc | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | 1 | 2019-04-19T01:05:07.000Z | 2019-04-19T01:05:07.000Z | solutions/tests/cache/CacheTest.cc | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | null | null | null | solutions/tests/cache/CacheTest.cc | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | null | null | null | #include "CacheTest.hpp"
#include <unistd.h>
Test*
CacheTest::suite() {
TestSuite* res = new TestSuite("UtilsTest");
res->addTest(new TestCaller<CacheTest>(
"sample_test",
&CacheTest::simpleTest));
return res;
}
void
CacheTest::simpleTest() {
LRUCache l(4, -1);
std::vector<std::list<std::pair<int, int>>> expectedResult = {
{
{1, 1}
},
{
{3, 3},
{1, 1}
},
{
{2, 2},
{3, 3},
{1, 1}
},
{
{3, 3},
{2, 2},
{1, 1}
},
{
{5, 5},
{3, 3},
{2, 2},
{1, 1}
},
{
{7, 7},
{5, 5},
{3, 3},
{2, 2}
},
{
{1, 1},
{7, 7},
{5, 5},
{3, 3}
},
{
{9, 9},
{1, 1},
{7, 7},
{5, 5}
}
};
int i = 0;
for (int a : {1,3,2,3,5,7,1,9}) {
l.set(a, a);
CPPUNIT_ASSERT(expectedResult.at(i) == l.data);
i++;
}
}
| 11.571429 | 63 | 0.425926 | PysKa-Ratzinger |
2dea9af562d4923a538b4c47a971342b551f7837 | 885 | hpp | C++ | inference-engine/src/legacy_api/src/network_serializer_v7.hpp | Mobious96/openvino | cbdd50556bc350db36da53da2a2db9a2f54e201e | [
"Apache-2.0"
] | null | null | null | inference-engine/src/legacy_api/src/network_serializer_v7.hpp | Mobious96/openvino | cbdd50556bc350db36da53da2a2db9a2f54e201e | [
"Apache-2.0"
] | null | null | null | inference-engine/src/legacy_api/src/network_serializer_v7.hpp | Mobious96/openvino | cbdd50556bc350db36da53da2a2db9a2f54e201e | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <ie_icnn_network.hpp>
#include <legacy/ie_layers.h>
#include <string>
#include <vector>
namespace InferenceEngine {
namespace Serialization {
/**
* @brief Serialize execution network into IE IR-like XML file
* @param xmlPath Path to XML file
* @param network network to be serialized
*/
INFERENCE_ENGINE_API_CPP(void) Serialize(const std::string& xmlPath, const InferenceEngine::ICNNNetwork& network);
/**
* @brief Returns set of topologically sorted layers
* @param network network to be sorted
* @return `std::vector` of topologically sorted CNN layers
*/
INFERENCE_ENGINE_API_CPP(std::vector<CNNLayerPtr>) TopologicalSort(const InferenceEngine::ICNNNetwork& network);
} // namespace Serialization
} // namespace InferenceEngine
| 27.65625 | 114 | 0.740113 | Mobious96 |
2dedb6de915b725be3467a3766c58fba9de74ae4 | 569 | cpp | C++ | ProducerComsumer/buffer.cpp | Awybupt/OperatingSystem | 9afddba501c779bad5ed653973ed410dd0389fe1 | [
"MIT"
] | null | null | null | ProducerComsumer/buffer.cpp | Awybupt/OperatingSystem | 9afddba501c779bad5ed653973ed410dd0389fe1 | [
"MIT"
] | null | null | null | ProducerComsumer/buffer.cpp | Awybupt/OperatingSystem | 9afddba501c779bad5ed653973ed410dd0389fe1 | [
"MIT"
] | 1 | 2019-01-13T14:32:02.000Z | 2019-01-13T14:32:02.000Z | //
// buffer.cpp
// Producer&&Comsumer
//
// Created by 魏晓 on 10/29/17.
// Copyright © 2017 魏晓. All rights reserved.
//
#include <stdio.h>
#include "buffer.hpp"
int insert_item(bufferQueue *queue,buffer_item x)
{
if((queue->tail+1)%BUFFER_SIZE==queue->tail) return -1;
queue->data[queue->tail]=x;
queue->tail=(queue->tail+1)%BUFFER_SIZE;
return 0;
}
int remove_item(bufferQueue *queue)
{
if(queue->head==queue->tail) return -1;//fail
int temp=queue->data[queue->head];
queue->head=(queue->head+1)%BUFFER_SIZE;
return temp;
}
| 20.321429 | 59 | 0.646749 | Awybupt |
2dedbc6a592c217342c7df4a4e7a85d38d9564ee | 5,087 | cc | C++ | ui/views/examples/flex_layout_example.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/views/examples/flex_layout_example.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/views/examples/flex_layout_example.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2018 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 "ui/views/examples/flex_layout_example.h"
#include <memory>
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/models/combobox_model.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/combobox/combobox.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/examples/example_combobox_model.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
#include "ui/views/view_class_properties.h"
namespace views {
namespace examples {
FlexLayoutExample::FlexLayoutExample() : LayoutExampleBase("Flex Layout") {}
FlexLayoutExample::~FlexLayoutExample() = default;
void FlexLayoutExample::CreateAdditionalControls(int vertical_pos) {
static const char* const orientation_values[2] = {"Horizontal", "Vertical"};
static const char* const main_axis_values[3] = {"Start", "Center", "End"};
static const char* const cross_axis_values[4] = {"Stretch", "Start", "Center",
"End"};
orientation_ = CreateAndAddCombobox(base::ASCIIToUTF16("Orientation"),
orientation_values, 2, &vertical_pos);
main_axis_alignment_ = CreateAndAddCombobox(
base::ASCIIToUTF16("Main axis"), main_axis_values, 3, &vertical_pos);
cross_axis_alignment_ = CreateAndAddCombobox(
base::ASCIIToUTF16("Cross axis"), cross_axis_values, 4, &vertical_pos);
CreateMarginsTextFields(base::ASCIIToUTF16("Interior margin"),
&interior_margin_, &vertical_pos);
CreateMarginsTextFields(base::ASCIIToUTF16("Default margins"),
&default_child_margins_, &vertical_pos);
collapse_margins_ = CreateAndAddCheckbox(
base::ASCIIToUTF16("Collapse margins"), &vertical_pos);
ignore_default_main_axis_margins_ = CreateAndAddCheckbox(
base::ASCIIToUTF16("Ignore main axis margins"), &vertical_pos);
layout_ = layout_panel()->SetLayoutManager(std::make_unique<FlexLayout>());
}
void FlexLayoutExample::OnPerformAction(Combobox* combobox) {
static const LayoutOrientation orientations[2] = {
LayoutOrientation::kHorizontal, LayoutOrientation::kVertical};
static const LayoutAlignment main_axis_alignments[3] = {
LayoutAlignment::kStart, LayoutAlignment::kCenter, LayoutAlignment::kEnd};
static const LayoutAlignment cross_axis_alignments[4] = {
LayoutAlignment::kStretch, LayoutAlignment::kStart,
LayoutAlignment::kCenter, LayoutAlignment::kEnd};
if (combobox == orientation_) {
layout_->SetOrientation(orientations[combobox->GetSelectedIndex()]);
} else if (combobox == main_axis_alignment_) {
layout_->SetMainAxisAlignment(
main_axis_alignments[combobox->GetSelectedIndex()]);
} else if (combobox == cross_axis_alignment_) {
layout_->SetCrossAxisAlignment(
cross_axis_alignments[combobox->GetSelectedIndex()]);
}
RefreshLayoutPanel(false);
}
void FlexLayoutExample::ContentsChanged(Textfield* sender,
const base::string16& new_contents) {
layout_->SetInteriorMargin(
LayoutExampleBase::TextfieldsToInsets(interior_margin_));
layout_->SetDefault(views::kMarginsKey, LayoutExampleBase::TextfieldsToInsets(
default_child_margins_));
RefreshLayoutPanel(false);
}
void FlexLayoutExample::ButtonPressedImpl(Button* sender) {
if (sender == collapse_margins_) {
layout_->SetCollapseMargins(collapse_margins_->GetChecked());
} else if (sender == ignore_default_main_axis_margins_) {
layout_->SetIgnoreDefaultMainAxisMargins(
ignore_default_main_axis_margins_->GetChecked());
}
RefreshLayoutPanel(false);
}
void FlexLayoutExample::UpdateLayoutManager() {
for (View* child : layout_panel()->children()) {
ChildPanel* panel = static_cast<ChildPanel*>(child);
int flex = panel->GetFlex();
if (flex < 0)
panel->ClearProperty(views::kFlexBehaviorKey);
else
panel->SetProperty(views::kFlexBehaviorKey, GetFlexSpecification(flex));
}
}
FlexSpecification FlexLayoutExample::GetFlexSpecification(int weight) const {
return weight > 0
? FlexSpecification(MinimumFlexSizeRule::kScaleToZero,
MaximumFlexSizeRule::kUnbounded)
.WithWeight(weight)
: FlexSpecification(MinimumFlexSizeRule::kPreferredSnapToZero,
MaximumFlexSizeRule::kPreferred)
.WithWeight(0);
}
} // namespace examples
} // namespace views
| 40.373016 | 80 | 0.712797 | mghgroup |
2dee881bc9c468e5c55a5dfcc49d00c728b46c34 | 1,388 | cpp | C++ | Codeforces/258C.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | Codeforces/258C.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | Codeforces/258C.cpp | Alipashaimani/Competitive-programming | 5d55567b71ea61e69a6450cda7323c41956d3cb9 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 100 , MOD = 1e9 + 7 ;
int dp[MAXN] , n , mx;
long long ans , temp;
vector <int> divv;
long long power(long long x , long long y){
if (y == 0)
return 1;
long long t = power (x, y / 2);
t = (t * t) % MOD;
if (y % 2 == 1)
t = (t * x) % MOD;
return t;
}
void dive(int x){
divv.clear();
for (int i = 1 ; i*i <=x ; i++){
if (i * i == x)
divv.push_back(i);
else if (x % i == 0){
divv.push_back(i);
divv.push_back(x/i);
}
}
}
int main(){
cin >> n;
for (int i = 0; i < n; i++){
int x; cin >> x;
mx = max(x,mx);
dp [x]++;
}
for (int i = 1; i < MAXN; i++)
dp[i] = dp[i-1] + dp[i];
for (int i = 1; i <= mx; i++){
dive(i);
sort(divv.begin(),divv.end());
temp = 1;
for (int j = 1; j < divv.size(); j++){
temp = (temp * power(j,dp[divv[j]-1] - dp[divv[j-1]-1])) % MOD;
}
long long a = ((temp * power(divv.size(),(dp[100000]-dp[divv[divv.size()-1]-1])) )%MOD);
long long b = ((temp * power(divv.size() - 1,(dp[100000]-dp[divv[divv.size()-1]-1])) )%MOD);
temp = a - b;
if (temp <0)
temp += MOD;
ans = (ans +temp)%MOD;
}
cout<<ans<<endl;
return 0;
}
| 22.754098 | 100 | 0.423631 | Alipashaimani |
2df158dfc7812335c241a4b8113f9fa09fad53d9 | 4,129 | hpp | C++ | extlib/include/xyginext/audio/AudioScape.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 17 | 2018-06-23T14:40:56.000Z | 2019-07-02T11:58:55.000Z | extlib/include/xyginext/audio/AudioScape.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | 3 | 2018-06-23T12:35:12.000Z | 2018-06-23T12:38:54.000Z | extlib/include/xyginext/audio/AudioScape.hpp | fallahn/speljongen | 57cb5e09eec7db8c21ee7b3e7943fa0a76738c51 | [
"Unlicense"
] | null | null | null | /*********************************************************************
(c) Matt Marchant 2017 - 2019
http://trederia.blogspot.com
xygineXT - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
#pragma once
#include "../Config.hpp"
#include "../ecs/components/AudioEmitter.hpp"
#include "../core/ConfigFile.hpp"
#include <string>
#include <unordered_map>
namespace xy
{
class AudioResource;
/*!
\brief Contains one or more definitions used to create AudioEmitter components.
Similarly to the SpriteSheet class used for loading Sprites from configuration
files, AudioScapes can be used to define the settings used to create AudioEmitter
components. AudioScape files usually have the extension *.xas with the following
ConfigFile compatible layout:
\code
audio_scape NAME
{
emitter NAME_ONE
{
path = "STR_PATH_TO_FILE"
streaming = BOOL
pitch = FLOAT
volume = FLOAT
relative_listener = BOOL
min_distance = FLOAT
attenuation = FLOAT
looped = BOOL
mixer_channel = INT
}
emitter NAME_TWO
{
path = "STR_PATH_TO_FILE"
streaming = BOOL
pitch = FLOAT
volume = FLOAT
relative_listener = BOOL
min_distance = FLOAT
attenuation = FLOAT
looped = BOOL
mixer_channel = INT
}
}
\endcode
Emitter properties are optional (except path and streaming) and any omitted properties
will fall back to their default values.
*/
class XY_EXPORT_API AudioScape final
{
public:
/*!
\brief Constructor
\param rx Reference to an AudioResource object used to cache
any non-streamed audio files.
*/
AudioScape(AudioResource& rx);
/*!
\brief Attempts to load an AudioScape file from the given path
\param path String containing the path to the *.xas file to load
\returns bool true if successful else false
*/
bool loadFromFile(const std::string& path);
/*!
\brief Saves the AudioScape configuration to a given path.
AudioScape files normally have the extension *.xas
*/
bool saveToFile(const std::string& path);
/*!
\brief Returns an AudioEmitter configured with the given name from
the loaded confugration, if it exists, else returns an Uninitialised
AudioEmitter. Use AudioEmitter::hasSource() to check validity of the
returned emitter.
*/
AudioEmitter getEmitter(const std::string& name) const;
/*!
\brief Adds an emitter configuration to the AudioScape.
\param name Name of the AudioEmitter as it appears in the configuration.
If an emitter with the name already exists then it will be overwritten.
\param emitter An AudioEmitter whose current settings will be saved in the
configuration file.
*/
void addEmitter(const std::string& name, const AudioEmitter& emitter);
private:
AudioResource& m_audioResource;
std::unordered_map<std::string, ConfigObject> m_emitterConfigs;
};
} //namespace xy | 33.298387 | 90 | 0.644224 | fallahn |
2df39609f6624936adbb8612f353638b10a972cd | 678 | cpp | C++ | examples/xtd.forms.examples/applications/application_restart/src/application_restart.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | 251 | 2019-04-20T02:02:24.000Z | 2022-03-31T09:52:08.000Z | examples/xtd.forms.examples/applications/application_restart/src/application_restart.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | 29 | 2021-01-07T12:52:12.000Z | 2022-03-29T08:42:14.000Z | examples/xtd.forms.examples/applications/application_restart/src/application_restart.cpp | ExternalRepositories/xtd | 5889d69900ad22a00fcb640d7850a1d599cf593a | [
"MIT"
] | 27 | 2019-11-21T02:37:44.000Z | 2022-03-30T22:59:14.000Z | #include <xtd/xtd>
using namespace std;
using namespace xtd;
using namespace xtd::forms;
int main() {
auto restart_count = 0;
if (!environment::get_environment_variable("applicatioon_restart_count").empty())
restart_count = parse<int>(environment::get_environment_variable("applicatioon_restart_count"));
auto main_form = control::create<form>(ustring::format("Restart {} times", restart_count));
auto restart_button = control::create<button>(*main_form, "Restart", {10 ,10});
restart_button->click += application::restart;
environment::set_environment_variable("applicatioon_restart_count", to_string(restart_count + 1));
application::run(*main_form);
}
| 33.9 | 100 | 0.756637 | ExternalRepositories |
2df3c89c672af712777848ad167426fca2117a99 | 1,167 | hpp | C++ | Siv3D/src/Siv3D/Renderer2D/CurrentBatchStateChanges.hpp | emadurandal/OpenSiv3D | 2c7a77526be7bb8669a223066210337d74bdc9c6 | [
"MIT"
] | 709 | 2016-03-19T07:55:58.000Z | 2022-03-31T08:02:22.000Z | Siv3D/src/Siv3D/Renderer2D/CurrentBatchStateChanges.hpp | emadurandal/OpenSiv3D | 2c7a77526be7bb8669a223066210337d74bdc9c6 | [
"MIT"
] | 415 | 2017-05-21T05:05:02.000Z | 2022-03-29T16:08:27.000Z | Siv3D/src/Siv3D/Renderer2D/CurrentBatchStateChanges.hpp | emadurandal/OpenSiv3D | 2c7a77526be7bb8669a223066210337d74bdc9c6 | [
"MIT"
] | 123 | 2016-03-19T12:47:08.000Z | 2022-03-25T03:47:51.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include <Siv3D/Common.hpp>
# include <Siv3D/Mat3x2.hpp>
# include <Siv3D/MathConstants.hpp>
namespace s3d
{
namespace detail
{
[[nodiscard]]
inline float CalculateMaxScaling(const Mat3x2& mat)
{
return (Float2{ mat._11 + mat._21, mat._12 + mat._22 }.length() / Math::Sqrt2_v<float>);
}
}
template <class Enum>
class CurrentBatchStateChanges
{
private:
uint64 m_states = 0;
public:
[[nodiscard]]
bool has(const Enum command) const noexcept
{
return ((m_states & (0x1ull << FromEnum(command))) != 0);
}
[[nodiscard]]
bool hasStateChange() const noexcept
{
return (m_states > 1);
}
void set(const Enum command) noexcept
{
m_states |= (0x1ull << FromEnum(command));
}
void clear(const Enum command) noexcept
{
m_states &= ~(0x1ull << FromEnum(command));
}
void clear() noexcept
{
m_states = 0;
}
};
}
| 17.953846 | 91 | 0.59383 | emadurandal |
2df7102107f72e7e5c0f5d5a7caedad4300879e1 | 4,103 | hpp | C++ | linear_algebra.inl.hpp | matheuscscp/linear_algebra | 2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e | [
"MIT"
] | null | null | null | linear_algebra.inl.hpp | matheuscscp/linear_algebra | 2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e | [
"MIT"
] | null | null | null | linear_algebra.inl.hpp | matheuscscp/linear_algebra | 2a8d5dee1ab1b6d62ba1e1987e2251b87febe74e | [
"MIT"
] | null | null | null | /*
* linear_algebra.inl.hpp
*
* Created on: Feb 21, 2015
* Author: Pimenta
*/
#ifndef LINEAR_ALGEBRA_INL_HPP_
#define LINEAR_ALGEBRA_INL_HPP_
#include <cmath>
namespace linear_algebra {
template <typename T>
struct Vector3 {
T x, y, z;
Vector3(T x = 0, T y = 0, T z = 0) : x(x), y(y), z(z) {
}
// arithmetic operators
inline Vector3 operator+(const Vector3& other) {
return Vector3(x + other.x, y + other.y, z + other.z);
}
inline Vector3 operator-(const Vector3& other) {
return Vector3(x - other.x, y - other.y, z - other.z);
}
inline Vector3 operator-() {
return Vector3(-x, -y, -z);
}
inline Vector3 operator*(T scalar) {
return Vector3(x*scalar, y*scalar, z*scalar);
}
inline Vector3 operator/(T scalar) {
return Vector3(x/scalar, y/scalar, z/scalar);
}
// compound assignment
Vector3& operator+=(const Vector3& other) {
x += other.x;
y += other.y;
z += other.z;
return *this;
}
Vector3& operator-=(const Vector3& other) {
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
Vector3& operator*=(T scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
return *this;
}
Vector3& operator/=(T scalar) {
x /= scalar;
y /= scalar;
z /= scalar;
return *this;
}
// relational operators
inline bool operator==(const Vector3& other) {
return x == other.x && y == other.y && z == other.z;
}
inline bool operator!=(const Vector3& other) {
return x != other.x || y != other.y || z != other.z;
}
// methods
inline T length() {
return sqrt(x*x + y*y + z*z);
}
inline Vector3 versor() {
T len = length();
if (len == 0) {
return *this;
}
return operator/(len);
}
inline T dot(const Vector3& other) {
return x*other.x + y*other.y + z*other.z;
}
inline Vector3 cross(const Vector3& v) {
return Vector3(y*v.z - z*v.y, z*v.x - x*v.z, x*v.x - y*v.x);
}
inline T angle(const Vector3& other) {
T len = length()*other.length();
if (len == 0) {
return 0;
}
return acos(dot(other)/len);
}
inline Vector3 proj(const Vector3& other) { // other on this
Vector3 v = versor();
return v*v.dot(other);
}
inline Vector3 rej(const Vector3& other) { // other from this
return other - proj(other);
}
inline T scalarproj(const Vector3& other) { // other on this
return versor().dot(other);
}
inline Vector3 rotate(const Vector3& other, T angle) { // other around this
Vector3 u = versor();
T a2 = u.x*u.x, ab = u.x*u.y, ac = u.x*u.z;
T b2 = u.y*u.y, bc = u.y*u.z, c2 = u.z*u.z;
T sint = sin(angle), cost = cos(angle), _1mcost = 1 - cost;
T asint = u.x*sint, bsint = u.y*sint, csint = u.z*sint;
T x = other.x, y = other.y, z = other.z;
return Vector3(
x*(a2*_1mcost + cost) + y*(ab*_1mcost - csint) + z*(ac*_1mcost + bsint),
x*(ab*_1mcost + csint) + y*(b2*_1mcost + cost) + z*(bc*_1mcost - asint),
x*(ac*_1mcost - bsint) + y*(bc*_1mcost + asint) + z*(c2*_1mcost + cost)
);
}
};
// determinant
template <typename T>
T det(const Vector3<T>& a, const Vector3<T>& b) {
return a.x*b.y - a.y*b.x;
}
template <typename T>
T det(const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c) {
return
a.x*b.y*c.z + b.x*c.y*a.z + c.x*a.y*b.z
- a.z*b.y*c.x - b.z*c.y*a.x - c.z*a.y*b.x
;
}
// linear system
template <typename T>
bool solvesys(
const Vector3<T>& a, const Vector3<T>& b,
const Vector3<T>& c,
T& x, T& y
) {
T D = det(a, b);
if (D == 0) {
return false;
}
x = det(c, b)/D;
y = det(a, c)/D;
return true;
}
template <typename T>
bool solvesys(
const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c,
const Vector3<T>& d,
T& x, T& y, T& z
) {
T D = det(a, b, c);
if (D == 0) {
return false;
}
x = det(d, b, c)/D;
y = det(a, d, c)/D;
z = det(a, b, d)/D;
return true;
}
// basic types
typedef Vector3<float> Vector3f;
typedef Vector3<double> Vector3d;
} // namespace linear_algebra
#endif /* LINEAR_ALGEBRA_INL_HPP_ */
| 23.58046 | 79 | 0.571289 | matheuscscp |
2df739bf9bb4abb66a79b7b4cd8b4f70dfbf4e5a | 114 | hh | C++ | P09_Analysis/source/include/Analysis.hh | koichi-murakami/g4tutorial2020 | 0162a94dc1407a39dd0651ac530d10913037c6f0 | [
"BSD-2-Clause"
] | 2 | 2020-11-05T06:31:43.000Z | 2021-07-09T05:32:19.000Z | P09_Analysis/source/include/Analysis.hh | koichi-murakami/g4tutorial2020 | 0162a94dc1407a39dd0651ac530d10913037c6f0 | [
"BSD-2-Clause"
] | null | null | null | P09_Analysis/source/include/Analysis.hh | koichi-murakami/g4tutorial2020 | 0162a94dc1407a39dd0651ac530d10913037c6f0 | [
"BSD-2-Clause"
] | null | null | null |
#ifndef Analysis_h
#define Analysis_h 1
//#include "g4root.hh"
#include "g4csv.hh"
//#include "g4xml.hh"
#endif
| 12.666667 | 22 | 0.710526 | koichi-murakami |
2df8e2bd2ca2f77a3b26a8885c3b5578f87b74cc | 5,233 | cxx | C++ | Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx | liuxuvip/OTB | 73ed482d62c2924aea158aac14d725dc9447083b | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/IO/IOGDAL/test/otbGDALRPCTransformerTest2.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* 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 "itkPoint.h"
#include "otbGDALRPCTransformer.h"
#include "itkEuclideanDistanceMetric.h"
#include "otbGeographicalDistance.h"
#include "otbImageMetadata.h"
#include "otbMetaDataKey.h"
#include "otbGeomMetadataSupplier.h"
#include "otbImageMetadataInterfaceFactory.h"
#include "otbMacro.h"
#include "otbDEMHandler.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
//typedef otb::Image<double> ImageType;
typedef std::vector<itk::Point<double, 3>> pointsContainerType;
typedef itk::Statistics::EuclideanDistanceMetric<otb::GDALRPCTransformer::PointType> DistanceType;
typedef otb::GeographicalDistance<otb::GDALRPCTransformer::PointType> GeographicalDistanceType;
int otbGDALRPCTransformerTest2(int itkNotUsed(argc), char* argv[])
{
bool success = true;
otb::GDALRPCTransformer::PointType imagePoint;
otb::GDALRPCTransformer::PointType geo3dPoint;
// Inputs
std::string rpcFile(argv[1]);
std::string gcpFileName(argv[2]);
double geoTol(atof(argv[3]));
double imgTol(atof(argv[4]));
// Tools
auto distance = DistanceType::New();
auto geoDistance = GeographicalDistanceType::New();
otb::ImageMetadata imd;
if (0 == rpcFile.compare(rpcFile.length() - 4, 4, "geom"))
{
// Fetching the RPC model from a GEOM file
otb::GeomMetadataSupplier geomSupplier(rpcFile);
for (int loop = 0 ; loop < geomSupplier.GetNbBands() ; ++loop)
imd.Bands.emplace_back();
otb::ImageMetadataInterfaceFactory::CreateIMI(imd, geomSupplier);
geomSupplier.FetchRPC(imd);
}
else
{
// Fetching the RPC model from a product
typedef otb::Image<double, 2> ImageType;
typedef otb::ImageFileReader<ImageType> ImageFileReaderType;
auto reader = ImageFileReaderType::New();
reader->SetFileName(rpcFile);
reader->UpdateOutputInformation();
imd = reader->GetOutput()->GetImageMetadata();
}
auto rpcModel = boost::any_cast<otb::Projection::RPCParam>(imd[otb::MDGeom::RPC]);
// Setting the RPCTransformer
// otb::DEMHandler::GetInstance().SetDefaultHeightAboveEllipsoid(0.0);
otb::GDALRPCTransformer transformer(rpcModel.LineOffset, rpcModel.SampleOffset, rpcModel.LatOffset, rpcModel.LonOffset, rpcModel.HeightOffset,
rpcModel.LineScale, rpcModel.SampleScale, rpcModel.LatScale, rpcModel.LonScale, rpcModel.HeightScale,
rpcModel.LineNum, rpcModel.LineDen, rpcModel.SampleNum, rpcModel.SampleDen, false);
// Loading the GCP
pointsContainerType pointsContainer;
pointsContainerType geo3dPointsContainer;
std::ifstream file(gcpFileName, std::ios::in);
if (file)
{
std::string line;
while (getline(file, line))
{
if (line.find_first_of("#") != 0)
{
std::istringstream iss(line);
iss >> imagePoint[0] >> imagePoint[1] >> geo3dPoint[0] >> geo3dPoint[1] >> geo3dPoint[2];
imagePoint[2] = geo3dPoint[2];
pointsContainer.push_back(imagePoint);
geo3dPointsContainer.push_back(geo3dPoint);
}
}
file.close();
}
// For each CGP
for (pointsContainerType::iterator pointsIt = pointsContainer.begin(), geo3dPointsIt = geo3dPointsContainer.begin() ;
(pointsIt != pointsContainer.end()) && (geo3dPointsIt != geo3dPointsContainer.end()) ;
++pointsIt, ++geo3dPointsIt)
{
// std::cout << "Point: " << *pointsIt << " GeoPoint: " << *geo3dPointsIt << "\n";
// Testing forward transform
geo3dPoint = transformer.ForwardTransform(*pointsIt);
auto forwardPointDistance = geoDistance->Evaluate(geo3dPoint, *geo3dPointsIt);
if (forwardPointDistance > geoTol)
{
std::cerr << "Geo distance between otbGDALRPCTransformer->ForwardTransform and GCP too high :\n"
<< "GCP: " << *geo3dPointsIt << " / computed: " << geo3dPoint << "\n"
<< "dist = " << forwardPointDistance << " (tol = " << geoTol << ")" << std::endl;
success = false;
}
// Testing inverse transform
imagePoint = transformer.InverseTransform(*geo3dPointsIt);
auto inversePointDistance = distance->Evaluate(imagePoint, *pointsIt);
if (inversePointDistance > imgTol)
{
std::cerr << "Distance between otbGDALRPCTransformer->InverseTransform and GCP too high :\n"
<< "GCP: " << *pointsIt << " / computed: " << imagePoint << "\n"
<< "dist = " << inversePointDistance << " (tol = " << imgTol << ")" << std::endl;
success = false;
}
}
if (success)
return EXIT_SUCCESS;
else
return EXIT_FAILURE;
}
| 37.378571 | 144 | 0.688324 | liuxuvip |
2dfd222fd08540f4e2673955c76bf3284e2db9b3 | 636 | cpp | C++ | Data Structure and Algorithms/Dynamic Programming/dp_fib.cpp | Sid200026/Misc-Programs | d50a1689a89d331d2567486a5dd22fb2311a0d87 | [
"MIT"
] | 3 | 2021-05-13T13:36:39.000Z | 2021-09-01T05:33:48.000Z | Data Structure and Algorithms/Dynamic Programming/dp_fib.cpp | rosy2000/Misc-Programs | d50a1689a89d331d2567486a5dd22fb2311a0d87 | [
"MIT"
] | 4 | 2021-10-06T08:46:33.000Z | 2022-02-26T21:19:42.000Z | Data Structure and Algorithms/Dynamic Programming/dp_fib.cpp | rosy2000/Misc-Programs | d50a1689a89d331d2567486a5dd22fb2311a0d87 | [
"MIT"
] | 2 | 2021-09-01T05:33:51.000Z | 2021-09-06T14:39:15.000Z | #include<iostream>
using namespace std;
// int main()
// {
// int n;
// cin>>n;
// int dp[n];
// dp[0] = 0;
// dp[1] = 1;
// for(int i = 2; i<n; i++)
// {
// dp[i] = dp[i-1] + dp[i-2];
// }
// cout<<dp[n-1];
// }
int dp[100];
int fib(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
{
if(dp[n] != -1)
return dp[n];
else
{
dp[n]=fib(n-1)+fib(n-2);
return dp[n];
}
}
}
int main()
{
int n;
cin>>n;
for(int i = 0;i<100;i++)
{
dp[i] = -1;
}
cout<<fib(n-1);
} | 14.790698 | 37 | 0.341195 | Sid200026 |
93046434ae89d0310e0d9f6a5e72487c0425faf4 | 775 | cpp | C++ | packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/utility/system/src/Utility_CylindricalSpatialCoordinateConversionPolicy.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file Utility_CylindricalSpatialCoordinateConversionPolicy.cpp
//! \author Alex Robinson
//! \brief Cylindrical coordinate conversion policy template instantiations
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "FRENSIE_Archives.hpp"
#include "Utility_CylindricalSpatialCoordinateConversionPolicy.hpp"
EXPLICIT_CLASS_SERIALIZE_INST( Utility::CylindricalSpatialCoordinateConversionPolicy );
//---------------------------------------------------------------------------//
// end Utility_CylindricalSpatialCoordinateConversionPolicy.cpp
//---------------------------------------------------------------------------//
| 43.055556 | 87 | 0.492903 | bam241 |
9304e43be421663bdce11be46852fde98a892444 | 1,091 | cpp | C++ | perftest/testlocator.cpp | mashavorob/lfds | 3890472a8a9996ce35d9a28f185df4c2f219a2bd | [
"0BSD"
] | null | null | null | perftest/testlocator.cpp | mashavorob/lfds | 3890472a8a9996ce35d9a28f185df4c2f219a2bd | [
"0BSD"
] | null | null | null | perftest/testlocator.cpp | mashavorob/lfds | 3890472a8a9996ce35d9a28f185df4c2f219a2bd | [
"0BSD"
] | null | null | null | /*
* testlocator.cpp
*
* Created on: Mar 23, 2015
* Author: masha
*/
#include "testlocator.hpp"
#include "performancetest.hpp"
#include "testfactory.hpp"
#include <xtomic/aux/cppbasics.hpp>
#include <stdexcept>
namespace xtomic
{
namespace perftest
{
PerfTestInfo* PerfTestLocator::m_link = nullptr;
PerfTestLocator::PerfTestLocator()
{
}
const PerfTestLocator& PerfTestLocator::getInstance()
{
static const PerfTestLocator instance;
return instance;
}
void PerfTestLocator::registerTest(PerfTestInfo* info)
{
info->m_id = getSize();
info->m_link = m_link;
m_link = info;
}
void PerfTestLocator::getTest(const id_type id, PerformanceTest & test) const
{
test.attach(at(id)->m_factory->create());
}
const PerfTestInfo* PerfTestLocator::at(const id_type id) const
{
if (id >= getSize())
{
throw std::out_of_range("PerfTestLocator::at()");
}
PerfTestInfo* link = m_link;
while (link)
{
if (link->m_id == id)
{
break;
}
link = link->m_link;
}
return link;
}
}
}
| 16.044118 | 77 | 0.64528 | mashavorob |
930763a3ca783d7a8ce194e6a11554f0f9f549f4 | 1,860 | cc | C++ | piksi_multi_cpp/src/receiver/receiver_ros.cc | fm-uulm/ethz_piksi_ros | a228dc3bfb29266897c2bb38bdfb098ac475ffa0 | [
"BSD-3-Clause"
] | 65 | 2018-01-03T21:58:56.000Z | 2022-03-09T22:02:33.000Z | piksi_multi_cpp/src/receiver/receiver_ros.cc | fm-uulm/ethz_piksi_ros | a228dc3bfb29266897c2bb38bdfb098ac475ffa0 | [
"BSD-3-Clause"
] | 138 | 2017-11-30T15:46:26.000Z | 2022-02-22T06:57:53.000Z | piksi_multi_cpp/src/receiver/receiver_ros.cc | fm-uulm/ethz_piksi_ros | a228dc3bfb29266897c2bb38bdfb098ac475ffa0 | [
"BSD-3-Clause"
] | 86 | 2017-12-06T19:32:55.000Z | 2022-03-29T17:57:26.000Z | #include "piksi_multi_cpp/receiver/receiver_ros.h"
#include <piksi_multi_cpp/sbp_callback_handler/sbp_callback_handler_factory.h>
// SBP message definitions.
#include <piksi_multi_cpp/observations/file_observation_logger.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include "piksi_multi_cpp/sbp_callback_handler/position_sampler.h"
#include "piksi_multi_cpp/sbp_callback_handler/ros_time_handler.h"
namespace piksi_multi_cpp {
ReceiverRos::ReceiverRos(const ros::NodeHandle& nh, const Device::Ptr& device)
: SettingsIo(device), nh_(nh) {
// Register all relay callbacks.
// Handle (GPS) time stamping.
auto ros_time_handler = std::make_shared<RosTimeHandler>(state_);
geotf_handler_ = std::make_shared<GeoTfHandler>(nh, state_);
sbp_relays_ =
SBPCallbackHandlerFactory::createAllSBPMessageRelays(nh, state_);
ros_relays_ = SBPCallbackHandlerFactory::createAllRosMessageRelays(
nh, state_, ros_time_handler, geotf_handler_);
position_sampler_ = std::make_shared<PositionSampler>(
nh, state_, ros_time_handler, geotf_handler_);
// Create observation callbacks
obs_cbs_ = std::make_unique<SBPObservationCallbackHandler>(nh, state_);
if (1) {
auto logger = std::make_shared<FileObservationLogger>();
/*ROS_WARN_STREAM(logger->open("/tmp/tempfile.sbp"));
obs_cbs_->addObservationCallbackListener(
CBtoRawObsConverter::createFor(logger));*/
}
}
std::vector<std::string> ReceiverRos::getVectorParam(
const std::string& name, const std::string& default_value) {
auto string_value = nh_.param<std::string>(name, default_value);
if (string_value.length() == 0) return {};
std::vector<std::string> vector_value;
boost::algorithm::split(vector_value, string_value, boost::is_any_of(";"));
return vector_value;
}
} // namespace piksi_multi_cpp
| 37.959184 | 78 | 0.763978 | fm-uulm |
93076ebed2da5f10879ce444c000c80e472b2f75 | 4,918 | cpp | C++ | service/src/sys/autorun2.cpp | BOBBYWY/exodusdb | cfe8a3452480af90071dd10cefeed58299eed4e7 | [
"MIT"
] | null | null | null | service/src/sys/autorun2.cpp | BOBBYWY/exodusdb | cfe8a3452480af90071dd10cefeed58299eed4e7 | [
"MIT"
] | null | null | null | service/src/sys/autorun2.cpp | BOBBYWY/exodusdb | cfe8a3452480af90071dd10cefeed58299eed4e7 | [
"MIT"
] | null | null | null | #include <exodus/library.h>
libraryinit()
#include <getsubs.h>
#include <sys_common.h>
var mode;
var datax;
var runasusercode;
var targetusercodes;
var title;
var usern;//num
function main(in mode0, in title0, in module, in request, in data0, in runasusercode0, in targetusercodes0, io document0, io docid, out msg) {
//c sys in,in,in,in,in,in,in,io,io,out
//creates an autorun record in documents
//GBP CREATEALERT mode WRITE
//GBP GENERAL.SUBS2 mode ASAP
//BP MEDIADIARY mode WRITE/ASP for media diary
//ABP none
#include <system_common.h>
//default unassigned parameters
if (mode0.unassigned()) {
mode = "";
} else {
mode = mode0;
}
if (data0.unassigned()) {
datax = "";
} else {
datax = data0;
}
if (runasusercode0.unassigned()) {
runasusercode = "";
} else {
runasusercode = runasusercode0;
}
if (targetusercodes0.unassigned()) {
targetusercodes = "";
} else {
targetusercodes = targetusercodes0;
}
if (document0.unassigned()) {
sys.document = "";
} else {
sys.document = document0;
}
if (docid.unassigned()) {
docid = "";
}
if (title0) {
title = title0;
} else {
title = sys.document.a(1);
}
//default runtime to once
if (not(sys.document.field(FM, 20, 10).convert(FM, ""))) {
//run once now
sys.document(27) = 1;
}
var fullrequest = module ^ "PROXY" ^ FM ^ request;
//get target usercodes
var users;
if (not(users.open("USERS", ""))) {
msg = "USERS file is missing";
return 0;
}
//determine the runas usercode if not specified
if (not runasusercode) {
//allow for runuser to be passed in document
runasusercode = sys.document.a(1);
}
if (runasusercode) {
var runasuser;
if (not(runasuser.read(users, runasusercode))) {
if (not(runasusercode eq "EXODUS")) {
msg = runasusercode.quote() ^ " user doesnt exist";
return 0;
}
runasuser = "";
}
} else {
//run as the bottom user in the current users group
//assuming we are going to send it to all members of the group
var usercode = USERNAME;
runasusercode = usercode.xlate("USERS", 5, "");
//if not a proper user (eg EXODUS then skip)
if (not runasusercode) {
msg = usercode.quote() ^ " can only autorun if specified as the runas user";
return 0;
}
}
//if no targets specified then
//send to the "run as" user and all users above in the same group
if (targetusercodes eq "") {
//allow for targetusers to be passed in document
targetusercodes = sys.document.a(14);
//runasuser is NOT a target unless there are no recipients
//if targetusercodes='' then
// targetusercodes=runasusercode
// end
}
//auto targeting
var initialtargetusercodes = targetusercodes;
if (targetusercodes eq "{GROUP}") {
var tt = runasusercode;
if (SECURITY.a(1).locate(tt, usern)) {
while (true) {
var userx;
if (userx.read(users, tt)) {
//only to users with emails
if (userx.a(7)) {
var seniorfirst = 1;
if (seniorfirst) {
targetusercodes.inserter(1, 1, tt);
} else {
targetusercodes(1, -1) = tt;
}
}
}
usern -= 1;
tt = SECURITY.a(1, usern);
///BREAK;
if (not((usern and tt) and tt ne "---")) break;
}//loop;
}
} else {
//check all users exist (even if they dont have emails)
if (targetusercodes) {
var nusers = targetusercodes.count(VM) + 1;
for (usern = nusers; usern >= 1; --usern) {
var usercode = targetusercodes.a(1, usern);
var userx;
if (not(userx.read(users, usercode))) {
if (not(usercode eq "EXODUS")) {
msg = usercode.quote() ^ " user doesnt exist";
return 0;
}
userx = "";
}
} //usern;
}
}
//if no targets have emails then skip
if (initialtargetusercodes and targetusercodes eq "") {
msg = "No target users have email addresses";
return 0;
}
//got all data, prepare autorun document
sys.document(2) = title;
sys.document(5) = lower(fullrequest);
sys.document(6) = lower(datax);
sys.document(1) = runasusercode;
sys.document(14) = targetusercodes;
sys.document(7) = APPLICATION;
sys.document(3) = var().date();
sys.document(4) = var().time();
if (sys.document.a(12) eq "") {
sys.document(12) = 1;
}
//email delivery - save if report successful or not run
if (docid) {
//dont lose last run date/time to avoid rerunning.
//to force rerun delete and recreate
var olddoc;
if (olddoc.read(sys.documents, docid)) {
sys.document(13) = olddoc.a(13);
}
} else {
var saveid = ID;
call getsubs("DEF.DOCUMENT.NO");
docid = ID;
ID = saveid;
if (not docid) {
msg = "Could not get next document number in AUTORUN2|Please try again after 1 minute";
return 0;
}
}
//prevent document from being run until the request has been processed
//relies on unlock all in listen
if (mode eq "ASAP") {
if (not(sys.documents.lock( docid))) {
{}
}
}
sys.document.write(sys.documents, docid);
return 1;
}
libraryexit()
| 22.874419 | 142 | 0.642741 | BOBBYWY |
930b523b2c973ced897591911c935e661ad4b128 | 1,155 | cpp | C++ | console/tetris/DrawBlock.cpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | 4 | 2019-10-17T20:26:09.000Z | 2019-11-14T12:01:57.000Z | console/tetris/DrawBlock.cpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | console/tetris/DrawBlock.cpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | #include "DrawBlock.hpp"
#include "Context.hpp"
#include <cassert>
#include <raylib.h>
namespace Tetris {
void DrawBlock(ShapeType type, int game_level, int x, int y, unsigned char alpha, bool small)
{
// Quick hack to clip drawing blocks above matrix
if (y < 48) {
return;
}
int tile_size_int = small ? TILE_SIZE_SMALL : TILE_SIZE;
if (type == 0) {
// DrawRectangle(x - 1, y, tile_size_int + 1, tile_size_int, BLACK);
return;
}
auto tile_size = static_cast<float>(tile_size_int);
auto tiles = small ? Context::instance().tiles_small : Context::instance().tiles;
int index = static_cast<int>(type) - 1;
assert(index >= 0);
assert(index <= 7);
int level = game_level - 1;
assert(level >= 0);
assert(level <= 9);
Rectangle source {
static_cast<float>(index) * tile_size,
static_cast<float>(level) * tile_size,
tile_size,
tile_size,
};
Vector2 position {
static_cast<float>(x),
static_cast<float>(y),
};
Color color { 255, 255, 255, alpha };
DrawTextureRec(tiles, source, position, color);
}
}
| 22.647059 | 93 | 0.612987 | piotrek-szczygiel |
930ddd26645c88c32a69a90ef7a13aaba10c5e12 | 951 | cpp | C++ | src/client/main.cpp | korolr/DeskX | a0841828f0b37848887531c993c1355bac3a78d3 | [
"Apache-2.0"
] | null | null | null | src/client/main.cpp | korolr/DeskX | a0841828f0b37848887531c993c1355bac3a78d3 | [
"Apache-2.0"
] | null | null | null | src/client/main.cpp | korolr/DeskX | a0841828f0b37848887531c993c1355bac3a78d3 | [
"Apache-2.0"
] | null | null | null |
#include "../../include/Client.h"
int processIsTranslated() {
int ret = 0;
size_t size = sizeof(ret);
if (sysctlbyname("sysctl.proc_translated", &ret, &size, NULL, 0) == -1)
{
if (errno == ENOENT)
return 0;
return -1;
}
return ret;
}
int main(int argc, char *argv[]) {
Global::args = Tools::ArgsRead(argc, argv);
byte request[AUTH_SIZE];
// disable work on apple silicon
if (processIsTranslated() == 1) {
return 1;
}
if (Global::args.ip.empty() || Global::args.port < 1) {
std::cout << man_text << "\n";
return 1;
}
Global::net = new TCP(Global::args.port, Global::args.ip);
assert(Global::net);
switch (*Global::args.cmd.c_str()) {
case 'r':
/**
* Remote control mode
*/
Actions::StartStreaming(request);
break;
case 'e':
/**
* Completion of work
*/
*request = 2;
Global::net->Send(request, AUTH_SIZE);
default: break;
}
delete Global::net;
return 0;
}
| 17.611111 | 75 | 0.59306 | korolr |
930dfb0d9be75eaed422e27eff72f9cc840075e0 | 1,479 | cc | C++ | src/base/resolution.cc | miguelpinho/gem5-thesis | 3a604b7a742dbfd40a1157749c461e8a71911c45 | [
"BSD-3-Clause"
] | 2 | 2021-02-20T21:41:39.000Z | 2021-11-09T14:52:01.000Z | src/base/resolution.cc | miguelpinho/gem5-thesis | 3a604b7a742dbfd40a1157749c461e8a71911c45 | [
"BSD-3-Clause"
] | null | null | null | src/base/resolution.cc | miguelpinho/gem5-thesis | 3a604b7a742dbfd40a1157749c461e8a71911c45 | [
"BSD-3-Clause"
] | null | null | null | /// MPINHO 2-mar-2019 BEGIN ///
#include "base/resolution.hh"
#include "arch/utility.hh"
int
unsignedIntResolution(uint64_t val)
{
if (val == 0) return 0;
int prc = 1; // in findMsbSet they don't have this
if (val >> 32) { val += 32; val = val >> 32; }
if (val >> 16) { prc += 16; val = val >> 16; }
if (val >> 8) { prc += 8; val = val >> 8; }
if (val >> 4) { prc += 4; val = val >> 4; }
if (val >> 2) { prc += 2; val = val >> 2; }
if (val >> 1) { prc++; }
return prc;
}
int
signedIntResolution(uint64_t val)
{
// the precision of a value is equal to its complement's
if (val >> 63) val = ~val;
int prc = 1;
// fast result
if (!val) return prc;
// find the most significative 1 bit and add one
prc++;
if (val >> 32) { prc += 32; val = val >> 32; }
if (val >> 16) { prc += 16; val = val >> 16; }
if (val >> 8) { prc += 8; val = val >> 8; }
if (val >> 4) { prc += 4; val = val >> 4; }
if (val >> 2) { prc += 2; val = val >> 2; }
if (val >> 1) { prc++; }
return prc;
}
/// MPINHO 15-may-2019 BEGIN ///
int
roundPrcBlock(int prc, int block)
{
assert(prc >= 0 && block >= 0);
// Source: https://stackoverflow.com/questions/3407012/
// Make sure block is a power of 2.
assert(block && ((block & (block-1)) == 0));
return (prc + block - 1) & -block;
}
// TODO: implement roundPrcBlockLog function
/// MPINHO 15-may-2019 END ///
/// MPINHO 2-mar-2019 END ///
| 23.109375 | 60 | 0.521298 | miguelpinho |
93101178a438876b9b6f3c3b691a0c2e3c26e612 | 3,101 | cpp | C++ | Aurora/Aurora/timer.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | 8 | 2021-07-19T04:46:35.000Z | 2022-03-12T17:56:00.000Z | Aurora/Aurora/timer.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | Aurora/Aurora/timer.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (C) Manas Kamal Choudhury 2021
*
* timer.h -- The Global Timer used by usermode objects
*
* /PROJECT - Aurora's Xeneva v1.0
* /AUTHOR - Manas Kamal Choudhury
*
*/
#include <timer.h>
#include <_null.h>
#include <pmmngr.h>
#include <stdio.h>
#include <arch\x86_64\cpu.h>
#include <ipc\postbox.h>
timer_t *timer_head = NULL;
timer_t *timer_last = NULL;
uint32_t utimer_id = 0;
void timer_insert (timer_t* new_timer ) {
new_timer->next = NULL;
new_timer->prev = NULL;
if (timer_head == NULL) {
timer_last = new_timer;
timer_head = new_timer;
} else {
timer_last->next = new_timer;
new_timer->prev = timer_last;
}
timer_last = new_timer;
}
void timer_delete (timer_t* new_timer) {
if (timer_head == NULL)
return;
if (new_timer == timer_head) {
timer_head = timer_head->next;
} else {
new_timer->prev->next = new_timer->next;
}
if (new_timer == timer_last) {
timer_last = new_timer->prev;
} else {
new_timer->next->prev = new_timer->prev;
}
pmmngr_free(new_timer);
}
/*
create_timer -- Creates a new timer
@param interval -- the difference time
@param id -- the caller thread id
@return -- a unique id of the timer
*/
int create_timer (uint32_t interval, uint16_t id) {
utimer_id++;
timer_t *t = (timer_t*)pmmngr_alloc();
t->timer_count = 0;
t->task_id = id;
t->interval = interval;
t->utimer_id = utimer_id;
t->start = false;
timer_insert (t);
return utimer_id;
}
/*
pause_timer -- pauses the timer
@param utimer_id -- Unique timer id to pause
*/
void pause_timer (int utimer_id) {
for (timer_t *t = timer_head; t != NULL; t = t->next) {
if (t->utimer_id == utimer_id) {
t->start = false;
break;
}
}
}
/*
start_timer - start the timer
@param utimer_id -- Unique timer id to start
*/
void start_timer (int utimer_id ) {
for (timer_t *t = timer_head; t != NULL; t = t->next) {
if (t->utimer_id == utimer_id) {
t->start = true;
break;
}
}
}
/*
destroy_timer -- Destroy a specific timer
@param utimer_id -- Unique timer id to destroy
*/
void destroy_timer (int utimer_id) {
for (timer_t *t = timer_head; t != NULL; t = t->next) {
if (t->utimer_id == utimer_id) {
timer_delete (t);
utimer_id--;
break;
}
}
}
/*
find_timer_id -- find a timer by a given task id
@param id -- task id
@return -- unique timer id of the timer, if found
*/
int find_timer_id (uint16_t id) {
for (timer_t *t = timer_head; t != NULL; t = t->next) {
if (t->task_id == id) {
return t->utimer_id;
break;
}
}
return -1;
}
/**
timer_fire -- this routine is called by the scheduler
for monitoring time for threads.
*/
void timer_fire () {
x64_cli();
if (timer_head != NULL) {
for (timer_t *t = timer_head; t != NULL; t = t->next) {
if (t->start) {
if (t->timer_count == t->interval ) {
postmsg_t msg;
msg.type = SYSTEM_MESSAGE_TIMER_EVENT;
msg.to_id = t->task_id;
post_box_put_msg (&msg,t->task_id);
t->timer_count = 0;
}
t->timer_count++;
}
}
}
}
| 19.26087 | 57 | 0.62238 | manaskamal |
9311892ac3c1fd2b8a3db6e74e57269792d352f0 | 4,279 | cpp | C++ | src/navmesh_parameters.cpp | TheFamousRat/GodotFlowField | 0da627f73aff1149bd7838cab03b380fb7f34b86 | [
"MIT"
] | 3 | 2021-02-25T18:39:07.000Z | 2022-01-28T16:11:08.000Z | src/navmesh_parameters.cpp | TheFamousRat/GodotFlowField | 0da627f73aff1149bd7838cab03b380fb7f34b86 | [
"MIT"
] | 1 | 2021-04-05T15:42:18.000Z | 2021-04-05T15:42:18.000Z | src/navmesh_parameters.cpp | TheFamousRat/GodotFlowField | 0da627f73aff1149bd7838cab03b380fb7f34b86 | [
"MIT"
] | null | null | null | #include "navmesh_parameters.h"
static const int DEFAULT_TILE_SIZE = 64;
static const float DEFAULT_CELL_SIZE = 0.3f;
static const float DEFAULT_CELL_HEIGHT = 0.2f;
static const float DEFAULT_AGENT_HEIGHT = 2.0f;
static const float DEFAULT_AGENT_RADIUS = 0.6f;
static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
static const int DEFAULT_MAX_OBSTACLES = 1000;
static const int DEFAULT_MAX_LAYERS = 8;
using namespace godot;
void NavmeshParameters::_register_methods()
{
register_property<NavmeshParameters, real_t>("cell_size", &NavmeshParameters::set_cell_size, &NavmeshParameters::get_cell_size, DEFAULT_CELL_SIZE);
register_property<NavmeshParameters, int>("tile_size", &NavmeshParameters::set_tile_size, &NavmeshParameters::get_tile_size, DEFAULT_TILE_SIZE);
register_property<NavmeshParameters, real_t>("cell_height", &NavmeshParameters::set_cell_height, &NavmeshParameters::get_cell_height, DEFAULT_CELL_HEIGHT);
register_property<NavmeshParameters, real_t>("agent_height", &NavmeshParameters::set_agent_height, &NavmeshParameters::get_agent_height, DEFAULT_AGENT_HEIGHT);
register_property<NavmeshParameters, real_t>("agent_radius", &NavmeshParameters::set_agent_radius, &NavmeshParameters::get_agent_radius, DEFAULT_AGENT_RADIUS);
register_property<NavmeshParameters, real_t>("agent_max_climb", &NavmeshParameters::set_agent_max_climb, &NavmeshParameters::get_agent_max_climb, DEFAULT_AGENT_MAX_CLIMB);
register_property<NavmeshParameters, real_t>("agent_max_slope", &NavmeshParameters::set_agent_max_slope, &NavmeshParameters::get_agent_max_slope, DEFAULT_AGENT_MAX_SLOPE);
register_property<NavmeshParameters, real_t>("region_min_size", &NavmeshParameters::set_region_min_size, &NavmeshParameters::get_region_min_size, DEFAULT_REGION_MIN_SIZE);
register_property<NavmeshParameters, real_t>("region_merge_size", &NavmeshParameters::set_region_merge_size, &NavmeshParameters::get_region_merge_size, DEFAULT_REGION_MERGE_SIZE);
register_property<NavmeshParameters, real_t>("edge_max_length", &NavmeshParameters::set_edge_max_length, &NavmeshParameters::get_edge_max_length, DEFAULT_EDGE_MAX_LENGTH);
register_property<NavmeshParameters, real_t>("edge_max_error", &NavmeshParameters::set_edge_max_error, &NavmeshParameters::get_edge_max_error, DEFAULT_EDGE_MAX_ERROR);
register_property<NavmeshParameters, real_t>("detail_sample_distance", &NavmeshParameters::set_detail_sample_distance, &NavmeshParameters::get_detail_sample_distance, DEFAULT_DETAIL_SAMPLE_DISTANCE);
register_property<NavmeshParameters, real_t>("detail_sample_max_error", &NavmeshParameters::set_detail_sample_max_error, &NavmeshParameters::get_detail_sample_max_error, DEFAULT_DETAIL_SAMPLE_MAX_ERROR);
// register_property<NavmeshParameters, Vector3>("padding", &NavmeshParameters::set_padding, &NavmeshParameters::get_padding, Vector3(1.0f, 1.0f, 1.0f));
register_property<NavmeshParameters, int>("max_layers", &NavmeshParameters::set_max_layers, &NavmeshParameters::get_max_layers, DEFAULT_MAX_LAYERS);
}
NavmeshParameters::NavmeshParameters()
{
}
void NavmeshParameters::_init()
{
if (OS::get_singleton()->is_stdout_verbose())
{
Godot::print("Navigation parameters inited.");
}
tile_size = DEFAULT_TILE_SIZE;
cell_size = DEFAULT_CELL_SIZE;
cell_height = DEFAULT_CELL_HEIGHT;
agent_height = DEFAULT_AGENT_HEIGHT;
agent_radius = DEFAULT_AGENT_RADIUS;
agent_max_climb = DEFAULT_AGENT_MAX_CLIMB;
agent_max_slope = DEFAULT_AGENT_MAX_SLOPE;
region_min_size = DEFAULT_REGION_MIN_SIZE;
region_merge_size = DEFAULT_REGION_MERGE_SIZE;
edge_max_length = DEFAULT_EDGE_MAX_LENGTH;
edge_max_error = DEFAULT_EDGE_MAX_ERROR;
detail_sample_distance = DEFAULT_DETAIL_SAMPLE_DISTANCE;
detail_sample_max_error = DEFAULT_DETAIL_SAMPLE_MAX_ERROR;
padding = Vector3(1.f, 1.f, 1.f);
max_layers = DEFAULT_MAX_LAYERS;
}
void NavmeshParameters::_ready()
{
}
NavmeshParameters::~NavmeshParameters()
{
} | 52.82716 | 204 | 0.838046 | TheFamousRat |
93124e5242aaec99a07bd9cad0ba8d70d8e84fe9 | 4,808 | cc | C++ | tagging_tools/entity_binding.cc | nickroess/hope-policy-engine | 3c8686b41dd933985c1eead593754c14d9a8728d | [
"MIT"
] | 1 | 2021-05-02T07:09:40.000Z | 2021-05-02T07:09:40.000Z | tagging_tools/entity_binding.cc | nickroess/hope-policy-engine | 3c8686b41dd933985c1eead593754c14d9a8728d | [
"MIT"
] | 13 | 2019-07-01T14:49:16.000Z | 2020-08-04T15:24:05.000Z | tagging_tools/entity_binding.cc | nickroess/hope-policy-engine | 3c8686b41dd933985c1eead593754c14d9a8728d | [
"MIT"
] | 3 | 2019-06-18T17:09:12.000Z | 2021-05-02T07:09:42.000Z | /*
* Copyright © 2017-2018 Dover Microsystems, Inc.
* All rights reserved.
*
* Use and disclosure subject to the following license.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <yaml-cpp/yaml.h>
#include "validator_exception.h"
#include "entity_binding.h"
using namespace policy_engine;
static void expect_field(YAML::Node const *n, const char *field, std::string entity_name) {
if (!(*n)[field])
throw configuration_exception_t("expected field " + std::string(field) + " in entity " + entity_name);
}
static void process_element(const YAML::Node &n,
std::list<std::unique_ptr<entity_binding_t>> &bindings) {
std::string elt_path;
if (!n["name"])
throw configuration_exception_t("binding must have an entity name");
std::string entity_name = n["name"].as<std::string>();
expect_field(&n, "kind", entity_name);
std::string element_name = n["kind"].as<std::string>();
if (element_name == "symbol") {
entity_symbol_binding_t *binding = new entity_symbol_binding_t;
std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding);
binding->entity_name = entity_name;
expect_field(&n, "elf_name", entity_name);
binding->elf_name = n["elf_name"].as<std::string>();
if (n["tag_all"])
binding->is_singularity = !n["tag_all"].as<bool>();
if (n["optional"])
binding->optional = n["optional"].as<bool>();
bindings.push_back(std::move(u));
} else if (element_name == "range") {
entity_range_binding_t *binding = new entity_range_binding_t;
std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding);
binding->entity_name = entity_name;
expect_field(&n, "elf_start", entity_name);
expect_field(&n, "elf_end", entity_name);
binding->elf_start_name = n["elf_start"].as<std::string>();
binding->elf_end_name = n["elf_end"].as<std::string>();
if (n["optional"])
binding->optional = n["optional"].as<bool>();
bindings.push_back(std::move(u));
} else if (element_name == "soc") {
entity_soc_binding_t *binding = new entity_soc_binding_t;
std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding);
binding->entity_name = entity_name;
if (n["optional"])
binding->optional = n["optional"].as<bool>();
bindings.push_back(std::move(u));
} else if (element_name == "isa") {
entity_isa_binding_t *binding = new entity_isa_binding_t;
std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding);
binding->entity_name = entity_name;
if (n["optional"])
binding->optional = n["optional"].as<bool>();
bindings.push_back(std::move(u));
} else if (element_name == "image") {
entity_image_binding_t *binding = new entity_image_binding_t;
std::unique_ptr<entity_binding_t> u = std::unique_ptr<entity_binding_t>(binding);
binding->entity_name = entity_name;
if (n["optional"])
binding->optional = n["optional"].as<bool>();
bindings.push_back(std::move(u));
} else {
throw configuration_exception_t("unexpected kind " + element_name);
}
}
void policy_engine::load_entity_bindings(const char *file_name,
std::list<std::unique_ptr<entity_binding_t>> &bindings,
reporter_t *err) {
try {
YAML::Node n = YAML::LoadFile(file_name);
// if (n["entities"]) {
// YAML::Node soc = n["entities"];
// for (YAML::const_iterator it = soc.begin(); it != soc.end(); ++it) {
for (YAML::const_iterator it = n.begin(); it != n.end(); ++it) {
process_element(*it, bindings);
}
} catch (std::exception &e) {
err->error("while parsing %s: %s\n", file_name, e.what());
}
// } else {
// throw configuration_exception_t("Expected a root 'entities' node");
// }
}
| 41.448276 | 106 | 0.691348 | nickroess |
931864a852a0a1633c69d6bcf21831da5265257a | 1,308 | cpp | C++ | cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp | anstaf/arbsimd | c4ba87b02b26a47ef33d0a3eba78a4f330c88073 | [
"BSD-3-Clause"
] | null | null | null | cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp | anstaf/arbsimd | c4ba87b02b26a47ef33d0a3eba78a4f330c88073 | [
"BSD-3-Clause"
] | null | null | null | cmake-build-debug/test/unit/mechanisms/test0_kin_conserve_gpu.cpp | anstaf/arbsimd | c4ba87b02b26a47ef33d0a3eba78a4f330c88073 | [
"BSD-3-Clause"
] | null | null | null | #include <arbor/mechanism_abi.h>
#include <cmath>
namespace testing {
void mechanism_test0_kin_conserve_gpu_init_(arb_mechanism_ppack*);
void mechanism_test0_kin_conserve_gpu_advance_state_(arb_mechanism_ppack*);
void mechanism_test0_kin_conserve_gpu_compute_currents_(arb_mechanism_ppack*);
void mechanism_test0_kin_conserve_gpu_write_ions_(arb_mechanism_ppack*);
void mechanism_test0_kin_conserve_gpu_apply_events_(arb_mechanism_ppack*, arb_deliverable_event_stream*);
void mechanism_test0_kin_conserve_gpu_post_event_(arb_mechanism_ppack*);
} // namespace testing
extern "C" {
arb_mechanism_interface* make_testing_test0_kin_conserve_interface_gpu() {
static arb_mechanism_interface result;
result.backend=arb_backend_kind_gpu;
result.partition_width=1;
result.alignment=1;
result.init_mechanism=testing::mechanism_test0_kin_conserve_gpu_init_;
result.compute_currents=testing::mechanism_test0_kin_conserve_gpu_compute_currents_;
result.apply_events=testing::mechanism_test0_kin_conserve_gpu_apply_events_;
result.advance_state=testing::mechanism_test0_kin_conserve_gpu_advance_state_;
result.write_ions=testing::mechanism_test0_kin_conserve_gpu_write_ions_;
result.post_event=testing::mechanism_test0_kin_conserve_gpu_post_event_;
return &result;
}
};
| 43.6 | 105 | 0.856269 | anstaf |
7933dc15b6801eb0fb6326bfd120ff6d021f9338 | 9,118 | cpp | C++ | Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | 2 | 2015-04-16T01:05:53.000Z | 2019-08-26T07:38:43.000Z | Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | null | null | null | Sources/Modules/Renderer/SM2/OcclusionMapGenerator.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* 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 holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <Core/Logger.h>
#include <Core/TGA.h>
#include <Renderer/Common/Tools.h>
#include <Renderer/Common/Texture.h>
#include <Renderer/Common/Camera.h>
#include <Renderer/SM2/OcclusionMapGenerator.h>
#include <Renderer/SM2/SceneSM2.h>
namespace Renderer
{
//-----------------------------------------------------------------------------
OcclusionMapGenerator::OcclusionMapGenerator(const Ptr<Gfx::IDevice> & pDevice, const Ptr<ShaderLib> & pShaderLib, const Ptr<PackedVerticesFormat> & pFormat, const Ptr<ScreenQuad> & pScreenQuad) :
_pDevice(pDevice),
_pShaderLib(pShaderLib),
_pFormat(pFormat),
_pScreenQuad(pScreenQuad)
{
}
//-----------------------------------------------------------------------------
bool OcclusionMapGenerator::initialise()
{
bool result = true;
try
{
// Pixel shaders - Generate texcoords
{
Core::List<Gfx::ShaderMacro> macros;
if(_pFormat->packedNormals())
macros.push_back(Gfx::ShaderMacro(L"PACKED_NORMAL_FLAG", L"1"));
_pVShaderGen = _pShaderLib->getVShader(L"generate-occlusionmap.vsh", Gfx::VS_V3_0, L"vs_main", macros);
_pPShaderGen = _pShaderLib->getPShader(L"generate-occlusionmap.psh", Gfx::PS_V3_0, L"ps_main", macros);
_idTextureSizeGen = _pVShaderGen->getConstantTable()->getConstantIndex(L"TextureSize");
_idIsTextureBorderOnGen = _pVShaderGen->getConstantTable()->getConstantIndex(L"IsTextureBorderOn");
Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID);
Gfx::RSDepthStencilDesc depth(false, false, Gfx::COMPARISON_LESS_EQUAL);
Gfx::RSBlendDesc blend;
_stateGen = _pDevice->createState(raster, depth, blend);
_pFormatGen = _pFormat->getVertexFormat(_pDevice, _pVShaderGen, VD_SKIN_G_B);
}
// Pixel shaders - Build mipmaps
{
Core::List<Gfx::ShaderMacro> macros;
_pPShaderMip = _pShaderLib->getPShader(L"build-mipmap.psh", Gfx::PS_V3_0, L"ps_main", macros);
_idSourceSizeMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"SourceSize");
_idSamplerImageMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"SamplerImage");
_idIsAlphaWeightedMip = _pPShaderMip->getConstantTable()->getConstantIndex(L"IsAlphaWeighted");
Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID);
Gfx::RSDepthStencilDesc depth(false, false, Gfx::COMPARISON_LESS_EQUAL);
Gfx::RSBlendDesc blend;
_stateMip = _pDevice->createState(raster, depth, blend);
}
}
catch(Core::Exception & exception)
{
ERR << L"Error initializing Occlusion generator : " << exception.getMessage() << L"\n";
ERR << exception.getCallStack();
result = false;
}
return result;
}
//-----------------------------------------------------------------------------
Ptr<Core::Bitmap> OcclusionMapGenerator::generateOcclusionMap(const OcclusionMapInfos & om, const Ptr<Assets::VerticeSet> & pVSet)
{
Ptr<IPackedSkinnedVertices> pPackedVertices = _pFormat->packSkinnedVerts(_pDevice, pVSet);
// Surfaces
int32 sizeMul = (om.internalTextureBorder || !om.superSampleUV) ? 1 : std::max(1, std::min(2048 / om.width, 2048 / om.height));
int32 srcWidth = sizeMul * om.width;
int32 srcHeight = sizeMul * om.height;
Gfx::Texture2DDesc texDesc;
texDesc.width = srcWidth;
texDesc.height = srcHeight;
texDesc.mipLevels = 1;
texDesc.format = Gfx::TF_A8R8G8B8;
texDesc.usage = Gfx::BUFFER_USAGE_DEFAULT;
texDesc.cpuAccess = Gfx::BCA_NO_ACCESS;
texDesc.bind = Gfx::TB_RENDER_TARGET;
texDesc.autoGenMipmap = false;
Gfx::RenderTargetViewDesc rtDesc;
rtDesc.texture2D.mipSlice = 0;
Ptr<Gfx::ITexture2D> pTexOcclusion = _pDevice->createTexture2D(texDesc);
Ptr<Gfx::IRenderTargetView> pViewOcclusion = _pDevice->createRenderTargetView(pTexOcclusion, rtDesc);
_pDevice->beginDraw();
_pDevice->setState(_stateGen);
_pDevice->setVertexFormat(_pFormatGen);
_pDevice->setVertexShader(_pVShaderGen);
_pDevice->setPixelShader(_pPShaderGen);
_pVShaderGen->getConstantTable()->setConstant(_idTextureSizeGen, Core::Vector2f(float(srcWidth), float(srcHeight)));
_pVShaderGen->getConstantTable()->setConstant(_idIsTextureBorderOnGen, om.internalTextureBorder);
Gfx::IRenderTargetViewPtr targets[2];
_pDevice->setRenderTarget(pViewOcclusion, null);
_pDevice->clearCurrentRenderTargetView(Core::Vector4f(1.0f, 1.0f, 1.0f, 0.0f), 0.0f, 0, Gfx::CLEAR_COLOR_BUFFER);
pPackedVertices->bindData(_pDevice, VD_SKIN_G_B);
pPackedVertices->sendData(_pDevice, VD_SKIN_G_B, 0);
targets[0] = null;
targets[1] = null;
resize(pTexOcclusion, pViewOcclusion, srcWidth, srcHeight, om.width, om.height);
Ptr<Core::Bitmap> pBitmapOcclusion = _pDevice->toBitmap(pViewOcclusion);
_pDevice->endDraw();
pViewOcclusion = null;
for(int32 ii=0; ii < 4; ii++)
pBitmapOcclusion = borderDiffuse(pBitmapOcclusion);
return pBitmapOcclusion;
}
//-----------------------------------------------------------------------------
void OcclusionMapGenerator::resize(Ptr<Gfx::ITexture2D> & pTex, Ptr<Gfx::IRenderTargetView> & pView, int32 srcWidth, int32 srcHeight, int32 dstWidth, int32 dstHeight)
{
if(srcWidth == dstWidth && srcHeight == dstHeight)
return;
int32 halfWidth = std::max(dstWidth, srcWidth / 2);
int32 halfHeight = std::max(dstHeight, srcHeight / 2);
Gfx::Texture2DDesc texDesc;
texDesc.width = halfWidth;
texDesc.height = halfHeight;
texDesc.mipLevels = 1;
texDesc.format = Gfx::TF_A8R8G8B8;
texDesc.usage = Gfx::BUFFER_USAGE_DEFAULT;
texDesc.cpuAccess = Gfx::BCA_NO_ACCESS;
texDesc.bind = Gfx::TB_RENDER_TARGET;
texDesc.autoGenMipmap = false;
Gfx::RenderTargetViewDesc rtDesc;
rtDesc.texture2D.mipSlice = 0;
Ptr<Gfx::ITexture2D> pTexHalf = _pDevice->createTexture2D(texDesc);
Ptr<Gfx::IRenderTargetView> pViewHalf = _pDevice->createRenderTargetView(pTexHalf, rtDesc);
_pDevice->setState(_stateMip);
_pDevice->setPixelShader(_pPShaderMip);
_pPShaderMip->getConstantTable()->setConstant(_idSourceSizeMip, Core::Vector2f(float(srcWidth), float(srcHeight)));
_pPShaderMip->getConstantTable()->setConstant(_idIsAlphaWeightedMip, true);
_pPShaderMip->getConstantTable()->setSampler2D(_idSamplerImageMip, pTex->getShaderResourceView());
_pDevice->setRenderTarget(pViewHalf, null);
_pDevice->clearCurrentRenderTargetView(Core::Vector4f(0.0f, 0.0f, 0.0f, 0.0f), 0.0f, 0, Gfx::CLEAR_COLOR_BUFFER);
_pScreenQuad->send(halfWidth, halfHeight);
if(halfWidth != dstWidth || halfHeight != dstHeight)
{
resize(pTexHalf, pViewHalf, halfWidth, halfHeight, dstWidth, dstHeight);
}
std::swap(pTex, pTexHalf);
std::swap(pView, pViewHalf);
_pDevice->setRenderTarget(pView, null);
_pPShaderMip->getConstantTable()->setSampler2D(_idSamplerImageMip, null);
pViewHalf = null;
pTexHalf = null;
}
//-----------------------------------------------------------------------------
}
| 42.212963 | 197 | 0.665826 | benkaraban |
793bc66b628a68a4da50a33889a08ba4127e8612 | 43 | hpp | C++ | tests/headers/only_bitfields.hpp | dustlang/rust-bindgen | 62caa5eeba843b88eb4248d313d1fb90db878dae | [
"BSD-3-Clause"
] | 1,848 | 2018-11-22T06:08:21.000Z | 2022-03-31T10:54:10.000Z | tests/headers/only_bitfields.hpp | dustlang/rust-bindgen | 62caa5eeba843b88eb4248d313d1fb90db878dae | [
"BSD-3-Clause"
] | 845 | 2016-06-22T21:55:20.000Z | 2018-10-31T15:50:10.000Z | tests/headers/only_bitfields.hpp | dustlang/rust-bindgen | 62caa5eeba843b88eb4248d313d1fb90db878dae | [
"BSD-3-Clause"
] | 274 | 2018-11-23T17:46:29.000Z | 2022-03-27T04:52:37.000Z | class C {
bool a: 1;
bool b: 7;
};
| 8.6 | 14 | 0.418605 | dustlang |
793e9d490330920025aca555b4bc7cc7bcf440a4 | 1,424 | cpp | C++ | Source/LogiLed/Private/LogiLedModule.cpp | ue4plugins/LogitechLed | 6347c14d2b785b5a4d7636998ab0c99bc8a5b166 | [
"BSD-3-Clause"
] | null | null | null | Source/LogiLed/Private/LogiLedModule.cpp | ue4plugins/LogitechLed | 6347c14d2b785b5a4d7636998ab0c99bc8a5b166 | [
"BSD-3-Clause"
] | null | null | null | Source/LogiLed/Private/LogiLedModule.cpp | ue4plugins/LogitechLed | 6347c14d2b785b5a4d7636998ab0c99bc8a5b166 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "LogiLedPrivate.h"
#include "Modules/ModuleInterface.h"
#include "Modules/ModuleManager.h"
#include "LogitechLEDLib.h"
DEFINE_LOG_CATEGORY(LogLogiLed);
#define LOCTEXT_NAMESPACE "FLogiLedModule"
/**
* Implements the LogiLed module.
*/
class FLogiLedModule
: public IModuleInterface
{
public:
/** Default constructor. */
FLogiLedModule()
: Initialized(false)
{ }
public:
//~ IModuleInterface interface
virtual void StartupModule() override
{
#if LOGILED_SUPPORTED_PLATFORM
// initialize Logitech SDK
if (!::LogiLedInit())
{
UE_LOG(LogLogiLed, Error, TEXT("Failed to initialize Logitech LED SDK"));
return;
}
#else
return;
#endif //LOGILED_SUPPORTED_PLATFORM
int Major, Minor, Build;
if (::LogiLedGetSdkVersion(&Major, &Minor, &Build))
{
UE_LOG(LogLogiLed, Log, TEXT("Initialized Logitech LED SDK %i.%i.%i."), Major, Minor, Build);
}
else
{
UE_LOG(LogLogiLed, Log, TEXT("Initialized Logitech LED SDK (unknown version)"));
}
Initialized = true;
}
virtual void ShutdownModule() override
{
if (!Initialized)
{
return;
}
#if LOGILED_SUPPORTED_PLATFORM
// shut down SDK
::LogiLedShutdown();
#endif
Initialized = false;
}
private:
/** Whether the module has been initialized. */
bool Initialized;
};
IMPLEMENT_MODULE(FLogiLedModule, LogiLed);
#undef LOCTEXT_NAMESPACE
| 16.55814 | 96 | 0.707865 | ue4plugins |
794349e6afc59dff7efd2a109daa192786bd1679 | 439 | cpp | C++ | raygame/SteeringBehaviour.cpp | lodisperkins/AI2021---Graph-Framework | 84c5f5d733c27b1ea144b90ca66bce276586cd63 | [
"MIT"
] | null | null | null | raygame/SteeringBehaviour.cpp | lodisperkins/AI2021---Graph-Framework | 84c5f5d733c27b1ea144b90ca66bce276586cd63 | [
"MIT"
] | null | null | null | raygame/SteeringBehaviour.cpp | lodisperkins/AI2021---Graph-Framework | 84c5f5d733c27b1ea144b90ca66bce276586cd63 | [
"MIT"
] | null | null | null | #include "SteeringBehaviour.h"
SteeringBehaviour::SteeringBehaviour()
{
}
SteeringBehaviour::SteeringBehaviour(SteeringForce * steeringForce)
{
steeringForceObject = steeringForce;
}
SteeringBehaviour::~SteeringBehaviour()
{
}
void SteeringBehaviour::execute(Agent* agent)
{
force = steeringForceObject->GetForce(agent);
}
void SteeringBehaviour::update(Agent * agent, float deltatime)
{
execute(agent);
agent->AddForce(force);
}
| 16.884615 | 67 | 0.776765 | lodisperkins |
7945a84d9a2c62378e2471d1edfb16dfbf3fdc95 | 819 | cpp | C++ | cpp1st/week07/byongmin/01.constexpr.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 2 | 2022-03-10T10:18:23.000Z | 2022-03-16T15:37:22.000Z | cpp1st/week07/byongmin/01.constexpr.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 8 | 2022-03-09T16:14:47.000Z | 2022-03-28T15:35:17.000Z | cpp1st/week07/byongmin/01.constexpr.cpp | th4inquiry/PentaDevs | aa379d24494a485ad5e7fdcc385c6ccfb02cf307 | [
"Apache-2.0"
] | 4 | 2022-03-08T00:22:29.000Z | 2022-03-12T13:22:43.000Z | #include <iostream>
using namespace std;
class RectConst
{
public:
constexpr RectConst(size_t width, size_t height)
: myWidth(width), myHeight(height)
{
}
constexpr size_t getArea() const
{
return myWidth * myHeight;
}
private:
int myWidth;
int myHeight;
};
class Rect
{
public:
Rect(size_t width, size_t height)
: myWidth(width), myHeight(height)
{
}
size_t getArea() const
{
return myWidth * myHeight;
}
private:
int myWidth;
int myHeight;
};
int main()
{
RectConst rectConst{8, 2};
int array[rectConst.getArea()];
cout << "getArea = " << rectConst.getArea() << endl;
Rect rect{8, 2};
//int array[rect.getArea()]; // Error. conflicting declaration 'int array [<anonymous>]'
return 0;
} | 15.75 | 93 | 0.600733 | th4inquiry |
794644b59e611b3ea604cb28a42867f1adedef12 | 1,393 | cpp | C++ | Source/modules/serviceworkers/ServiceWorkerClient.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | 2 | 2016-05-19T10:37:25.000Z | 2019-09-18T04:37:14.000Z | Source/modules/serviceworkers/ServiceWorkerClient.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | null | null | null | Source/modules/serviceworkers/ServiceWorkerClient.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | 7 | 2015-09-23T09:56:29.000Z | 2022-01-20T10:36:06.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "modules/serviceworkers/ServiceWorkerClient.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/SerializedScriptValue.h"
#include "modules/serviceworkers/ServiceWorkerGlobalScopeClient.h"
#include "public/platform/WebString.h"
#include "wtf/RefPtr.h"
namespace blink {
ServiceWorkerClient* ServiceWorkerClient::create(unsigned id)
{
return new ServiceWorkerClient(id);
}
ServiceWorkerClient::ServiceWorkerClient(unsigned id)
: m_id(id)
{
}
void ServiceWorkerClient::postMessage(ExecutionContext* context, PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
// Disentangle the port in preparation for sending it to the remote context.
OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
if (exceptionState.hadException())
return;
WebString messageString = message->toWireString();
OwnPtr<WebMessagePortChannelArray> webChannels = MessagePort::toWebMessagePortChannelArray(channels.release());
ServiceWorkerGlobalScopeClient::from(context)->postMessageToClient(m_id, messageString, webChannels.release());
}
} // namespace blink
| 35.717949 | 170 | 0.788945 | Fusion-Rom |
794a1568ac8c9fa554b21ebbbf04ecf8e77adaec | 25,708 | cpp | C++ | fhq-jury-ad/src/core/light_http_server.cpp | SibirCTF/2019-jury-system | bbd09c36b325ba1b616abfeca147ca1d113a2e97 | [
"MIT"
] | null | null | null | fhq-jury-ad/src/core/light_http_server.cpp | SibirCTF/2019-jury-system | bbd09c36b325ba1b616abfeca147ca1d113a2e97 | [
"MIT"
] | null | null | null | fhq-jury-ad/src/core/light_http_server.cpp | SibirCTF/2019-jury-system | bbd09c36b325ba1b616abfeca147ca1d113a2e97 | [
"MIT"
] | null | null | null | #include "light_http_server.h"
#include <utils_logger.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <sys/stat.h>
#include <sys/time.h>
#include <fstream>
#include <regex> // regex, sregex_token_iterator
#include <stdio.h>
#include <math.h>
#include <thread>
#include <algorithm>
#include <fs.h>
#include <ts.h>
#include <fallen.h>
// ----------------------------------------------------------------------
// LightHttpResponse
// enum for http responses
std::map<int, std::string> *LightHttpResponse::g_mapReponseDescription = nullptr;
// deprecated
std::string LightHttpResponse::RESP_OK = "HTTP/1.1 200 OK";
std::string LightHttpResponse::RESP_BAD_REQUEST = "HTTP/1.1 400 Bad Request";
std::string LightHttpResponse::RESP_FORBIDDEN = "HTTP/1.1 403 Forbidden";
std::string LightHttpResponse::RESP_NOT_FOUND = "HTTP/1.1 404 Not Found";
std::string LightHttpResponse::RESP_PAYLOAD_TOO_LARGE = "HTTP/1.1 413 Payload Too Large";
std::string LightHttpResponse::RESP_INTERNAL_SERVER_ERROR = "HTTP/1.1 500 Internal Server Error";
std::string LightHttpResponse::RESP_NOT_IMPLEMENTED = "HTTP/1.1 501 Not Implemented";
// ----------------------------------------------------------------------
LightHttpResponse::LightHttpResponse(int nSockFd) {
TAG = "LightHttpResponse";
if (LightHttpResponse::g_mapReponseDescription == nullptr) {
LightHttpResponse::g_mapReponseDescription = new std::map<int, std::string>();
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(200,"HTTP/1.1 200 OK"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(400, "HTTP/1.1 400 Bad Request"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(403, "HTTP/1.1 403 Forbidden"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(404, "HTTP/1.1 404 Not Found"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(413, "HTTP/1.1 413 Payload Too Large"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(500, "HTTP/1.1 500 Internal Server Error"));
LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(501, "HTTP/1.1 501 Not Implemented"));
}
m_nSockFd = nSockFd;
m_bClosed = false;
noCache();
long nSec = Fallen::currentTime_seconds();
m_sLastModified = Fallen::formatTimeForWeb(nSec);
m_nResponseCode = 500;
m_sDataType = "text/html";
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::ok() {
m_nResponseCode = 200;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::badRequest() {
m_nResponseCode = 400;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::forbidden() {
m_nResponseCode = 403;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::notFound() {
m_nResponseCode = 404;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::payloadTooLarge() {
m_nResponseCode = 413;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::internalServerError() {
m_nResponseCode = 500;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::notImplemented() {
m_nResponseCode = 501;
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::noCache() {
m_sCacheControl = "no-cache, no-store, must-revalidate";
return *this;
}
// ----------------------------------------------------------------------
LightHttpResponse &LightHttpResponse::cacheSec(int nCacheSec) {
m_sCacheControl = "max-age=" + std::to_string(nCacheSec);
return *this;
}
// ----------------------------------------------------------------------
std::string LightHttpResponse::prepareHeaders(int nLength) {
std::string sResponseCode = LightHttpResponse::g_mapReponseDescription->at(m_nResponseCode);
return sResponseCode + "\r\n"
"Date: " + m_sLastModified + "\r\n"
"Server: wsjcpp\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Cache-Control: " + m_sCacheControl + "\r\n"
"Last-Modified: " + m_sLastModified + "\r\n" // TODO generate data
"Content-Length: " + std::to_string(nLength) + "\r\n"
"Content-Type: " + m_sDataType + "\r\n"
"Connection: Closed\r\n";
}
// ----------------------------------------------------------------------
std::string LightHttpResponse::detectTypeOfFile(const std::string &sFilePath) {
// TODO cache: check file in cache
std::string sFileExt = sFilePath.substr(sFilePath.find_last_of(".") + 1);
std::string sType = "application/octet-stream";
if (sFileExt == "json") {
sType = "application/json";
} else if (sFileExt == "css") {
sType = "text/css";
} else if (sFileExt == "js") {
sType = "text/javascript";
} else if (sFileExt == "html") {
sType = "text/html";
} else if (sFileExt == "gif") {
sType = "image/gif";
} else if (sFileExt == "ico") {
sType = "image/x-icon";
} else if (sFileExt == "xml") {
sType = "application/xml";
} else if (sFileExt == "png") {
sType = "application/xml";
} else if (sFileExt == "jpg" || sFileExt == "jpeg") {
sType = "image/jpeg";
} else if (sFileExt == "svg") {
sType = "image/svg+xml";
}
return sType;
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendText(const std::string &sBody) {
m_sDataType = "text/html";
std::string sResponse = prepareHeaders(sBody.length())
+ "\r\n" + sBody;
if (m_bClosed) {
Log::warn(TAG, "Already sended response");
return;
}
m_bClosed = true;
// Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<");
send(m_nSockFd, sResponse.c_str(), sResponse.length(),0);
close(m_nSockFd);
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendEmpty() {
this->sendText("");
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendOptions(const std::string &sOptions) {
m_sDataType = "text/html";
std::string sResponse = prepareHeaders(0)
+ "Access-Control-Allow-Methods: " + sOptions
+ "\r\n\r\n";
if (m_bClosed) {
Log::warn(TAG, "Already sended response");
return;
}
m_bClosed = true;
// Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<");
send(m_nSockFd, sResponse.c_str(), sResponse.length(),0);
close(m_nSockFd);
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendDontUnderstand() {
std::string sResponse = "I don't understand you! Are you just a machine? Or maybe hacker?";
if (m_bClosed) {
Log::warn(TAG, "Already sended response");
return;
}
m_bClosed = true;
// Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<");
send(m_nSockFd, sResponse.c_str(), sResponse.length(),0);
close(m_nSockFd);
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendFile(const std::string &sFilePath) {
// read data from file
std::ifstream f(sFilePath, std::ios::binary | std::ios::ate);
std::streamsize nSize = f.tellg();
f.seekg(0, std::ios::beg);
char *pData = new char[nSize];
// std::vector<char> buffer(size);
if (nSize > 10*1024*1024) {
this->payloadTooLarge();
this->sendEmpty();
delete[] pData;
return;
}
if (!f.read(pData, nSize)) {
this->forbidden();
this->sendEmpty();
delete[] pData;
return;
// std::cout << sFilePath << "\n filesize: " << nSize << " bytes\n";
}
this->sendBuffer(sFilePath, pData, nSize);
delete[] pData;
}
// ----------------------------------------------------------------------
void LightHttpResponse::sendBuffer(const std::string &sFilePath, const char *pBuffer, const int nBufferSize) {
// TODO cache: check file in cache
m_sDataType = detectTypeOfFile(sFilePath);
std::string sResponse = prepareHeaders(nBufferSize)
+ "\r\n";
if (m_bClosed) {
Log::warn(TAG, "Already sended response");
// delete[] pData;
return;
}
m_bClosed = true;
#if __APPLE__
send(m_nSockFd, sResponse.c_str(), sResponse.length(),SO_NOSIGPIPE);
send(m_nSockFd, pData, nSize, SO_NOSIGPIPE);
// #if
// TARGET_OS_MAC
#else
send(m_nSockFd, sResponse.c_str(), sResponse.length(), MSG_CONFIRM);
send(m_nSockFd, pBuffer, nBufferSize, MSG_CONFIRM);
#endif
close(m_nSockFd);
}
// ----------------------------------------------------------------------
// LightHttpRequest
LightHttpRequest::LightHttpRequest(int nSockFd, const std::string &sAddress) {
m_nSockFd = nSockFd;
m_sAddress = sAddress;
m_bClosed = false;
m_sRequest = "";
m_nParserState = EnumParserState::START;
TAG = "LightHttpRequest";
long nSec = Fallen::currentTime_seconds();
m_sLastModified = Fallen::formatTimeForWeb(nSec);
m_nContentLength = 0;
}
// ----------------------------------------------------------------------
int LightHttpRequest::sockFd() {
return m_nSockFd;
}
// ----------------------------------------------------------------------
std::string LightHttpRequest::requestType() {
return m_sRequestType;
}
// ----------------------------------------------------------------------
std::string LightHttpRequest::requestPath() {
return m_sRequestPath;
}
// ----------------------------------------------------------------------
std::string LightHttpRequest::requestHttpVersion() {
return m_sRequestHttpVersion;
}
// ----------------------------------------------------------------------
std::map<std::string,std::string> &LightHttpRequest::requestQueryParams() {
return m_sRequestQueryParams;
}
// ----------------------------------------------------------------------
std::string LightHttpRequest::address() {
return m_sAddress;
}
// ----------------------------------------------------------------------
void LightHttpRequest::appendRecieveRequest(const std::string &sRequestPart) {
m_sRequest += sRequestPart;
const std::string sContentLengthPrefix = "content-length:";
if (m_nParserState == EnumParserState::START) {
m_vHeaders.clear();
// Log::info(TAG, "START \n>>>\n" + m_sRequest + "\n<<<\n");
std::istringstream f(m_sRequest);
std::string sLine = "";
int nSize = 0;
bool bHeadersEnded = false;
while (getline(f, sLine, '\n')) {
nSize += sLine.length() + 1;
Fallen::trim(sLine);
// Log::info(TAG, "Line: {" + sLine + "}, size=" + std::to_string(sLine.length()));
if (sLine.length() == 0) {
bHeadersEnded = true;
break;
}
m_vHeaders.push_back(sLine);
Fallen::to_lower(sLine);
if (!sLine.compare(0, sContentLengthPrefix.size(), sContentLengthPrefix)) {
m_nContentLength = atoi(sLine.substr(sContentLengthPrefix.size()).c_str());
// Log::warn(TAG, "Content-Length: " + std::to_string(m_nContentLength));
}
}
if (bHeadersEnded) {
if (m_vHeaders.size() > 0) {
this->parseFirstLine(m_vHeaders[0]);
}
m_sRequest.erase(0, nSize);
// Log::info(TAG, "AFTER ERASE \n>>>\n" + m_sRequest + "\n<<<\n");
m_nParserState = EnumParserState::BODY;
} else {
// Log::info(TAG, "Not ended");
}
}
if (m_nParserState == EnumParserState::BODY && m_sRequest.length() == m_nContentLength) {
m_nParserState = EnumParserState::ENDED;
m_sRequestBody = m_sRequest;
}
}
// ----------------------------------------------------------------------
bool LightHttpRequest::isEnoughAppendReceived() {
return m_nParserState == EnumParserState::ENDED;
}
// ----------------------------------------------------------------------
void LightHttpRequest::parseFirstLine(const std::string &sHeader) {
if (sHeader.size() > 0) {
std::istringstream f(sHeader);
std::vector<std::string> params;
std::string s;
while (getline(f, s, ' ')) {
params.push_back(s);
}
if (params.size() > 0) {
m_sRequestType = params[0];
}
if (params.size() > 1) {
m_sRequestPath = params[1];
}
// TODO m_sRequestPath - need split by ? if exists
if (params.size() > 2) {
m_sRequestHttpVersion = params[2];
}
}
// parse query
std::size_t nFound = m_sRequestPath.find("?");
if (nFound != std::string::npos) {
std::string sQuery = m_sRequestPath.substr(nFound+1);
m_sRequestPath = m_sRequestPath.substr(0, nFound);
std::istringstream f(sQuery);
std::string sParam;
while (getline(f, sParam, '&')) {
std::size_t nFound2 = sParam.find("=");
std::string sValue = sParam.substr(nFound2+1);
std::string sName = sParam.substr(0, nFound2);
m_sRequestQueryParams[sName] = sValue; // wrong use map for params
}
}
}
// ----------------------------------------------------------------------
// LightHttpDequeRequests
LightHttpRequest *LightHttpDequeRequests::popRequest() {
if (m_dequeRequests.size() == 0) {
m_mtxWaiterRequests.lock();
}
std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests);
LightHttpRequest *pRequest = nullptr;
int nSize = m_dequeRequests.size();
if (nSize > 0) {
pRequest = m_dequeRequests.back();
m_dequeRequests.pop_back();
}
return pRequest;
}
// ----------------------------------------------------------------------
void LightHttpDequeRequests::pushRequest(LightHttpRequest *pRequest) {
{
std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests);
if (m_dequeRequests.size() > 20) {
Log::warn(TAG, " deque more than " + std::to_string(m_dequeRequests.size()));
}
m_dequeRequests.push_front(pRequest);
}
if (m_dequeRequests.size() == 1) {
m_mtxWaiterRequests.unlock();
}
}
// ----------------------------------------------------------------------
void LightHttpDequeRequests::cleanup() {
std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests);
while (m_dequeRequests.size() > 0) {
delete m_dequeRequests.back();
m_dequeRequests.pop_back();
}
}
// ---------------------------------------------------------------------
// LightHttpHandlerBase
LightHttpHandlerBase::LightHttpHandlerBase(const std::string &sName) {
m_sName = sName;
}
// ---------------------------------------------------------------------
const std::string &LightHttpHandlerBase::name() {
return m_sName;
}
// ---------------------------------------------------------------------
// LightHttpHandlers
LightHttpHandlers::LightHttpHandlers() {
TAG = "LightHttpHandlers";
}
// ---------------------------------------------------------------------
void LightHttpHandlers::add(LightHttpHandlerBase *pHandler) {
m_pHandlers.push_back(pHandler);
}
// ---------------------------------------------------------------------
void LightHttpHandlers::remove(const std::string &sName) {
std::vector<LightHttpHandlerBase *>::iterator it = m_pHandlers.begin();
for (it = m_pHandlers.end(); it != m_pHandlers.begin(); it--) {
LightHttpHandlerBase *pHandler = *it;
if (pHandler->name() == sName) {
m_pHandlers.erase(it);
}
}
}
// ---------------------------------------------------------------------
bool LightHttpHandlers::find(const std::string &sName, LightHttpHandlerBase *pHandler) {
std::vector<LightHttpHandlerBase *>::iterator it = m_pHandlers.begin();
for (it = m_pHandlers.begin(); it != m_pHandlers.end(); ++it) {
LightHttpHandlerBase *p = *it;
if (p->name() == sName) {
pHandler = p;
return true;
}
}
return false;
}
// ---------------------------------------------------------------------
bool LightHttpHandlers::handle(const std::string &sWorkerId, LightHttpRequest *pRequest) {
std::string _tag = TAG + "-" + sWorkerId;
for (int i = 0; i < m_pHandlers.size(); i++) {
if (m_pHandlers[i]->canHandle(sWorkerId, pRequest)) {
if (m_pHandlers[i]->handle(sWorkerId, pRequest)) {
return true;
} else {
Log::warn("LightHttpHandlers", m_pHandlers[i]->name() + " - could not handle request '" + pRequest->requestPath() + "'");
}
}
}
return false;
}
// ----------------------------------------------------------------------
// LightHttpThreadWorker
void* processRequest(void *arg) {
LightHttpThreadWorker *pWorker = (LightHttpThreadWorker *)arg;
pthread_detach(pthread_self());
pWorker->run();
return 0;
}
// ----------------------------------------------------------------------
LightHttpThreadWorker::LightHttpThreadWorker(const std::string &sName, LightHttpDequeRequests *pDeque, LightHttpHandlers *pHandlers) {
TAG = "LightHttpThreadWorker-" + sName;
m_pDeque = pDeque;
m_bStop = false;
m_sName = sName;
m_pHandlers = pHandlers;
}
// ----------------------------------------------------------------------
void LightHttpThreadWorker::start() {
m_bStop = false;
pthread_create(&m_serverThread, NULL, &processRequest, (void *)this);
}
// ----------------------------------------------------------------------
void LightHttpThreadWorker::stop() {
m_bStop = true;
}
// ----------------------------------------------------------------------
void LightHttpThreadWorker::run() {
const int nMaxPackageSize = 4096;
while (1) {
if (m_bStop) return;
LightHttpRequest *pInfo = m_pDeque->popRequest();
bool bExists = pInfo != nullptr;
// TODO refactor
if (bExists) {
int nSockFd = pInfo->sockFd();
// set timeout options
struct timeval timeout;
timeout.tv_sec = 1; // 1 seconds timeout
timeout.tv_usec = 0;
setsockopt(nSockFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
struct sockaddr_in addr;
socklen_t addr_size = sizeof(struct sockaddr_in);
int res = getpeername(nSockFd, (struct sockaddr *)&addr, &addr_size);
char *clientip = new char[20];
memset(clientip, 0, 20);
strcpy(clientip, inet_ntoa(addr.sin_addr));
// Log::info(TAG, "IP-address: " + std::string(clientip));
LightHttpResponse *pResponse = new LightHttpResponse(nSockFd);
int n;
// int newsockfd = (long)arg;
char msg[nMaxPackageSize];
std::string sRequest;
// std::cout << nSockFd << ": address = " << info->address() << "\n";
// read data from socket
bool bErrorRead = false;
while (1) { // problem can be here
// std::cout << nSockFd << ": wait recv...\n";
memset(msg, 0, nMaxPackageSize);
n = recv(nSockFd, msg, nMaxPackageSize, 0);
// std::cout << "N: " << n << std::endl;
if (n == -1) {
bErrorRead = true;
std::cout << nSockFd << ": error read... \n";
break;
}
if (n == 0) {
//close(nSockFd);
break;
}
// Log::info(TAG, "Readed " + std::to_string(n) + " bytes...");
msg[n] = 0;
//send(newsockfd,msg,n,0);
sRequest = std::string(msg);
std::string sRecv(msg);
pInfo->appendRecieveRequest(sRecv);
if (pInfo->isEnoughAppendReceived()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Log::info(TAG, "\nRequest: \n>>>\n" + sRequest + "\n<<<");
if (bErrorRead) {
pResponse->sendDontUnderstand();
} else if (pInfo->requestType() == "OPTIONS") {
pResponse->ok().sendOptions("OPTIONS, GET, POST");
} else if (pInfo->requestType() != "GET" && pInfo->requestType() != "POST") {
pResponse->notImplemented().sendEmpty();
} else {
if (!m_pHandlers->handle(m_sName, pInfo)) {
pResponse->notFound().sendEmpty();
} else {
// TODO resp internal error
// this->response(LightHttpResponse::RESP_INTERNAL_SERVER_ERROR);
}
}
delete pInfo;
delete pResponse;
}
/*if (!bExists) {
if (m_bStop) return;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (m_bStop) return;
}*/
}
}
// ----------------------------------------------------------------------
// LightHttpServer
LightHttpServer::LightHttpServer() {
TAG = "LightHttpServer";
m_nMaxWorkers = 4;
m_pDeque = new LightHttpDequeRequests();
m_pHandlers = new LightHttpHandlers();
m_bStop = false;
m_nPort = 8080;
}
// ----------------------------------------------------------------------
void LightHttpServer::setPort(int nPort) {
if (nPort > 10 && nPort < 65536) {
m_nPort = nPort;
} else {
Log::warn(TAG, "Port must be 10...65535");
}
m_nPort = nPort;
}
// ----------------------------------------------------------------------
void LightHttpServer::setMaxWorkers(int nMaxWorkers) {
if (nMaxWorkers > 0 && nMaxWorkers <= 100) {
m_nMaxWorkers = nMaxWorkers;
} else {
Log::warn(TAG, "Max workers must be 1...100");
}
}
// ----------------------------------------------------------------------
void LightHttpServer::startSync() {
m_nSockFd = socket(AF_INET, SOCK_STREAM, 0);
if (m_nSockFd <= 0) {
Log::err(TAG, "Failed to establish socket connection");
return;
}
int enable = 1;
if (setsockopt(m_nSockFd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
Log::err(TAG, "setsockopt(SO_REUSEADDR) failed");
return;
}
memset(&m_serverAddress, 0, sizeof(m_serverAddress));
m_serverAddress.sin_family = AF_INET;
m_serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
m_serverAddress.sin_port = htons(m_nPort);
if (bind(m_nSockFd, (struct sockaddr *)&m_serverAddress, sizeof(m_serverAddress)) == -1) {
Log::err(TAG, "Error binding to port " + std::to_string(m_nPort));
return;
}
listen(m_nSockFd, 5);
Log::info("LightHttpServer", "Light Http Server started on " + std::to_string(m_nPort) + " port.");
for (int i = 0; i < m_nMaxWorkers; i++) {
m_vWorkers.push_back(new LightHttpThreadWorker("worker" + std::to_string(i), m_pDeque, m_pHandlers));
}
for (int i = 0; i < m_vWorkers.size(); i++) {
m_vWorkers[i]->start();
}
std::string str;
m_bStop = false;
while (!m_bStop) { // or problem can be here
struct sockaddr_in clientAddress;
socklen_t sosize = sizeof(clientAddress);
int nSockFd = accept(m_nSockFd,(struct sockaddr*)&clientAddress,&sosize);
std::string sAddress = inet_ntoa(clientAddress.sin_addr);
LightHttpRequest *pInfo = new LightHttpRequest(nSockFd, sAddress);
// info will be removed inside a thread
m_pDeque->pushRequest(pInfo);
// pthread_create(&m_serverThread, NULL, &newRequest, (void *)pInfo);
// std::cout << "wait \n";
// std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
m_pDeque->cleanup();
for (int i = 0; i < m_vWorkers.size(); i++) {
m_vWorkers[i]->stop();
}
close(m_nSockFd);
}
// ----------------------------------------------------------------------
void* processWebServerStart(void *arg) {
LightHttpServer *pWebServer = (LightHttpServer *)arg;
pthread_detach(pthread_self());
pWebServer->startSync();
return 0;
}
// ----------------------------------------------------------------------
void LightHttpServer::start() {
m_bStop = false;
pthread_create(&m_serverThread, NULL, &processWebServerStart, (void *)this);
}
// ----------------------------------------------------------------------
LightHttpHandlers *LightHttpServer::handlers() {
return m_pHandlers;
}
// ----------------------------------------------------------------------
void LightHttpServer::stop() {
m_bStop = true;
}
| 32.707379 | 137 | 0.512603 | SibirCTF |
794eabe2a177cfb60461b8cfdd4cc07673433e37 | 3,416 | cpp | C++ | c++/serial2com/v0.2/serial_write.cpp | BoKoIsMe/J1900_FreeBSD | 19c4f7f01a37f4eda11a64040dad307a06563fb9 | [
"BSD-2-Clause"
] | null | null | null | c++/serial2com/v0.2/serial_write.cpp | BoKoIsMe/J1900_FreeBSD | 19c4f7f01a37f4eda11a64040dad307a06563fb9 | [
"BSD-2-Clause"
] | null | null | null | c++/serial2com/v0.2/serial_write.cpp | BoKoIsMe/J1900_FreeBSD | 19c4f7f01a37f4eda11a64040dad307a06563fb9 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <string>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
//#include <stdlib.h>
int open_port(int fd,int comport);
int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop);
int main(int argc,char * argv[])
{
using namespace std;
int fd;
int nwrite,arg_return;
char buff[255] = "hello\n";
if((fd = open_port(fd,1))<0)
{
perror("open_port error");
return 0;
}
if((arg_return = set_opt(fd,115200,8,'N',1))<0)
{
perror("set_opt error");
return 0;
}
cout << "opened serial fd = " << fd << endl;
for(int index = 65535;index != 0;index--)
{
nwrite = write(fd,buff,8);
cout <<"nwrite = " << nwrite << ',' << buff << "at " << index << " time" << endl;
}
close(fd);
return 0;
}
int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop)
{
struct termios newtio,oldtio;
//保存测试现有串口参数设置,在这里如果串口号等出错,会有相关出错信息
if (tcgetattr(fd,&oldtio) != 0)
{
perror("SetupSerial 1");
return -1;
}
bzero(&newtio,sizeof(newtio));
//设置字符大小
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
//设置停止位
switch(nBits)
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
//设置奇偶校验位
switch(nEvent)
{
case 'O'://奇数
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E'://偶数
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= PARENB;
break;
}
//设置数据传输率
switch(nSpeed)
{
case 2400:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
case 4800:
cfsetispeed(&newtio,B4800);
cfsetospeed(&newtio,B4800);
break;
case 9600:
cfsetispeed(&newtio,B9600);
cfsetospeed(&newtio,B9600);
break;
case 115200:
cfsetispeed(&newtio,B115200);
cfsetospeed(&newtio,B115200);
break;
case 460800:
cfsetispeed(&newtio,B460800);
cfsetospeed(&newtio,B460800);
break;
default:
cfsetispeed(&newtio,B2400);
cfsetospeed(&newtio,B2400);
break;
}
//设置停止位
if (nStop == 1)
newtio.c_cflag &= ~CSTOPB;
else if (nStop == 2)
newtio.c_cflag |= CSTOPB;
//设置等待时间和最小接收字符
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
//处理未接收字符
tcflush(fd,TCIFLUSH);
//激活新配置
if((tcsetattr(fd,TCSANOW,&newtio)) != 0)
{
perror("com set error");
return -1;
}
std::cout << "set done!" << std::endl;
return 0;
}
int open_port(int fd,int comport)
{
//char *dev[] {"/dev/cuau1","/dev/cuau2","/dev/cuau3"};
//long vdisable;
if (comport == 1)//串口1
{
fd = open("/dev/ttyu1",O_RDWR|O_NOCTTY|O_NDELAY);
if (-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
}
}
else if(comport == 2)//串口2
{
fd = open("/dev/ttyu2",O_RDWR|O_NOCTTY|O_NDELAY);
if (-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
}
}
else if (comport == 3)//串口3
{
fd = open("/dev/ttyu3",O_RDWR|O_NOCTTY|O_NDELAY);
if (-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
}
}
//恢复串口为阻塞状态
if(fcntl(fd,F_SETFL,0)<0)
std::cout << "fcntl failed!" << std::endl;
else
std::cout << "fcntl = " << fcntl(fd,F_SETFL,0) << std::endl;
//测试是否为终端设备
if (isatty(STDIN_FILENO) == 0)
std::cout << "standard input is not a terminal device" << std::endl;
else
std::cout << "isatty success!" << std::endl;
return fd;
}
| 19.745665 | 82 | 0.619145 | BoKoIsMe |
7951c2099d2a2305c69ec684eb3cd8f04736fdcd | 3,107 | cpp | C++ | Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp | reghrafa/PrintBot | fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617 | [
"MIT"
] | null | null | null | Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp | reghrafa/PrintBot | fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617 | [
"MIT"
] | null | null | null | Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp | reghrafa/PrintBot | fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617 | [
"MIT"
] | null | null | null | #include "Dialog.h"
#include "ProgramBlock.h"
Dialog::Dialog(ProgramBlock *newProgramBlock, QWidget *parent) :
programBlock(newProgramBlock),
QWidget(parent)
{
// qDebug() << "neuer Dialog, this: " << this;
qGridGroupBox.setFixedSize(DIALOG_WIDTH,DIALOG_HEIGHT);
if (programBlock)
{
// qDebug() << "neuer Dialog mit newProgramBlock: " << programBlock;
this->programBlock->createDialog(this);
this->programBlock->updateSourcecodeWidget();
this->programBlock->generateGraphics();
// this->setupWidgets();
}
else ///Leerer Dialog
{
// qDebug() << "neuer Dialog ohne newProgramBlock";
}
this->qGridLayout.setColumnStretch(3,1);
this->qGridLayout.setRowStretch(0,100);
this->qGridLayout.setRowStretch(1,50);
this->qGridGroupBox.setLayout(&qGridLayout);
this->qGridGroupBox.setParent(this);
}
Dialog::~Dialog()
{
// qDebug() << "~Dialog";
// qDebug() << "~Dialog, this: " << this;
// qDebug() << "~Dialog, programBlock: " << programBlock;
// qDebug() << "~Dialog Mitte";
if (this->programBlock)
{
if (this->programBlock->getDialog() == this)
{
this->programBlock->deleteDialog();
}
else
{
qDebug() << "ERROR?, ~Dialog: es existiert noch ein anderer Dialog: " << this->programBlock->getDialog();
}
///TODO: Evtl. Problem, dass Destruktor von programBlock gerade beim Durchlaufen ist!?
programBlock->generateGraphics(); //deselectBlock
programBlock->updateSourcecodeWidget();
}
}
///entfernt den Rahmen des Blocks, der zu diesem Dialog gehört
void Dialog::deselectBlock()
{
qDebug() << "Dialog::deselectBlock()";
if (programBlock)
{
programBlock->deleteDialog();
// qDebug() << "Dialog::deselectBlock(), Mitte";
programBlock->generateGraphics();
}
// qDebug() << "Dialog::deselectBlock(), Ende";
}
ProgramBlock *Dialog::getProgramBlock()
{
// qDebug() << "Dialog::getProgramBlock()";
return this->programBlock;
}
void Dialog::setProgramBlock(ProgramBlock *newProgramBlock)
{
this->programBlock = newProgramBlock;
}
QGridLayout &Dialog::getQGridLayout()
{
return this->qGridLayout;
}
QLabel &Dialog::getQLabel(int labelNumber)
{
if (labelNumber == 0) return this->qLabel0;
else if (labelNumber == 1) return this->qLabel1;
else qDebug() << "ERROR: Dialog::getLabel, undefined labelNumber";
}
QSpinBox &Dialog::getQSpinBox()
{
return this->qSpinBox0;
}
QComboBox &Dialog::getQComboBox(int comboBoxNumber)
{
if (comboBoxNumber == 0) return this->qComboBox0;
else if (comboBoxNumber == 1) return this->qComboBox1;
else if (comboBoxNumber == 2) return this->qComboBox2;
else qDebug() << "ERROR: Dialog::getQComboBox, undefined comboBoxNumber";
}
QSlider &Dialog::getQSlider()
{
return qSlider0;
}
QLineEdit &Dialog::getQLineEdit()
{
return qLineEdit0;
}
QDoubleSpinBox &Dialog::getQDoubleSpinBox()
{
return qDoubleSpinBox;
}
QDial &Dialog::getQDial()
{
return qDial;
}
| 25.260163 | 117 | 0.646283 | reghrafa |
7954e58a39ed71700f2083cb16de25dd062ff003 | 3,301 | cpp | C++ | Acrolinx.Sidebar.SDK/Dokument.cpp | acrolinx/sidebar-sdk-cpp | c2e640f9f512934162337704be062fc2e16e4ed9 | [
"Apache-2.0"
] | null | null | null | Acrolinx.Sidebar.SDK/Dokument.cpp | acrolinx/sidebar-sdk-cpp | c2e640f9f512934162337704be062fc2e16e4ed9 | [
"Apache-2.0"
] | null | null | null | Acrolinx.Sidebar.SDK/Dokument.cpp | acrolinx/sidebar-sdk-cpp | c2e640f9f512934162337704be062fc2e16e4ed9 | [
"Apache-2.0"
] | null | null | null | /* Copyright Acrolinx GmbH */
// Dokument.cpp : Implementation of CDokument
#include "stdafx.h"
#include "Dokument.h"
// CDokument
STDMETHODIMP CDokument::GetContent(BSTR* content)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
ACROASSERT(m_isInstanceCreated == TRUE, "Initialize Document object by calling InitInstance() before using it");
*content = m_content.AllocSysString();
return S_OK;
}
STDMETHODIMP CDokument::GetReference(BSTR* reference)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
ACROASSERT(m_isInstanceCreated == TRUE, "Initialize Document object by calling InitInstance() before using it");
*reference = m_reference.AllocSysString();
return S_OK;
}
STDMETHODIMP CDokument::GetFormat(Input_Format* format)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
ACROASSERT(m_isInstanceCreated == TRUE, "Initialize Document object by calling InitInstance() before using it");
*format = m_format;
return S_OK;
}
STDMETHODIMP CDokument::InitInstance(BSTR content, BSTR reference, Input_Format inputFormat)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if(!Instantiate())
{
return S_FALSE;
}
SetDocument(content, reference, inputFormat, nullptr);
return S_OK;
}
CString CDokument::GetFormatAsString(void)
{
ACROASSERT(m_isInstanceCreated == TRUE, "Initialize Document object by calling InitInstance() before using it");
if(m_format == IF_XML)
return CString(_T("XML"));
else if (m_format == IF_HTML)
return CString(_T("HTML"));
else if (m_format == IF_MARKDOWN)
return CString(_T("MARKDOWN"));
else if (m_format == IF_TEXT)
return CString(_T("TEXT"));
else if (m_format == IF_WORD_XML)
return CString(_T("WORD_XML"));
else if (m_format == IF_AUTO)
return CString(_T("AUTO"));
return CString(_T("AUTO"));
}
STDMETHODIMP CDokument::InitInstanceWithSelectionRanges(BSTR content, BSTR reference, Input_Format inputFormat, IRanges* selectionRanges)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if(!Instantiate())
{
return S_FALSE;
}
ACROASSERT(selectionRanges != nullptr, "Selection ranges object is not valid");
SetDocument(content, reference, inputFormat, selectionRanges);
return S_OK;
}
void CDokument::SetDocument(BSTR content, BSTR reference, Input_Format inputFormat, IRanges* selectionRanges)
{
ACROASSERT(inputFormat >= IF_XML && inputFormat <= IF_AUTO, "You are trying to set input format which is not supported.");
ACROASSERT(m_selectionRanges == nullptr, "You have already called SetDocument(). Use the instance you have created.");
if(m_selectionRanges != nullptr)
{
m_selectionRanges->Release();
m_selectionRanges = nullptr;
}
m_content = content;
LOGD << "Content: " << m_content.GetString();
m_reference = reference;
LOGD << "Reference: " << m_reference.GetString();
m_format = inputFormat;
LOGD << "Format: " << GetFormatAsString().GetString();
m_selectionRanges = selectionRanges;
}
IRanges* CDokument::GetSelectionRanges(void)
{
ACROASSERT(m_isInstanceCreated == TRUE, "Initialize Document object by calling InitInstance() before using it");
return m_selectionRanges;
}
| 26.408 | 137 | 0.705241 | acrolinx |
7957212bc67001ea48eaa90be28759fdb2c36026 | 760 | hpp | C++ | src/it/resources/expected/my_cpp_interface/cwrapper/cw__my_cpp_interface.hpp | mutagene/djinni-generator | 09b420537183e0f941ae55afbf15d72c3f8b76a1 | [
"Apache-2.0"
] | 60 | 2020-10-17T18:05:37.000Z | 2022-03-14T22:58:27.000Z | src/it/resources/expected/my_cpp_interface/cwrapper/cw__my_cpp_interface.hpp | mutagene/djinni-generator | 09b420537183e0f941ae55afbf15d72c3f8b76a1 | [
"Apache-2.0"
] | 85 | 2020-10-13T21:58:40.000Z | 2022-03-16T09:29:01.000Z | src/it/resources/expected/my_cpp_interface/cwrapper/cw__my_cpp_interface.hpp | mutagene/djinni-generator | 09b420537183e0f941ae55afbf15d72c3f8b76a1 | [
"Apache-2.0"
] | 24 | 2020-10-16T21:22:31.000Z | 2022-03-02T18:15:29.000Z | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file was generated by Djinni from my_cpp_interface.djinni
#pragma once
#include <atomic>
#include <optional>
#include "../cpp-headers/my_cpp_interface.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include "../cwrapper-headers/cw__my_cpp_interface.h"
#ifdef __cplusplus
}
#endif
struct DjinniWrapperMyCppInterface final {
DjinniWrapperMyCppInterface(std::shared_ptr<::MyCppInterface>wo): wrapped_obj(wo) {};
static std::shared_ptr<::MyCppInterface> get(djinni::Handle<DjinniWrapperMyCppInterface> dw);
static djinni::Handle<DjinniWrapperMyCppInterface> wrap(std::shared_ptr<::MyCppInterface> obj);
const std::shared_ptr<::MyCppInterface> wrapped_obj;
std::atomic<size_t> ref_count {1};
};
| 28.148148 | 99 | 0.761842 | mutagene |
7959fe8af057f9068966bdfb0e40465848e2d815 | 1,249 | cpp | C++ | src/common/ServiceThread.cpp | kangliqiang/rocketmq-client4cpp | ebea2464f769f24f60206e998411f65c53f87b01 | [
"Apache-2.0"
] | 12 | 2016-01-07T07:24:05.000Z | 2021-02-03T08:03:20.000Z | src/common/ServiceThread.cpp | yaosiming/vesselmq-client4c | a7af22d83c2e8cd27346940cd7215c7fe2918961 | [
"Apache-2.0"
] | 1 | 2016-12-27T07:45:14.000Z | 2018-03-21T05:09:51.000Z | src/common/ServiceThread.cpp | yaosiming/vesselmq-client4c | a7af22d83c2e8cd27346940cd7215c7fe2918961 | [
"Apache-2.0"
] | 4 | 2016-01-14T11:10:22.000Z | 2018-01-16T02:16:59.000Z | /**
* Copyright (C) 2013 kangliqiang ,kangliq@163.com
*
* 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 "ServiceThread.h"
#include "Monitor.h"
#include "ScopedLock.h"
ServiceThread::ServiceThread(const char* name)
:kpr::Thread(name),
m_notified(false),
m_stoped(false)
{
}
ServiceThread::~ServiceThread()
{
}
void ServiceThread::stop()
{
m_stoped = true;
wakeup();
}
void ServiceThread::wakeup()
{
kpr::ScopedLock<kpr::Monitor> lock(*this);
if (!m_notified)
{
m_notified = true;
Notify();
}
}
void ServiceThread::waitForRunning(long interval)
{
kpr::ScopedLock<kpr::Monitor> lock(*this);
if (m_notified)
{
m_notified = false;
return;
}
try
{
Wait(interval);
}
catch (...)
{
m_notified = false;
}
}
| 18.101449 | 74 | 0.705364 | kangliqiang |
795e05bdae48dba3bcd68ee1e89e1ce7d1bde0b7 | 3,152 | cc | C++ | chrome/services/machine_learning/public/cpp/decision_tree_model_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/services/machine_learning/public/cpp/decision_tree_model_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/services/machine_learning/public/cpp/decision_tree_model_unittest.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 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/services/machine_learning/public/cpp/decision_tree_model.h"
#include <memory>
#include <utility>
#include "base/macros.h"
#include "base/test/task_environment.h"
#include "chrome/services/machine_learning/public/cpp/test_support/machine_learning_test_utils.h"
#include "chrome/services/machine_learning/public/mojom/decision_tree.mojom.h"
#include "components/optimization_guide/optimization_guide_test_util.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace machine_learning {
class DecisionTreeModelTest : public ::testing::Test {
public:
DecisionTreeModelTest() = default;
~DecisionTreeModelTest() override = default;
};
TEST_F(DecisionTreeModelTest, InstantiateValidModel) {
DecisionTreeModel model(testing::GetModelProtoForPredictionResult(
mojom::DecisionTreePredictionResult::kTrue));
EXPECT_TRUE(model.IsValid());
}
TEST_F(DecisionTreeModelTest, InstantiateInvalidModel) {
DecisionTreeModel model(nullptr);
EXPECT_FALSE(model.IsValid());
}
TEST_F(DecisionTreeModelTest, ValidModelFromSpec) {
auto model_proto = testing::GetModelProtoForPredictionResult(
mojom::DecisionTreePredictionResult::kTrue);
std::string model_string = model_proto->SerializeAsString();
auto model = DecisionTreeModel::FromModelSpec(
mojom::DecisionTreeModelSpec::New(model_string));
EXPECT_TRUE(model->IsValid());
}
TEST_F(DecisionTreeModelTest, InvalidModelFromSpec) {
// Scenario 1: initialize from an empty model spec pointer.
EXPECT_FALSE(DecisionTreeModel::FromModelSpec({}));
// Scenario 2: failed deserialization due to invalid model string.
EXPECT_FALSE(DecisionTreeModel::FromModelSpec(
mojom::DecisionTreeModelSpec::New("invalid model string")));
}
TEST_F(DecisionTreeModelTest, ValidModelPrediction) {
DecisionTreeModel model_true(testing::GetModelProtoForPredictionResult(
mojom::DecisionTreePredictionResult::kTrue));
double prediction_score;
mojom::DecisionTreePredictionResult decision_true =
model_true.Predict({}, &prediction_score);
EXPECT_EQ(mojom::DecisionTreePredictionResult::kTrue, decision_true);
EXPECT_GT(prediction_score, testing::kModelThreshold);
DecisionTreeModel model_false(testing::GetModelProtoForPredictionResult(
mojom::DecisionTreePredictionResult::kFalse));
mojom::DecisionTreePredictionResult decision_false =
model_false.Predict({}, &prediction_score);
EXPECT_EQ(mojom::DecisionTreePredictionResult::kFalse, decision_false);
EXPECT_LT(prediction_score, testing::kModelThreshold);
}
TEST_F(DecisionTreeModelTest, InvalidModelPrediction) {
DecisionTreeModel model_invalid(nullptr);
double prediction_score;
mojom::DecisionTreePredictionResult decision =
model_invalid.Predict({}, &prediction_score);
EXPECT_EQ(mojom::DecisionTreePredictionResult::kUnknown, decision);
}
} // namespace machine_learning
| 37.975904 | 97 | 0.798223 | mghgroup |
795fea6ba96d8763d47391bf425b2540472f1673 | 7,261 | cxx | C++ | inetsrv/query/cindex/indxact.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/cindex/indxact.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/cindex/indxact.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1991 - 1992.
//
// File: INDXACT.CXX
//
// Contents: Index transactions
//
// Classes: CIndexTrans, CChangeTrans
//
// History: 15-Oct-91 BartoszM created
//
// Notes: All operations are done under ResMan LOCK
//
//--------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <pstore.hxx>
#include "indxact.hxx"
#include "fretest.hxx"
#include "resman.hxx"
#include "changes.hxx"
#include "merge.hxx"
#include "mindex.hxx"
//+-------------------------------------------------------------------------
//
// Method: CIndexTrans::CIndexTrans, public
//
// Synopsis: Start transaction
//
// Arguments: [storage] -- physical storage
// [resman] -- resource manager
//
// History: 15-Oct-91 BartoszM created
//
//--------------------------------------------------------------------------
CIndexTrans::CIndexTrans ( CResManager& resman )
: _resman(resman), _freshTest(0), _fCommit(FALSE)
{
ciDebugOut (( DEB_ITRACE, ">>>> BEGIN index<<<<" ));
}
void CIndexTrans::LokCommit()
{
Win4Assert( !_fCommit );
ciDebugOut (( DEB_ITRACE, ">>>> COMMIT index<<<<" ));
_resman.LokCommitFresh ( _freshTest );
_freshTest = 0;
_fCommit = TRUE;
CTransaction::Commit();
}
//+---------------------------------------------------------------------------
//
// Function: LokCommit
//
// Synopsis: COmmit procedure for a master merge.
//
// Arguments: [storage] -- Storage object
// [widNewFreshLog] -- WorkId of the new fresh log
//
// History: 10-05-94 srikants Created
//
// Notes:
//
//----------------------------------------------------------------------------
void CIndexTrans::LokCommit( PStorage & storage, WORKID widNewFreshLog )
{
Win4Assert( widInvalid != widNewFreshLog );
_resman.LokCommitFresh( _freshTest );
WORKID widOldFreshLog = storage.GetSpecialItObjectId( itFreshLog );
Win4Assert( widInvalid != widOldFreshLog );
storage.RemoveFreshLog( widOldFreshLog );
storage.SetSpecialItObjectId( itFreshLog, widNewFreshLog );
_freshTest = 0;
_fCommit = TRUE;
CTransaction::Commit();
}
//+-------------------------------------------------------------------------
//
// Method: CMergeTrans::CMergeTrans, public
//
// Synopsis: Start transaction
//
// Arguments: [storage] -- physical storage
// [resman] -- resource manager
// [merge] -- merge object
//
// History: 15-Oct-91 BartoszM created
//
//--------------------------------------------------------------------------
CMergeTrans::CMergeTrans ( CResManager & resman,
PStorage& storage,
CMerge& merge )
: CIndexTrans( resman ),
_merge(merge),
_swapped(0),
_fCommit(FALSE),
_storage(storage),
_widNewFreshLog(widInvalid)
{
ciDebugOut (( DEB_ITRACE, ">>>> BEGIN merge trans <<<<" ));
}
//+-------------------------------------------------------------------------
//--------------------------------------------------------------------------
CMergeTrans::~CMergeTrans ()
{
if ( !_fCommit )
{
ciDebugOut (( DEB_ITRACE, ">>>> ABORT merge<<<<" ));
_merge.LokRollBack(_swapped);
if ( widInvalid != _widNewFreshLog )
{
_storage.RemoveFreshLog( _widNewFreshLog );
}
}
}
//+-------------------------------------------------------------------------
//--------------------------------------------------------------------------
void CMergeTrans::LokCommit()
{
Win4Assert( !_fCommit );
ciDebugOut (( DEB_ITRACE, ">>>> COMMIT merge<<<<" ));
_merge.LokZombify(); // old indexes
_fCommit = TRUE;
CIndexTrans::LokCommit( _storage, _widNewFreshLog );
}
IMPLEMENT_UNWIND( CMasterMergeTrans );
//+-------------------------------------------------------------------------
//--------------------------------------------------------------------------
void CMasterMergeTrans::LokCommit()
{
Win4Assert( _pMasterMergeIndex );
//
// Commit the master merge by replacing the master merge index
// with the new index.
//
//
// Transfer the ownership of the MMerge IndexSnapshot to the merge
// object from the master merge index.
//
_masterMerge.LokTakeIndexes( _pMasterMergeIndex );
//
// Replace the CMasterMergeIndex in the partition with the target index
// as the new master in the partition.
//
_pMasterMergeIndex->Zombify();
_resman.LokReplaceMasterIndex( _pMasterMergeIndex );
_mergeTrans.LokCommit();
}
//+-------------------------------------------------------------------------
//
// Method: CChangeTrans::CChangeTrans, public
//
// Synopsis: Start transaction
//
// Arguments: [storage] -- physical storage
// [resman] -- resource manager
//
// History: 15-Oct-91 BartoszM created
//
//--------------------------------------------------------------------------
CChangeTrans::CChangeTrans ( CResManager & resman, CPartition* pPart )
: _pPart(pPart), _resman(resman)
{
}
//+-------------------------------------------------------------------------
//
// Method: CChangeTrans::~CChangeTrans, public
//
// Synopsis: Commit or Abort transaction
//
// History: 15-Oct-91 BartoszM created
// 19-May-94 SrikantS Modified to disable updates in
// case of failures.
// 22-Nov-94 DwightKr Added content scan calls
//
//--------------------------------------------------------------------------
CChangeTrans::~CChangeTrans()
{
if ( GetStatus() != CTransaction::XActCommit )
{
//
// The change log commit failed, requiring either an incremental
// update or a full update. This code is executed when an
// internal corruption is detected or during a low disk situation
// or if a memory allocation failed. Disable updates in changelog.
//
_pPart->LokDisableUpdates();
//
// Tell Resman that a scan is needed.
//
_resman.SetUpdatesLost( _pPart->GetId() );
}
}
//+---------------------------------------------------------------------------
//
// Function: CDeletedIIDTrans
//
// Synopsis: ~dtor of the CDeletedIIDTrans. If change to deleted iid is
// logged and the transaction is not committed, it will roll
// back the change to the deleted iid.
//
// History: 7-17-95 srikants Created
//
// Notes:
//
//----------------------------------------------------------------------------
CDeletedIIDTrans::~CDeletedIIDTrans()
{
if ( IsRollBackTrans() )
{
_resman.RollBackDeletedIIDChange( *this );
}
}
| 28.034749 | 79 | 0.460818 | npocmaka |
79615ded1c8922959d0457cdd465aa407b968bac | 22,674 | cc | C++ | unicode/output_unicode_data.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | unicode/output_unicode_data.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | unicode/output_unicode_data.cc | RobertLWalton/min | 763bb5cf7cc72218831da2da685e8e5aa6e1408f | [
"Unlicense"
] | null | null | null | // MIN Routines to Output UNICODE Data Tables
//
// File: output_unicode_data.cc
// Author: Bob Walton (walton@acm.org)
// Date: Thu Aug 20 14:06:37 EDT 2020
//
// The authors have placed this program in the public
// domain; they make no warranty and accept no liability
// for this program.
// This file contains routines to check and output the
// MIN UNICODE database. This file is to be `#include'd
// in other files such as make_unicode_data.cc and
// min_unicode_test.cc.
# include <cmath>
// Vector of ASCII name equivalents for properties:
//
const char * property_name[] = {
"ASCII_Hex_Digit",
"Bidi_Control",
"Dash",
"Deprecated",
"Diacritic",
"Extender",
"Hex_Digit",
"Hyphen",
"Ideographic",
"IDS_Binary_Operator",
"IDS_Trinary_Operator",
"Join_Control",
"Logical_Order_Exception",
"Noncharacter_Code_Point",
"Other_Alphabetic",
"Other_Default_Ignorable_Code_Point",
"Other_Grapheme_Extend",
"Other_ID_Continue",
"Other_ID_Start",
"Other_Lowercase",
"Other_Math",
"Other_Uppercase",
"Pattern_Syntax",
"Pattern_White_Space",
"Prepended_Concatenation_Mark",
"Regional_Indicator",
"Quotation_Mark",
"Radical",
"Sentence_Terminal",
"Soft_Dotted",
"STerm",
"Terminal_Punctuation",
"Unified_Ideograph",
"Variation_Selector",
"White_Space"
};
unsigned const property_name_size =
sizeof property_name / sizeof property_name[0];
// Return true if strings are equal, false otherwise.
// NULL is treated as a string that is only equal
// to itself.
//
inline bool eq ( const char * s1, const char * s2 )
{
if ( s1 == NULL ) return s2 == NULL;
else if ( s2 == NULL ) return false;
else return strcmp ( s1, s2 ) == 0;
}
// Ditto, but for ustring's for which columns == 0 is
// possible. The ustring_chars values determine the
// length and columns uniquely.
//
inline bool ustring_eq ( ustring s1, ustring s2 )
{
if ( s1 == NULL ) return s2 == NULL;
else if ( s2 == NULL ) return false;
else return strcmp ( ustring_chars ( s1 ),
ustring_chars ( s2 ) ) == 0;
}
// Return true if index[.] values i1 and i2 have
// identical values in all the tables and so can be
// merged.
//
// WARNING: as this function is used by make_unicode_
// data.cc, indexes must be uns32's and NOT uns16's.
//
inline bool index_eq ( uns32 i1, uns32 i2 )
{
return
eq ( category[i1], category[i2] )
&& combining_class[i1] == combining_class[i2]
&& eq ( bidi_class[i1], bidi_class[i2] )
&& numerator[i1] == numerator[i2]
&& denominator[i1] == denominator[i2]
// Numeric value is determined by
// numerator/denominator.
&& bidi_mirrored[i1] == bidi_mirrored[i2]
&& properties[i1] == properties[i2]
&& ustring_eq ( name[i1], name[i2] )
&& ustring_eq ( picture[i1], picture[i2] )
&& support_sets[i1] == support_sets[i2];
}
// Print data for index i, and list character codes c
// with i == index[c].
//
char line[502]; // Also used in make_unicode_data.cc.
const unsigned line_width = 80;
unsigned indent;
char * linep;
void putprop ( ostream & out, const char * prop )
{
unsigned length = strlen ( prop );
unsigned column = linep - line;
if ( column > indent )
* linep ++ = ',', ++ column;
if ( column + length + 2 > line_width )
{
* linep = 0;
out << line << endl;
linep = line;
for ( unsigned i = 0; i < indent; ++ i )
* linep ++ = ' ';
}
* linep ++ = ' ';
strcpy ( linep, prop );
linep += strlen ( linep );
}
void print_ss_support_set
( uns32 i, ostream & out = cout )
{
assert ( i < ss_support_sets_size );
uns8 k = ss_support_sets_shift[i];
sprintf ( line, "%12s = ( 1 << %2d ):",
ss_support_sets_name[i], k );
indent = strlen ( line );
linep = line + indent;
for ( uns32 j = 0; j < cc_support_sets_size;
++ j )
{
if ( cc_support_sets_mask[j] & ( 1 << k ) )
putprop ( out, cc_support_sets_name[j] );
}
* linep = 0;
out << line << endl;
}
void print_index ( uns16 i, ostream & out = cout )
{
assert ( i < index_limit );
char combining[20] = "";
if ( combining_class[i] != -1 )
sprintf ( combining, "%4d",
combining_class[i] );
sprintf ( line,
"%4d" // i
" %-4s" // name
" %s" // picture
" %-3s" // category
"%4s" // combining
" %-4s" // bidi_class
" %c", // bidi_mirrored
i,
name[i] == NULL ? " " :
ustring_chars ( name[i] ),
picture[i] == NULL ? " " :
ustring_chars ( picture[i] ),
category[i] == NULL ? "" :
category[i],
combining,
bidi_class[i] == NULL ? "" :
bidi_class[i],
bidi_mirrored[i] == 0 ? ' ' :
bidi_mirrored[i] );
indent = strlen ( line );
linep = line + indent;
if ( denominator[i] != 0 )
{
char buffer[100];
if ( denominator[i] == 1 )
sprintf ( buffer, "%.15g", numerator[i] );
else
sprintf ( buffer, "%.15g/%.15g",
numerator[i], denominator[i] );
putprop ( out, buffer );
}
for ( uns32 j = 0; j < ss_support_sets_size; ++ j )
{
uns8 k = ss_support_sets_shift[j];
if ( ( support_sets[i] & ( 1 << k ) ) != 0 )
putprop ( out, ss_support_sets_name[j] );
}
for ( unsigned j = 0; j < property_name_size; ++ j )
{
if ( ( properties[i] & ( 1ull << j ) ) != 0 )
putprop ( out, property_name[j] );
}
for ( Uchar c = 0; c < index_size; ++ c )
{
char buffer[10];
if ( i != index[c] ) continue;
sprintf ( buffer, "%02X", c );
putprop ( out, buffer );
}
* linep = 0;
out << line << endl;
}
void dump ( const char * filename )
{
ofstream out ( filename );
if ( ! out )
{
cout << "ERROR: could not open " << filename
<< " for output" << endl;
exit ( 1 );
}
out << std::setprecision ( 100 );
// Output double integers of arbitrary
// length.
out << "==================== UNICODE DATA DUMP:"
<< endl;
out << endl
<< "===== SUPPORT SETS:"
<< endl;
out << endl;
for ( uns32 i = 0; i < ss_support_sets_size;
++ i )
print_ss_support_set ( i, out );
out << endl
<< "===== INDEXED DATA:"
<< endl;
out << endl;
for ( uns16 i = 0; i < index_limit; ++ i )
print_index ( i, out );
out.close();
}
// Output: ` /* [0x...] = ['.'] */ '
//
// where 0x... is c in hex and '.' if c as an ASCII
// graphic character, with the ` = ['.']' being replaced
// by spaces if c is not an ASCII graphic character.
// n is the number of hex digits to be output. Return
// `out'.
//
ostream & index_comment
( ostream & out, Uchar c, int n )
{
char buffer[100];
sprintf ( buffer, "0x%0*X", n, c );
out << " /* [" << buffer;
if ( c < 127 && isgraph ( c ) )
out << "] = ['" << (char) c << "'] */ ";
else
out << "] */ ";
return out;
}
// Output values for a vector of const char *'s that are
// presumed to contain only graphic ASCII characters.
//
void output ( ostream & out,
const char * const * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
if ( vector[i] == NULL ) out << "NULL";
else out << '"' << vector[i] << '"';
}
out << endl;
}
// Output values for a vector of ustrings.
//
void ustring_output
( ostream & out,
ustring const * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
if ( vector[i] == NULL ) out << "NULL";
else
{
char buffer[100];
sprintf ( buffer, "\"\\x%02X\\x%02X\"",
ustring_length ( vector[i] ),
ustring_columns ( vector[i] ) );
out << "(ustring) " << buffer
<< " \"";
const char * p =
ustring_chars ( vector[i] );
const char * q = p;
while ( 0x20 < * q && * q < 0x7F ) ++ q;
if ( * q == 0 )
out << p;
else
{
while ( * p )
{
sprintf ( buffer, "\\x%02X",
(unsigned)
(unsigned char) * p ++ );
out << buffer;
}
}
out << '"';
}
}
out << endl;
}
// Output values for a vector of extra_name's.
//
void extra_name_output
( ostream & out,
extra_name const * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
extra_name const & e = vector[i];
char buffer[200];
char name[100];
sprintf ( name, "\"%s\"",
ustring_chars ( e.name ) );
sprintf ( buffer, " { (ustring)"
" \"\\x%02X\\x%02X\""
" %12s, 0x%08X }",
ustring_length ( e.name ),
ustring_columns ( e.name ),
name, e.c );
out << buffer;
}
out << endl;
}
// Output values for a vector of char's.
//
void output ( ostream & out, const char * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
if ( vector[i] == 0 ) out << "0";
else out << "'" << vector[i] << "'";
}
out << endl;
}
// Output values for a vector of uns8's.
//
void output ( ostream & out,
const uns8 * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
out << (unsigned) vector[i];
}
out << endl;
}
// Output values for a vector of short's.
//
void output ( ostream & out, const short * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
out << vector[i];
}
out << endl;
}
// Output values for a vector of uns32's.
//
void output ( ostream & out, const uns32 * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
out << vector[i];
}
out << endl;
}
// Output values for a vector of uns64's
// each containing at most b bits.
//
void output ( ostream & out,
const uns64 * vector,
unsigned b,
unsigned size )
{
char format[20];
sprintf ( format, "0x%%0%dllX", ( b + 3 ) / 4 );
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
char buffer[100];
sprintf ( buffer, format, vector[i] );
out << buffer;
}
out << endl;
}
// Output values for a vector of uns32's
// each containing at most b bits.
//
void output ( ostream & out,
const uns32 * vector,
unsigned b,
unsigned size )
{
char format[20];
sprintf ( format, "0x%%0%dX", ( b + 3 ) / 4 );
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
char buffer[100];
sprintf ( buffer, format, vector[i] );
out << buffer;
}
out << endl;
}
// Output values for a vector of double's that contain
// integer values.
//
void output ( ostream & out, const double * vector,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
char buffer[100];
sprintf ( buffer, "%.15g", vector[i] );
out << buffer;
}
out << endl;
}
// Output fraction values for a vector of double's whose
// contents are numerator/denominator or NaN if
// denominator == 0.
//
void output ( ostream & out,
const double * numerator,
const double * denominator,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
char buffer[100];
if ( denominator[i] == 0 ) out << "NAN";
else
{
sprintf ( buffer, "%.15g", numerator[i] );
out << buffer;
if ( denominator[i] != 1 )
{
sprintf ( buffer, ".0/%.15g",
denominator[i] );
out << buffer;
}
}
}
out << endl;
}
// Output Uchar vector.
//
void output_Uchar
( ostream & out, const Uchar * character,
unsigned size )
{
const char * finish = "";
for ( unsigned i = 0; i < size; ++ i )
{
out << finish << " \\" << endl;
finish = ",";
out << " /* [" << setw ( 3 ) << i << "] */ ";
char buffer[100];
sprintf ( buffer, "0x%08X", character[i] );
out << buffer;
}
out << endl;
}
// Output unicode_data_support_sets.h style file.
//
void output_support_sets ( const char * filename )
{
ofstream out ( filename );
if ( ! out )
{
cout << "ERROR: could not open " << filename
<< " for output" << endl;
exit ( 1 );
}
out <<
"// UNICODE Support Set Definitions\n"
"//\n"
"// File: " << filename << "\n"
"\n"
"// Generated by make_unicode_data.cc\n"
"\n"
"// See unicode_data.h for documentation.\n"
"\n"
"\n"
"enum {\n";
const char * first = "";
for ( unsigned i = 0; i < ss_support_sets_size;
++ i )
{
out << first << endl;
first = ",";
char buffer[100];
sprintf ( buffer, " %-16s = ( 1 << %2d )",
ss_support_sets_name[i],
ss_support_sets_shift[i] );
out << buffer;
}
out << endl <<
"\n"
"};\n";
out.close();
}
// Output unicode_data.cc style file.
//
void output_data ( const char * filename )
{
ofstream out ( filename );
if ( ! out )
{
cout << "ERROR: could not open " << filename
<< " for output" << endl;
exit ( 1 );
}
out << std::setprecision ( 100 );
// Output double integers of arbitrary
// length.
out <<
"// UNICODE Character Data\n"
"//\n"
"// File: " << filename << "\n"
"\n"
"// Generated by make_unicode_data.cc\n";
out <<
"\n"
"// UNICODE_SS_SUPPORT_SETS_NAME/SHIFT are\n"
"// lists of element values giving the names\n"
"// and shifts of ss support sets, and UNICODE_\n"
"// SS_SUPPORT_SETS_SIZE is the size of these\n"
"// vectors.\n";
out << endl
<< "# define UNICODE_SS_SUPPORT_SETS_SIZE "
<< ss_support_sets_size << endl;
out << endl
<< "# define UNICODE_SS_SUPPORT_SETS_NAME";
output ( out, ss_support_sets_name,
ss_support_sets_size );
out << endl
<< "# define UNICODE_SS_SUPPORT_SETS_SHIFT";
output ( out, ss_support_sets_shift,
ss_support_sets_size );
out <<
"\n"
"// UNICODE_CC_SUPPORT_SETS_NAME/MASK are\n"
"// lists of element values giving the names\n"
"// and masks of cc support sets, and UNICODE_\n"
"// CC_SUPPORT_SETS_SIZE is the size of these\n"
"// vectors.\n";
out << endl
<< "# define UNICODE_CC_SUPPORT_SETS_SIZE "
<< cc_support_sets_size << endl;
out << endl
<< "# define UNICODE_CC_SUPPORT_SETS_NAME";
output ( out, cc_support_sets_name,
cc_support_sets_size );
out << endl
<< "# define UNICODE_CC_SUPPORT_SETS_MASK";
output ( out, cc_support_sets_mask, 32,
cc_support_sets_size );
out <<
"\n"
"// UNICODE_INDEX is the list of element values\n"
"// of the `index' vector and UNICODE_INDEX_SIZE"
"\n"
"// is the size of the vector.\n";
out << endl << "# define UNICODE_INDEX_SIZE 0x"
<< hex << index_size << dec
<< endl;
out << endl << "# define UNICODE_INDEX";
const char * finish = "";
for ( Uchar c = 0; c < index_size; ++ c )
{
out << finish << " \\" << endl;
finish = ",";
index_comment ( out, c, 8 ) << index[c];
}
out << endl;
out <<
"\n"
"// UNICODE_INDEX_LIMIT is size of various\n"
"// vectors below.\n";
out << endl << "# define UNICODE_INDEX_LIMIT "
<< index_limit << endl;
out <<
"\n"
"// UNICODE_CHARACTER is the list of element\n"
"// values of the `character' vector whose size\n"
"// is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_CHARACTER";
output_Uchar ( out, character, index_limit );
out <<
"\n"
"// UNICODE_CATEGORY is the list of element\n"
"// values of the `category' vector whose size\n"
"// is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_CATEGORY";
output ( out, category, index_limit );
out <<
"\n"
"// UNICODE_COMBINING_CLASS is the list of\n"
"// element values of the `combining_class'\n"
"// vector whose size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_COMBINING_CLASS";
output ( out, combining_class, index_limit );
out <<
"\n"
"// UNICODE_BIDI_CLASS is the list of element\n"
"// values of the `bidi_class' vector whose\n"
"// size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_BIDI_CLASS";
output ( out, bidi_class, index_limit );
out <<
"\n"
"// UNICODE_NUMERATOR is the list of element\n"
"// values of the `numerator' vector whose size\n"
"// is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_NUMERATOR";
output ( out, numerator, index_limit );
out <<
"\n"
"// UNICODE_DENOMINATOR is the list of element\n"
"// values of the `denominator' vector whose\n"
"// size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_DENOMINATOR";
output ( out, denominator, index_limit );
out <<
"\n"
"// UNICODE_NUMERIC_VALUE is the list of\n"
"// element values of the `numeric_value'\n"
"// vector whose size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_NUMERIC_VALUE";
output ( out, numerator, denominator, index_limit );
out <<
"\n"
"// UNICODE_BIDI_MIRRORED is the list of"
" element\n"
"// values of the `bidi_mirrored' vector whose\n"
"// size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_BIDI_MIRRORED";
output ( out, bidi_mirrored, index_limit );
out <<
"\n"
"// UNICODE_PROPERTIES is the list of element\n"
"// values of the `properties' vector whose\n"
"// size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_PROPERTIES";
output ( out, properties, property_name_size,
index_limit );
out <<
"\n"
"// UNICODE_NAME is the list of element\n"
"// values of the `name' vector whose size\n"
"// is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_NAME";
ustring_output ( out, name, index_limit );
out <<
"\n"
"// UNICODE_EXTRA_NAMES_NUMBER is size of\n"
"// the UNICODE_EXTRA_NAMES vector below.\n";
out << endl
<< "# define UNICODE_EXTRA_NAMES_NUMBER "
<< extra_names_number << endl;
out <<
"\n"
"// UNICODE_EXTRA_NAMES is the list of element\n"
"// values of the `extra_names' vector whose\n"
"// size is UNICODE_EXTRA_NAMES_NUMBER.\n";
out << endl << "# define UNICODE_EXTRA_NAMES";
extra_name_output
( out, extra_names, extra_names_number );
out <<
"\n"
"// UNICODE_PICTURE is the list of element\n"
"// values of the `picture' vector whose size\n"
"// is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_PICTURE";
ustring_output ( out, picture, index_limit );
out <<
"\n"
"// UNICODE_SUPPORT_SETS is the list of element\n"
"// values of the `support_sets' vector whose\n"
"// size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_SUPPORT_SETS";
output ( out, support_sets, 32, index_limit );
out <<
"\n"
"// UNICODE_REFERENCE_COUNT is the list of\n"
"// element values of the `reference_count'\n"
"// vector whose size is UNICODE_INDEX_LIMIT.\n";
out << endl << "# define UNICODE_REFERENCE_COUNT";
output ( out, reference_count, index_limit );
out.close();
}
// Do some integrity checking of the tables.
//
void final_check ( void )
{
unsigned count[index_limit];
for ( unsigned i = 0;
i < index_limit; ++ i )
count[i] = 0;
for ( Uchar c = 0; c < index_size; ++ c )
{
unsigned i = index[c];
assert ( i < index_limit );
++ count[i];
}
for ( unsigned i = 0; i < index_limit; ++ i )
{
for ( unsigned i2 = i + 1;
i2 < index_limit; ++ i2 )
{
if ( i2 < 256 ) continue;
if ( ! index_eq ( i, i2 ) ) continue;
cout << "FINAL CHECK ERROR: "
<< "duplicate indices:" << endl;
print_index ( i );
print_index ( i2 );
}
const char * error = NULL;
// Check numeric value.
//
if ( denominator[i] == 0
&&
numerator[i] != 0 )
error = "denominator == 0 and numerator"
" != 0";
else if ( denominator[i] == 0
&&
! std::isnan ( numeric_value[i] ) )
error = "denominator == 0 and numeric_value"
" is not NaN";
else if ( denominator[i] != 0
&&
std::isnan ( numeric_value[i] ) )
error = "denominator != 0 and numeric_value"
" is NaN";
else if ( denominator[i] != 0
&&
numeric_value[i]
!= numerator[i] / denominator[i] )
error = "numeric_value !="
" numerator / denominator";
if ( count[i] != reference_count[i] )
error = "wrong reference_count";
if ( error != NULL )
{
cout << "FINAL CHECK ERROR: " << error
<< ":" << endl << "in ";
print_index ( i );
}
}
}
| 24.485961 | 56 | 0.530475 | RobertLWalton |
79627c204104b1e470dac018c9aa33a0dc3dc6d0 | 11,414 | hpp | C++ | qmath/include/qmath/mat3.hpp | jeanleflambeur/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 36 | 2015-03-09T16:47:14.000Z | 2021-02-04T08:32:04.000Z | qmath/include/qmath/mat3.hpp | jeanlemotan/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 42 | 2017-02-11T11:15:51.000Z | 2019-12-28T16:00:44.000Z | qmath/include/qmath/mat3.hpp | jeanleflambeur/silkopter | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | [
"BSD-3-Clause"
] | 5 | 2015-10-15T05:46:48.000Z | 2020-05-11T17:40:36.000Z | namespace math
{
template<typename T> mat3<T> const mat3<T>::zero(0); \
template<typename T> mat3<T> const mat3<T>::one(1); \
template<typename T> mat3<T> const mat3<T>::identity; \
///////////////////////////////////////////////////////////////////////////////
//constructors
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline mat3<T>::mat3()
: column0(math::uninitialized)
, column1(math::uninitialized)
, column2(math::uninitialized)
{
set_identity();
}
template <typename T>
inline mat3<T>::mat3(ZUninitialized)
: column0(math::uninitialized)
, column1(math::uninitialized)
, column2(math::uninitialized)
{
}
template <typename T>
inline mat3<T>::mat3(T value)
: column0(math::uninitialized)
, column1(math::uninitialized)
, column2(math::uninitialized)
{
MATH_ASSERT(is_finite(value));
m[0] = m[1] = m[2] = value;
m[3] = m[4] = m[5] = value;
m[6] = m[7] = m[8] = value;
}
template<typename T>
template<typename U>
inline mat3<T>::mat3(mat3<U> const& other)
: column0(math::uninitialized)
, column1(math::uninitialized)
, column2(math::uninitialized)
{
m[0] = (T)other.m[0];
m[1] = (T)other.m[1];
m[2] = (T)other.m[2];
m[3] = (T)other.m[3];
m[4] = (T)other.m[4];
m[5] = (T)other.m[5];
m[6] = (T)other.m[6];
m[7] = (T)other.m[7];
m[8] = (T)other.m[8];
}
template<typename T>
inline mat3<T>::mat3(T const v0, T const v1, T const v2, T const v3, T const v4, T const v5, T const v6, T const v7, T const v8)
: column0(math::uninitialized)
, column1(math::uninitialized)
, column2(math::uninitialized)
{
m[0] = v0;
m[1] = v1;
m[2] = v2;
m[3] = v3;
m[4] = v4;
m[5] = v5;
m[6] = v6;
m[7] = v7;
m[8] = v8;
MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) &&
is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) &&
is_finite(m[8]));
}
template<typename T>
inline mat3<T>::mat3(vec3<T> const& column0, vec3<T> const& column1, vec3<T> const& column2)
: column0(column0)
, column1(column1)
, column2(column2)
{
m[0] = column0.x;
m[1] = column0.y;
m[2] = column0.z;
m[3] = column1.x;
m[4] = column1.y;
m[5] = column1.z;
m[6] = column2.x;
m[7] = column2.y;
m[8] = column2.z;
}
///! Creates a world space lookat matrix (front axis is -yaxis, up axis is zaxis)
/// This lookAt method computes a look at matrix in jet coordinate system (3dmax biped).
/// This means that when you send a front of (0,1,0) and an up of (0,0,1) the resulting matrix is identity.
template<class T>
template<class Policy>
inline mat3<T> mat3<T>::look_at(vec3<T> const& front, vec3<T> const& up)
{
vec3<T> axisY = normalized<T, Policy>(front);
vec3<T> axisX = cross(axisY, normalized<T, Policy>(up));
axisX.template normalize<Policy>(); //this normalize is mandatory because axisY and up may be unitary but they hardly are orthogonal
vec3<T> axisZ = cross(axisX, axisY);
mat3<T> mat;
T* m = mat.m;
m[0] = axisX.x;
m[1] = axisX.y;
m[2] = axisX.z;
m[3] = axisY.x;
m[4] = axisY.y;
m[5] = axisY.z;
m[6] = axisZ.x;
m[7] = axisZ.y;
m[8] = axisZ.z;
MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) &&
is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) &&
is_finite(m[8]));
return mat;
}
///////////////////////////////////////////////////////////////////////////////
//methods
///////////////////////////////////////////////////////////////////////////////
template<typename T>
inline void mat3<T>::set(T const values[9])
{
MATH_ASSERT(values);
memcpy(m, values, sizeof(T)*element_count);
MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) &&
is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) &&
is_finite(m[8]));
}
template <typename T>
inline void mat3<T>::set_identity()
{
m[0] = m[4] = (T)1;
m[1] = m[2] = m[3] = m[5] = (T)0;
m[8] = (T)1;
m[6] = m[7] = (T)0;
}
template <typename T>
template <class Policy>
inline bool mat3<T>::invert()
{
// http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Matrix3.inl
// Invert a 3x3 using cofactors. This is faster than using a generic
// Gaussian elimination because of the loop overhead of such a method.
mat3<T> inv;
inv.m[0] = m[4]*m[8] - m[5]*m[7];
inv.m[1] = m[2]*m[7] - m[1]*m[8];
inv.m[2] = m[1]*m[5] - m[2]*m[4];
inv.m[3] = m[5]*m[6] - m[3]*m[8];
inv.m[4] = m[0]*m[8] - m[2]*m[6];
inv.m[5] = m[2]*m[3] - m[0]*m[5];
inv.m[6] = m[3]*m[7] - m[4]*m[6];
inv.m[7] = m[1]*m[6] - m[0]*m[7];
inv.m[8] = m[0]*m[4] - m[1]*m[3];
T fDet =
m[0]*inv.m[0] +
m[1]*inv.m[3] +
m[2]*inv.m[6];
if (is_zero(fDet))
{
return false;
}
T fInvDet = inverse<T, Policy>(fDet);
inv.m[0] *= fInvDet;
inv.m[1] *= fInvDet;
inv.m[2] *= fInvDet;
inv.m[3] *= fInvDet;
inv.m[4] *= fInvDet;
inv.m[5] *= fInvDet;
inv.m[6] *= fInvDet;
inv.m[7] *= fInvDet;
inv.m[8] *= fInvDet;
*this = inv;
MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) &&
is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) &&
is_finite(m[8]));
return true;
}
template <typename T>
inline void mat3<T>::transpose()
{
std::swap(m[1], m[3]);
std::swap(m[2], m[6]);
std::swap(m[5], m[7]);
}
template <typename T>
inline vec3<T> mat3<T>::get_row(uint8_t row) const
{
MATH_ASSERT(row < row_count);
return vec3<T>(m[row + 0], m[row + 3], m[row + 6]);
}
template <typename T>
inline void mat3<T>::set_row(uint8_t row, vec3<T> const& v)
{
MATH_ASSERT(is_finite(v));
MATH_ASSERT(row < row_count);
m[row + 0] = v.x;
m[row + 3] = v.y;
m[row + 6] = v.z;
}
template <typename T>
inline vec3<T> const& mat3<T>::get_column(uint8_t column) const
{
MATH_ASSERT(column < column_count);
uint8_t idx = column * row_count;
return reinterpret_cast<vec3<T> const&>(m[idx + 0]);
}
template <typename T>
inline void mat3<T>::set_column(uint8_t column, vec3<T> const& v)
{
MATH_ASSERT(is_finite(v));
MATH_ASSERT(column < column_count);
uint8_t idx = column * row_count;
m[idx + 0] = v.x;
m[idx + 1] = v.y;
m[idx + 2] = v.z;
}
template <typename T>
inline vec3<T> const& mat3<T>::get_axis_x() const
{
return get_column(0);
}
template <typename T>
inline vec3<T> const& mat3<T>::get_axis_y() const
{
return get_column(1);
}
template <typename T>
inline vec3<T> const& mat3<T>::get_axis_z() const
{
return get_column(2);
}
template <typename T>
inline vec3<T> mat3<T>::get_scale() const
{
return vec3<T>(math::length(get_axis_x()), math::length(get_axis_y()), math::length(get_axis_z()));
}
template <typename T>
inline void mat3<T>::set_axis_x(vec3<T> const& axis)
{
MATH_ASSERT(is_finite(axis));
m[0] = axis.x;
m[1] = axis.y;
m[2] = axis.z;
}
template <typename T>
inline void mat3<T>::set_axis_y(vec3<T> const& axis)
{
MATH_ASSERT(is_finite(axis));
m[3] = axis.x;
m[4] = axis.y;
m[5] = axis.z;
}
template <typename T>
inline void mat3<T>::set_axis_z(vec3<T> const& axis)
{
MATH_ASSERT(is_finite(axis));
m[6] = axis.x;
m[7] = axis.y;
m[8] = axis.z;
}
template <typename T>
inline void mat3<T>::set_scale(vec3<T> const& s)
{
MATH_ASSERT(is_finite(s));
m[0] = s.x;
m[4] = s.y;
m[8] = s.z;
}
template <typename T>
inline void mat3<T>::post_scale(vec3<T> const& s)
{
MATH_ASSERT(is_finite(s));
m[0] *= s.x;
m[4] *= s.y;
m[8] *= s.z;
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
inline bool mat3<T>::operator==(mat3<T> const& m) const
{
return memcmp(this->m, m.m, sizeof(T) * element_count) == 0;
}
template <typename T>
inline bool mat3<T>::operator!=(mat3<T> const& m) const
{
return !operator==(m);
}
///////////////////////////////////////////////////////////////////////////////
// indexing operators
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline T* mat3<T>::data()
{
return m;
}
template <typename T>
inline T const* mat3<T>::data() const
{
return m;
}
template <typename T>
inline T& mat3<T>::operator()(uint8_t column, uint8_t row)
{
MATH_ASSERT(column < column_count && row < row_count);
return m[column*row_count + row];
}
template <typename T>
inline T const& mat3<T>::operator()(uint8_t column, uint8_t row) const
{
MATH_ASSERT(column < column_count && row < row_count);
return m[column*row_count + row];
}
template <typename T>
inline mat3<T> mat3<T>::operator*(mat3<T> const& other) const
{
mat3<T> ret(math::uninitialized);
return multiply(ret, *this, other);
}
template <typename T>
inline mat3<T> mat3<T>::operator+(mat3<T> const& other) const
{
mat3<T> ret(math::uninitialized);
return cwise::add(ret, *this, other);
}
template <typename T>
inline mat3<T> mat3<T>::operator-(mat3<T> const& other) const
{
mat3<T> ret(math::uninitialized);
return cwise::substract(ret, *this, other);
}
template <typename T>
inline mat3<T>& mat3<T>::operator*=(mat3<T> const& other)
{
mat3<T> a(*this);
return multiply(*this, a, other);
}
template <typename T>
inline mat3<T>& mat3<T>::operator+=(mat3<T> const& other)
{
return cwise::add(*this, *this, other);
}
template <typename T>
inline mat3<T>& mat3<T>::operator-=(mat3<T> const& other)
{
return cwise::substract(*this, *this, other);
}
template <typename T>
inline mat3<T> mat3<T>::operator*(T scalar) const
{
MATH_ASSERT(is_finite(scalar));
mat3<T> ret(math::uninitialized);
return cwise::multiply(ret, *this, scalar);
}
template <typename T>
inline mat3<T> mat3<T>::operator+(T scalar) const
{
MATH_ASSERT(is_finite(scalar));
mat3<T> ret(math::uninitialized);
return cwise::add(ret, *this, scalar);
}
template <typename T>
inline mat3<T> mat3<T>::operator-(T scalar) const
{
MATH_ASSERT(is_finite(scalar));
mat3<T> ret(math::uninitialized);
return cwise::substract(ret, *this, scalar);
}
template <typename T>
inline mat3<T>& mat3<T>::operator*=(T scalar)
{
MATH_ASSERT(is_finite(scalar));
return cwise::multiply(*this, *this, scalar);
}
template <typename T>
inline mat3<T>& mat3<T>::operator+=(T scalar)
{
MATH_ASSERT(is_finite(scalar));
return cwise::add(*this, *this, scalar);
}
template <typename T>
inline mat3<T>& mat3<T>::operator-=(T scalar)
{
MATH_ASSERT(is_finite(scalar));
return cwise::substract(*this, *this, scalar);
}
}
| 26.482599 | 137 | 0.545733 | jeanleflambeur |
7966b213fa4cf117f76763778ebf11d519786445 | 11,667 | hpp | C++ | falcon/algorithm/recursive_for_each.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | falcon/algorithm/recursive_for_each.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | falcon/algorithm/recursive_for_each.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #ifndef FALCON_ALGORITHM_RECURSIVE_FOR_EACH_HPP
#define FALCON_ALGORITHM_RECURSIVE_FOR_EACH_HPP
#include <falcon/c++/reference.hpp>
#include <falcon/c++/conditional_cpp.hpp>
#include <falcon/iterator/subrange_access_iterator.hpp>
#include <falcon/type_traits/dimension.hpp>
#include <falcon/type_traits/ignore.hpp>
#include <falcon/utility/move.hpp>
namespace falcon {
namespace _aux {
template <class Function, class T, bool Break = true>
struct break_off
{
Function function;
T value;
#if __cplusplus < 201103L
break_off(const Function& function, const T& value)
: function(function)
, value(value)
{}
#endif
};
template <class Function, class Functor, bool Break = true>
struct break_if
{
Function function;
Functor functor;
#if __cplusplus < 201103L
break_if(const Function& function, const T& functor)
: function(function)
, functor(functor)
{}
#endif
};
template <class Function, class T, bool Break = true>
struct return_off
{
Function function;
T value;
#if __cplusplus < 201103L
return_off(const Function& function, const T& value)
: function(function)
, value(value)
{}
#endif
};
template <class Function, class Functor, bool Break = true>
struct return_if
{
Function function;
Functor functor;
#if __cplusplus < 201103L
return_if(const Function& function, const T& functor)
: function(function)
, functor(functor)
{}
#endif
};
template <std::size_t Dimension>
struct recursive_for_each
{
template<class Iterator, class Function>
static void for_each(Iterator first, Iterator last, Function& f)
{
for (; first != last; ++first) {
recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), f);
}
}
template<class Iterator, class Function, class T, bool Break>
static bool for_each(Iterator first, Iterator last, return_off<Function, T, Break>& w)
{
for (; first != last; ++first) {
if (!recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), w)) {
return false;
}
}
return true;
}
template<class Iterator, class Function, class Functor, bool Break>
static bool for_each(Iterator first, Iterator last, return_if<Function, Functor, Break>& w)
{
for (; first != last; ++first) {
if (!recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), w)) {
return false;
}
}
return true;
}
};
template <>
struct recursive_for_each<0>
{
template<class Iterator, class Function>
static void for_each(Iterator first, Iterator last, Function& f)
{
for (; first != last; ++first) {
f(*first);
}
}
template<class Iterator, class Function, class T, bool B>
static void for_each(Iterator first, Iterator last, break_off<Function, T, B>& w)
{
for (; first != last && (B ? *first != w.value : *first != w.value); ++first) {
w.function(*first);
}
}
template<class Iterator, class Function, class Functor, bool B>
static void for_each(Iterator first, Iterator last, break_if<Function, Functor, B>& w)
{
for (; first != last && B == w.functor(*first); ++first) {
w.function(*first);
}
}
template<class Iterator, class Function, class T, bool B>
static bool for_each(Iterator first, Iterator last, return_off<Function, T, B>& w)
{
for (; first != last; ++first) {
if (B ? *first == w.value : *first != w.value) {
return false;
}
w.function(*first);
}
return true;
}
template<class Iterator, class Function, class Functor, bool B>
static bool for_each(Iterator first, Iterator last, return_if<Function, Functor, B>& w)
{
for (; first != last; ++first) {
if (B != w.functor(*first)) {
return false;
}
w.function(*first);
}
return true;
}
};
template<class Preface, class Function, class Postface, std::size_t Dimension>
class recursive_intermediate;
}
#if __cplusplus >= 201103L
template <class Function, class T>
inline _aux::break_off<Function, T> break_off(Function&& function, T&& value)
{ return {std::forward<Function>(function), std::forward<T>(value)}; }
template <class Function, class T>
inline _aux::break_off<Function, T, false> break_off_not(Function&& function, T&& value)
{ return {std::forward<Function>(function), std::forward<T>(value)}; }
template <class Function, class Functor>
inline _aux::break_if<Function, Functor> break_if(Function&& function, Functor&& functor)
{ return {std::forward<Function>(function), std::forward<Functor>(functor)}; }
template <class Function, class Functor>
inline _aux::break_if<Function, Functor, false> break_if_not(Function&& function, Functor&& functor)
{ return {std::forward<Function>(function), std::forward<Functor>(functor)}; }
#else
template <class Function, class T>
inline _aux::break_off<Function, T> break_off(Function function, const T& value)
{ return _aux::break_off<Function, T>(function, value); }
template <class Function, class T>
inline _aux::break_off<Function, T, false> break_off_not(Function function, const T& value)
{ return _aux::break_off<Function, T, false>(function, value); }
template <class Function, class Functor>
inline _aux::break_if<Function, Functor> break_if(Function function, Functor functor)
{ return _aux::break_if<Function, Functor>(function, functor); }
template <class Function, class Functor>
inline _aux::break_if<Function, Functor, false> break_if_not(Function function, Functor functor)
{ return _aux::break_if<Function, Functor, false>(function, functor); }
#endif
#if __cplusplus >= 201103L
template <class Function, class T>
inline _aux::return_off<Function, T> return_off(Function&& function, T&& value)
{ return {std::forward<Function>(function), std::forward<T>(value)}; }
template <class Function, class T>
inline _aux::return_off<Function, T, false> return_off_not(Function&& function, T&& value)
{ return {std::forward<Function>(function), std::forward<T>(value)}; }
template <class Function, class Functor>
inline _aux::return_if<Function, Functor> return_if(Function&& function, Functor&& functor)
{ return {std::forward<Function>(function), std::forward<Functor>(functor)}; }
template <class Function, class Functor>
inline _aux::return_if<Function, Functor, false> return_if_not(Function&& function, Functor&& functor)
{ return {std::forward<Function>(function), std::forward<Functor>(functor)}; }
#else
template <class Function, class T>
inline _aux::return_off<Function, T> return_off(Function function, const T& value)
{ return _aux::return_off<Function, T>(function, value); }
template <class Function, class T>
inline _aux::return_off<Function, T, false> return_off_not(Function function, const T& value)
{ return _aux::return_off<Function, T, false>(function, value); }
template <class Function, class Functor>
inline _aux::return_if<Function, Functor> return_if(Function function, Functor functor)
{ return _aux::return_if<Function, Functor>(function, functor); }
template <class Function, class Functor>
inline _aux::return_if<Function, Functor, false> return_if_not(Function function, Functor functor)
{ return _aux::return_if<Function, Functor, false>(function, functor); }
#endif
template <class Iterator, class Function>
Function recursive_for_each(Iterator first, Iterator last, Function f)
{
_aux::recursive_for_each<dimension<
#if __cplusplus >= 201103L
decltype(*std::declval<Iterator>())
#else
std::iterator_traits<Iterator>::type
#endif
>::value - 1>::for_each(first, last, f);
return FALCON_FORWARD(Function, f);
}
template <std::size_t Dimension, class Iterator, class Function>
Function recursive_for_each(Iterator first, Iterator last, Function f)
{
_aux::recursive_for_each<
(Dimension == -1u ? dimension<
#if __cplusplus >= 201103L
decltype(*std::declval<Iterator>())
#else
std::iterator_traits<Iterator>::type
#endif
>::value : Dimension) - 1
>::for_each(first, last, f);
return FALCON_FORWARD(Function, f);
}
template <class Container, class Function>
Function recursive_for_each(Container CPP_RVALUE_OR_REFERENCE container, Function f)
{
_aux::recursive_for_each<dimension<Container>::value - 1>
::for_each(begin(container), end(container), f);
return FALCON_FORWARD(Function, f);
}
template <std::size_t Dimension, class Container, class Function>
Function recursive_for_each(Container CPP_RVALUE_OR_REFERENCE container, Function f)
{
_aux::recursive_for_each<
(Dimension == -1u ? dimension<Container>::value : Dimension) - 1
>::for_each(begin(container), end(container), f);
return FALCON_FORWARD(Function, f);
}
template<class Preface, class Function, class Postface CPP_IF_CPP11(= ignore_t)>
_aux::recursive_intermediate<Preface, Function, Postface, -1u>
recursive_intermediate(Preface CPP_RVALUE preface, Function CPP_RVALUE functor,
Postface CPP_RVALUE postface = Postface())
{
#if __cplusplus >= 201103L
return {
std::forward<Preface>(preface)
, std::forward<Function>(functor)
, std::forward<Postface>(postface)
};
#else
return _aux::recursive_intermediate<Preface, Function, Postface, -1u>(
preface, functor, postface);
#endif
}
template<std::size_t Dimension, class Preface, class Function, class Postface CPP_IF_CPP11(= ignore_t)>
_aux::recursive_intermediate<Preface, Function, Postface, Dimension>
recursive_intermediate(Preface CPP_RVALUE preface, Function CPP_RVALUE functor,
Postface CPP_RVALUE postface = Postface())
{
#if __cplusplus >= 201103L
return {
std::forward<Preface>(preface)
, std::forward<Function>(functor)
, std::forward<Postface>(postface)
};
#else
return _aux::recursive_intermediate<Preface, Function, Postface, Dimension>(
preface, functor, postface);
#endif
}
namespace _aux {
template<class Preface, class Function, class Postface, std::size_t Dimension>
struct recursive_intermediate
{
Preface preface;
Function functor;
Postface postface;
#if __cplusplus < 201103L
recursive_intermediate(Preface preface, Function functor, Postface postface)
: preface(preface)
, functor(functor)
, postface(postface)
{}
#endif
template<class Container>
void operator()(Container& v)
{
preface();
::falcon::recursive_for_each<Dimension>(v, functor);
postface();
}
};
template<class Function, class Postface, std::size_t Dimension>
struct recursive_intermediate<ignore_t, Function, Postface, Dimension>
{
Function functor;
Postface postface;
#if __cplusplus < 201103L
recursive_intermediate(const ignore_t&, Function functor, Postface postface)
: functor(functor)
, postface(postface)
{}
#endif
template<class Container>
void operator()(Container& v)
{
::falcon::recursive_for_each<Dimension>(v, functor);
postface();
}
};
template<class Preface, class Function, std::size_t Dimension>
struct recursive_intermediate<Preface, Function, ignore_t, Dimension>
{
Preface preface;
Function functor;
#if __cplusplus < 201103L
recursive_intermediate(Preface preface, Function functor, const ignore_t&)
: preface(preface)
, functor(functor)
{}
#endif
template<class Container>
void operator()(Container& v)
{
preface();
::falcon::recursive_for_each<Dimension>(v, functor);
}
};
template<class Function, std::size_t Dimension>
struct recursive_intermediate<ignore_t, Function, ignore_t, Dimension>
{
Function functor;
#if __cplusplus < 201103L
recursive_intermediate(const ignore_t&, Function functor, const ignore_t&)
: functor(functor)
{}
#endif
template<class Container>
void operator()(Container& v)
{
::falcon::recursive_for_each<Dimension>(v, functor);
}
};
}
}
#endif
| 29.240602 | 103 | 0.719294 | jonathanpoelen |
7967f4030b153b6da525d91f34be03b3ee49bf48 | 12,242 | cpp | C++ | platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp | sekodev/corona | b9a559d0cc68f5d9048444d710161fc5b778d981 | [
"MIT"
] | null | null | null | platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp | sekodev/corona | b9a559d0cc68f5d9048444d710161fc5b778d981 | [
"MIT"
] | null | null | null | platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp | sekodev/corona | b9a559d0cc68f5d9048444d710161fc5b778d981 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Core\Rtt_Build.h"
#include "Rtt_WinConnection.h"
#include "Rtt_WinPlatform.h"
#include "Rtt_WinPlatformServices.h"
#include "WinGlobalProperties.h"
#include "WinString.h"
namespace Rtt
{
#define Rtt_REGISTRY_SECTION _T("Preferences")
// These functions are used for WinPlatformServices::GetPreference() and SetPreference()
// Registry code copied from MFC Source appui3.cpp (CWinApp)
// returns key for HKEY_CURRENT_USER\"Software"\RegistryKey\ProfileName
// (or other top level key) creating it if it doesn't exist
// responsibility of the caller to call RegCloseKey() on the returned HKEY
// Modified to get registry key and profile name from WinGlobalProperties,
// initialized in CSimulatorApp::InitInstance()
static HKEY GetAppRegistryKey( HKEY hkeyTopLevel )
{
WinString strRegKey, strRegProfile;
#ifdef Rtt_NO_GUI
strRegKey.SetUTF8("Ansca Corona");
strRegProfile.SetUTF8("Corona Simulator");
#else
Rtt_ASSERT( GetWinProperties()->GetRegistryKey() != NULL);
Rtt_ASSERT( GetWinProperties()->GetRegistryProfile() != NULL);
strRegKey.SetUTF8( GetWinProperties()->GetRegistryKey() );
strRegProfile.SetUTF8( GetWinProperties()->GetRegistryProfile() );
#endif // Rtt_NO_GUI
HKEY hAppKey = NULL;
HKEY hSoftKey = NULL;
HKEY hCompanyKey = NULL;
if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("software"), 0, KEY_WRITE|KEY_READ,
&hSoftKey) == ERROR_SUCCESS)
{
DWORD dw;
if (RegCreateKeyEx(hSoftKey, strRegKey.GetTCHAR(), 0, REG_NONE,
REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
&hCompanyKey, &dw) == ERROR_SUCCESS)
{
RegCreateKeyEx(hCompanyKey, strRegProfile.GetTCHAR(), 0, REG_NONE,
REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
&hAppKey, &dw);
}
}
if (hSoftKey != NULL)
RegCloseKey(hSoftKey);
if (hCompanyKey != NULL)
RegCloseKey(hCompanyKey);
return hAppKey;
}
// returns key for:
// HKEY_CURRENT_USER\"Software"\RegistryKey\AppName\lpszSection
// creating it if it doesn't exist.
// responsibility of the caller to call RegCloseKey() on the returned HKEY
// Returns void * to avoid including windows.h before header file
static HKEY GetSectionKey(LPCTSTR lpszSection, HKEY hkeyTopLevel )
{
Rtt_ASSERT(lpszSection != NULL);
HKEY hSectionKey = NULL;
HKEY hAppKey = GetAppRegistryKey( hkeyTopLevel );
if (hAppKey == NULL)
return NULL;
DWORD dw;
RegCreateKeyEx(hAppKey, lpszSection, 0, REG_NONE,
REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL,
&hSectionKey, &dw);
RegCloseKey(hAppKey);
return hSectionKey;
}
static bool GetProfileString(
WinString *pstrValue, LPCTSTR lpszSection, LPCTSTR lpszEntry, HKEY hkeyTopLevel = HKEY_CURRENT_USER)
{
Rtt_ASSERT(lpszSection != NULL);
Rtt_ASSERT(lpszEntry != NULL);
HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel);
if (hSecKey == NULL)
{
return false;
}
DWORD dwType=REG_NONE;
DWORD dwCount=0;
LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
NULL, &dwCount);
if (lResult == ERROR_SUCCESS)
{
if( dwType == REG_SZ) // if type is string
{
// dwCount is in bytes, Expand takes # of characters and adds 1
(*pstrValue).Expand( dwCount/sizeof(TCHAR) );
lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
(LPBYTE)(*pstrValue).GetBuffer(), &dwCount);
}
}
RegCloseKey(hSecKey);
if (lResult == ERROR_SUCCESS)
{
// If we found the key, but type was not string (REG_SZ), return false
return (dwType == REG_SZ);
}
return false;
}
static BOOL WriteProfileString(
LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue, HKEY hkeyTopLevel = HKEY_CURRENT_USER)
{
Rtt_ASSERT(lpszSection != NULL);
Rtt_ASSERT(lpszEntry != NULL);
LONG lResult;
#if 0 // I don't think we want the whole section deleted by accident...
if (lpszEntry == NULL) //delete whole section
{
HKEY hAppKey = GetAppRegistryKey();
if (hAppKey == NULL)
return FALSE;
lResult = ::RegDeleteKey(hAppKey, lpszSection);
RegCloseKey(hAppKey);
}
else
#endif
if (lpszValue == NULL)
{
HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel);
if (hSecKey == NULL)
return FALSE;
// necessary to cast away const below
lResult = ::RegDeleteValue(hSecKey, (LPTSTR)lpszEntry);
RegCloseKey(hSecKey);
}
else
{
HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel);
if (hSecKey == NULL)
return FALSE;
lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_SZ,
(LPBYTE)lpszValue, (lstrlen(lpszValue)+1)*sizeof(TCHAR));
RegCloseKey(hSecKey);
}
return lResult == ERROR_SUCCESS;
}
static bool GetProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry, BYTE** ppData, UINT* pBytes)
{
Rtt_ASSERT(lpszSection != NULL);
Rtt_ASSERT(lpszEntry != NULL);
Rtt_ASSERT(ppData != NULL);
Rtt_ASSERT(pBytes != NULL);
*ppData = NULL;
*pBytes = 0;
HKEY hSecKey = GetSectionKey(lpszSection, HKEY_CURRENT_USER );
if (hSecKey == NULL)
{
return false;
}
DWORD dwType=0;
DWORD dwCount=0;
LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType, NULL, &dwCount);
*pBytes = dwCount;
if (lResult == ERROR_SUCCESS)
{
if( dwType == REG_BINARY ) // if type is binary
{
*ppData = new BYTE[*pBytes];
lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType,
*ppData, &dwCount);
}
}
RegCloseKey(hSecKey);
// If we found the key, but type was not binary, delete data and return false
if (lResult == ERROR_SUCCESS && (dwType == REG_BINARY))
{
return true;
}
else
{
delete [] *ppData;
*ppData = NULL;
}
return false;
}
static bool WriteProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPBYTE pData, UINT nBytes)
{
Rtt_ASSERT(lpszSection != NULL);
LONG lResult;
HKEY hSecKey = GetSectionKey(lpszSection, HKEY_CURRENT_USER );
if (hSecKey == NULL)
return false;
if( NULL == pData ) // delete key if pData is null
lResult = ::RegDeleteValue(hSecKey, (LPTSTR)lpszEntry);
else lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_BINARY,
pData, nBytes);
RegCloseKey(hSecKey);
return lResult == ERROR_SUCCESS;
}
static void EncryptString( const char *sSecret, BYTE **paBytes, UINT *pnBytes )
{
*paBytes = NULL;
*pnBytes = 0;
if( NULL == sSecret )
return;
DATA_BLOB unencryptedData, encryptedData;
unencryptedData.pbData = (BYTE *)sSecret;
// Save the NULL character in the data
// We need to multiply the length of the string by the
// size of the data contained therein to support multi-
// byte character sets.
unencryptedData.cbData = (strlen( sSecret ) + 1) * sizeof( sSecret[0] );
if (!CryptProtectData(
&unencryptedData,
_T("Marker"),
NULL,
NULL,
NULL,
0,
&encryptedData))
{
return;
}
// Save the encrypted data buffer in heap-allocated memory
*paBytes = new BYTE [encryptedData.cbData];
memcpy( *paBytes, encryptedData.pbData, encryptedData.cbData );
*pnBytes = encryptedData.cbData;
// clean up
LocalFree( encryptedData.pbData );
}
static bool DecryptString( WinString *pStr, BYTE *aBytes, UINT nBytes )
{
DATA_BLOB encryptedData, unencryptedData;
encryptedData.pbData = aBytes;
encryptedData.cbData = nBytes;
LPWSTR dataDescription; // Receives the description saved with data
if (!CryptUnprotectData(
&encryptedData,
&dataDescription,
NULL,
NULL,
NULL,
0,
&unencryptedData))
{
return false;
}
// And the data description string as well.
LocalFree(dataDescription);
// NOTE: Contains NULL terminator
pStr->SetUTF8( (char *)unencryptedData.pbData );
// Cleanup
LocalFree(unencryptedData.pbData);
return true;
}
WinPlatformServices::WinPlatformServices( const MPlatform& platform )
: fPlatform( platform )
{
}
const MPlatform&
WinPlatformServices::Platform() const
{
return fPlatform;
}
PlatformConnection*
WinPlatformServices::CreateConnection( const char* url ) const
{
return Rtt_NEW( & fPlatform.GetAllocator(), WinConnection( * this, url ) );
}
void
WinPlatformServices::GetPreference( const char *key, String * value ) const
{
WinString strResult, strKey;
strKey.SetUTF8( key );
bool bFound = GetProfileString( &strResult, Rtt_REGISTRY_SECTION, strKey.GetTCHAR());
if( bFound )
{
value->Set( strResult.GetUTF8() );
}
}
void
WinPlatformServices::SetPreference( const char *key, const char *value ) const
{
if ( Rtt_VERIFY( key ) )
{
WinString strKey, strValue;
strKey.SetUTF8( key );
strValue.SetUTF8( value );
WriteProfileString( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), strValue.GetTCHAR() );
}
}
void
WinPlatformServices::GetSecurePreference( const char *key, String * value ) const
{
const char *sResult = NULL;
BYTE *aBytes;
UINT nBytes;
WinString strKey;
strKey.SetUTF8( key );
bool bFound = GetProfileBinary(Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), &aBytes, &nBytes);
if( bFound )
{
WinString strResult;
if( DecryptString( &strResult, aBytes, nBytes ) )
{
value->Set( strResult.GetUTF8() );
}
}
}
bool
WinPlatformServices::SetSecurePreference( const char *key, const char *value ) const
{
bool result = false;
if ( Rtt_VERIFY( key ) )
{
BYTE *aBytes;
UINT nBytes;
EncryptString( value, &aBytes, &nBytes );
WinString strKey;
strKey.SetUTF8( key );
result = WriteProfileBinary( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), aBytes, nBytes );
if( aBytes )
delete aBytes;
}
return result;
}
void
WinPlatformServices::GetLibraryPreference( const char *key, String * value ) const
{
// Get the value from HKLM
WinString strResult, strKey;
strKey.SetUTF8( key );
bool bFound = GetProfileString( &strResult, Rtt_REGISTRY_SECTION, strKey.GetTCHAR(),
HKEY_LOCAL_MACHINE );
if( bFound )
{
value->Set( strResult.GetUTF8() );
}
}
void
WinPlatformServices::SetLibraryPreference( const char *key, const char *value ) const
{
// Set the value in HKLM
if ( Rtt_VERIFY( key ) )
{
WinString strKey, strValue;
strKey.SetUTF8( key );
strValue.SetUTF8( value );
WriteProfileString( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), strValue.GetTCHAR(),
HKEY_LOCAL_MACHINE );
}
}
// Checks for Internet connectivity.
// Returns true if the Internet is assumed available. Returns false if not.
bool
WinPlatformServices::IsInternetAvailable() const
{
MIB_IPFORWARDTABLE *pRoutingTable;
DWORD dwBufferSize = 0;
DWORD dwRowCount;
DWORD dwIndex;
DWORD dwResult;
bool bIsInternetAvailable = false;
// Fetch routing table information.
// We'll assume that the Internet is available if we can find a default route to a gateway.
GetIpForwardTable(NULL, &dwBufferSize, FALSE);
pRoutingTable = (MIB_IPFORWARDTABLE*)new BYTE[dwBufferSize];
dwResult = GetIpForwardTable(pRoutingTable, &dwBufferSize, FALSE);
if (NO_ERROR == dwResult)
{
dwRowCount = pRoutingTable->dwNumEntries;
for (dwIndex = 0; dwIndex < dwRowCount; dwIndex++)
{
// Default route designated by 0.0.0.0 in table.
if (0 == pRoutingTable->table[dwIndex].dwForwardDest)
{
bIsInternetAvailable = true;
break;
}
}
}
delete pRoutingTable;
// Return the result.
return bIsInternetAvailable;
}
bool
WinPlatformServices::IsLocalWifiAvailable() const
{
Rtt_ASSERT_NOT_IMPLEMENTED();
return false;
}
void
WinPlatformServices::Terminate() const
{
// Exit the application.
CWnd* windowPointer = ::AfxGetMainWnd();
if (windowPointer)
{
SendMessage(windowPointer->GetSafeHwnd(), WM_CLOSE, 0, 0);
}
}
void
WinPlatformServices::Sleep( int milliseconds ) const
{
if (milliseconds >= 0)
{
::Sleep( (DWORD)milliseconds );
}
}
} // namespace Rtt
| 25.772632 | 101 | 0.689103 | sekodev |
7969faa8338352043414df4fa2fec8467422614b | 20,523 | cc | C++ | src/asn1/oidc.cc | 1computerguy/mercury | 193bf6432e4f53f1253965f5ca8634bd6ca69136 | [
"BSD-2-Clause"
] | null | null | null | src/asn1/oidc.cc | 1computerguy/mercury | 193bf6432e4f53f1253965f5ca8634bd6ca69136 | [
"BSD-2-Clause"
] | null | null | null | src/asn1/oidc.cc | 1computerguy/mercury | 193bf6432e4f53f1253965f5ca8634bd6ca69136 | [
"BSD-2-Clause"
] | null | null | null | //
// oidc.cc - ASN.1 Object IDentifier Compiler
//
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <sstream>
#include <iterator>
#include <regex>
#include <unordered_map>
#include <map>
#include <set>
#include <algorithm>
void oid_print(std::vector<uint32_t> oid, const char *label) {
if (label) {
printf("%s: ", label);
}
bool first = true;
printf("{");
for (const uint32_t &i : oid) {
if (!first) {
printf(",");
} else {
first = false;
}
printf(" %d", i);
}
printf(" }\n");
}
struct char_pair { char first; char second; };
inline struct char_pair raw_to_hex(unsigned char x) {
char hex[]= "0123456789abcdef";
struct char_pair result = { hex[x >> 4], hex[x & 0x0f] };
return result;
}
inline uint8_t hex_to_raw(const char *hex) {
int value = 0;
if(*hex >= '0' && *hex <= '9') {
value = (*hex - '0');
} else if (*hex >= 'A' && *hex <= 'F') {
value = (10 + (*hex - 'A'));
} else if (*hex >= 'a' && *hex <= 'f') {
value = (10 + (*hex - 'a'));
}
value = value << 4;
hex++;
if(*hex >= '0' && *hex <= '9') {
value |= (*hex - '0');
} else if (*hex >= 'A' && *hex <= 'F') {
value |= (10 + (*hex - 'A'));
} else if (*hex >= 'a' && *hex <= 'f') {
value |= (10 + (*hex - 'a'));
}
return value;
}
std::string raw_to_hex_string(std::vector<uint8_t> v) {
std::string s;
for (const auto &x: v) {
char_pair p = raw_to_hex(x);
s.push_back(p.first);
s.push_back(p.second);
}
return s;
}
std::string raw_to_hex_array(std::vector<uint8_t> v) {
std::string s;
s.push_back('{');
bool comma = false;
for (const auto &x: v) {
if (comma) {
s.push_back(',');
} else {
comma = true;
}
s.push_back('0');
s.push_back('x');
char_pair p = raw_to_hex(x);
s.push_back(p.first);
s.push_back(p.second);
}
s.push_back('}');
return s;
}
std::vector<uint8_t> oid_to_raw_string(std::vector<uint32_t> oid) {
std::vector<uint8_t> raw;
raw.push_back(40 * oid[0] + oid[1]);
for (size_t i = 2; i < oid.size(); i++) {
uint32_t tmp = oid[i];
std::vector<uint8_t> v;
if (tmp == 0) {
v.push_back(0);
} else {
while (tmp > 0) {
uint32_t div = tmp/128;
uint32_t rem = tmp - div * 128;
v.push_back(rem);
tmp = div;
}
}
if (v.size() > 1) {
for (size_t j=v.size()-1; j>0; j--) {
raw.push_back(0x80 | v[j]);
}
}
raw.push_back(v[0]);
}
// printf("raw: ");
// for (const auto &x: raw) {
// printf("%02x", x);
// }
return raw;
}
std::string oid_to_hex_string(const std::vector<uint32_t> &oid) {
return raw_to_hex_string(oid_to_raw_string(oid));
}
std::string oid_to_hex_array(const std::vector<uint32_t> &oid) {
return raw_to_hex_array(oid_to_raw_string(oid));
}
std::vector<uint32_t> hex_string_to_oid(std::string s) {
std::vector<uint32_t> v;
if (s.size() & 1) {
return v;
}
const char *c = s.c_str();
uint32_t component = hex_to_raw(c);
uint32_t div = component / 40;
uint32_t rem = component - (div * 40);
if (div > 2 || rem > 39) {
return v; // error: invalid input
}
v.push_back(div);
v.push_back(rem);
c += 2;
component = 0;
for (unsigned int i=2; i<s.size(); i += 2) {
uint8_t tmp = hex_to_raw(c);
if (tmp & 0x80) {
component = component * 128 + (tmp & 0x7f);
} else {
component = component * 128 + tmp;
v.push_back(component);
component = 0;
}
c += 2;
}
return v;
}
void output_oid(std::vector<uint32_t> oid, const char *delimiter) {
if (oid.size() < 1) {
return; // nothing to output
}
unsigned int i = 0;
for ( ; i < oid.size() - 1; i++) {
std::cout << oid[i] << delimiter;
}
std::cout << oid[i] << '\n';
}
enum token_type {
token_unknown,
token_str,
token_num,
token_lbrace,
token_rbrace,
token_assignment,
token_comment
};
enum token_type type(const std::string &t) {
using namespace std;
regex str("[a-zA-Z_][a-zA-Z_\\-\\(\\)0-9]*");
regex num("[0-9]+");
if (t == "{") {
return token_lbrace;
} else if (t == "}") {
return token_rbrace;
} else if (t == "::=") {
return token_assignment;
} else if (t == "--") {
return token_comment;
} else if (regex_match(t, str)) {
return token_str;
} else if (regex_match(t, num)) {
return token_num;
}
return token_unknown;
}
enum assignment_type {
type_oid = 0,
type_other = 1
};
struct oid_assignment {
std::string name;
enum assignment_type type;
std::vector<uint32_t> asn_notation;
};
struct oid_set {
std::unordered_map<std::string, std::vector<uint32_t>> oid_dict;
std::unordered_map<std::string, std::vector<uint32_t>> nonterminal_oid_dict;
std::unordered_map<std::string, std::string> keyword_dict;
std::unordered_map<std::string, std::string> synonym;
std::multiset<std::string> keywords;
void dump_oid_dict_sorted();
void dump_oid_enum_dict_sorted();
void verify_oid_dict();
std::vector<uint32_t> get_vector_from_keyword(const std::string &keyword) {
auto x = oid_dict.find(keyword);
if (x != oid_dict.end()) {
return x->second;
}
auto syn = synonym.find(keyword);
if (syn != synonym.end()) {
return oid_dict[syn->second];
}
std::cerr << "error: unknown OID keyword '" << keyword << "'\n";
throw "parse error";
}
void add_oid(const std::string &name,
const std::vector<uint32_t> &v,
enum assignment_type type) {
// if 'v' is already in use as an OID, don't add anything to
// the OID set, but instead create a synonym
//
std::string oid_hex_string = oid_to_hex_string(v);
if (keyword_dict.find(oid_hex_string) != keyword_dict.end()) {
std::cerr << "note: OID ";
bool not_first = 0;
for (auto &c : v) {
if (not_first) {
std::cerr << '.';
} else {
not_first = 1;
}
std::cerr << c;
}
std::cerr << " is already in the OID set with keyword " << name;
if (keyword_dict[oid_hex_string] != name) {
std::cerr << " creating synonym for " << keyword_dict[oid_hex_string];
synonym[name] = keyword_dict[oid_hex_string];
}
std::cerr << std::endl;
return;
}
// if 'name' is already in use as a keyword, then append a
// distinct number
//
auto count = keywords.count(name);
std::string k(name);
keywords.insert(name);
if (count != 0) {
std::cerr << "note: keyword " << name << " is already in use, appending [" << count << "]" << std::endl;
k.append("[").append(std::to_string(count)).append("]");
}
// cout << "assignment: " << name << "\t" << type << endl;
oid_dict[k] = v;
if (type == type_other) {
std::cerr << "assigning synonym " << name << "\n";
}
keyword_dict[oid_to_hex_string(v)] = k;
}
void remove_nonterminals() {
for (std::pair <std::string, std::vector<uint32_t>> x : oid_dict) {
std::vector<uint32_t> v = x.second;
//std::cout << s << std::endl;
while (1) {
v.erase(v.end() - 1);
if (v.empty()) {
break;
}
std::string oid_hex_string = oid_to_hex_string(v);
const auto &o = keyword_dict.find(oid_hex_string);
if (o != keyword_dict.end()) {
//std::cout << "found in dict" << std::endl;
//nonterminal_oid_dict.insert(o);
keyword_dict.erase(o);
}
// for (auto &c : v) {
// std::cout << c << ' ';
//}
//std::cout << '\n';
}
}
}
};
struct oid_set oid_set;
void parse_asn1_line(std::list<std::string> &tokens) {
using namespace std;
regex str("[a-zA-Z][a-zA-Z\\-\\(\\)0-9]*");
regex num("[0-9]+");
regex str_with_num("(\\([0-9]*\\))");
/*
* examples of lines:
*
* id-at OBJECT IDENTIFIER ::= { joint-iso-ccitt(2) ds(5) 4 }
* id-at-name AttributeType ::= { id-at 41 }
*
* string OBJECT IDENTIFIER ::= { string+ number+ }
* string string ::= { string+ number+ }
*/
#if 0
for (auto t: tokens) {
cout << "token\t" << t << "\t";
if (regex_match(t, str)) {
cout << "is a string";
}
if (regex_match(t, num)) {
cout << "is a number";
}
if (t == "{") {
cout << "is a left brace";
} else if (t == "}") {
cout << "is a right brace";
} else if (t == "::=") {
cout << "is an assignment operator";
} else if (t == "--") {
cout << "is a comment";
}
if (type(t) == token_unknown) {
cout << "UNKNOWN TOKEN";
}
cout << "\n";
}
#endif
struct oid_assignment assignment;
std::list<std::string>::const_iterator t = tokens.begin();
if (type(*t) == token_comment) {
return;
}
if (type(*t) == token_str) {
assignment.name = *t;
} else {
cout << "error: expected string, got '" << *t << "'\n";
throw "parse error";
}
++t;
string category_name;
if (type(*t) == token_str) {
if (*t == "OBJECT") {
++t;
if (type(*t) == token_str && *t == "IDENTIFIER") {
assignment.type = type_oid;
}
} else {
assignment.type = type_other;
category_name = *t;
}
} else if (type(*t) == token_assignment) {
++t;
if (type(*t) == token_str && *t == "OBJECT") {
++t;
if (type(*t) == token_str && *t == "IDENTIFIER") {
assignment.type = type_oid;
} else {
throw "parse error";
}
} else {
return;
}
cout << assignment.name << " is a synonym for OBJECT IDENTIFIER\n";
return;
} else {
cout << "error: expected OBJECT IDENTIFIER or ::=, got '" << *t << "'\n";
throw "parse error";
}
++t;
if (type(*t) != token_assignment) {
cout << "error: expected '::=', got '" << *t << "'\n";
throw "parse error";
}
++t;
if (type(*t) != token_lbrace) {
cout << "error: expected '{', got '" << *t << "'\n";
throw "parse error";
}
++t;
while (type(*t) != token_rbrace) {
// cout << "got token " << *t << endl;
if (type(*t) == token_str) {
smatch string_match;
if (regex_search(*t, string_match, str_with_num)) {
string s = string_match.str(1);
// cout << "got str_with_num " << s << endl;
uint32_t component = stoi(s.substr(1, s.size() - 2));
// cout << "component " << component << endl;
assignment.asn_notation.push_back(component);
} else {
std::vector<uint32_t> x = oid_set.get_vector_from_keyword(*t);
for (uint32_t &component: x) {
assignment.asn_notation.push_back(component);
}
}
} else if (type(*t) == token_num) {
assignment.asn_notation.push_back(stoi(*t));
}
++t;
}
oid_set.add_oid(assignment.name, assignment.asn_notation, assignment.type);
}
int paren_balance(const char *s) {
int balance = 0;
while (*s != 0 && *s != '\n') {
// std::cout << *s;
switch(*s) {
case '{':
balance++;
break;
case '}':
balance--;
break;
default:
break;
}
s++;
}
// std::cout << "balance: " << balance << "\n";
return balance;
}
void parse_asn1_file(const char *filename) {
using namespace std;
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t nread;
stream = fopen(filename, "r");
if (stream == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
size_t balance = 0;
list<string> statement;
while ((nread = getline(&line, &len, stream)) != -1) {
// printf("got line of length %zu:\n", nread);
// fwrite(line, nread, 1, stdout);
string word;
istringstream iss(line, istringstream::in);
//while( iss >> word ) {
// cout << word << endl;
//}
list<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
balance += paren_balance(line);
statement.splice(statement.end(), tokens);
if (balance == 0 && statement.size() > 0) {
// cout << "parsing balanced line\n";
// for (auto x: statement) {
// cout << x << endl;
// }
parse_asn1_line(statement);
statement.clear();
} else {
// cout << "line is unbalanced (" << balance << ")\n";
}
}
fclose(stream);
}
void oid_set::dump_oid_dict_sorted() {
using namespace std;
struct pair_cmp {
inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) {
return (s1.second < s2.second);
}
};
vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end());
sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp());
cout << "std::unordered_map<std::basic_string<uint8_t>, std::string> oid_dict = {\n";
for (pair <string, vector<uint32_t>> x : ordered_dict) {
cout << "\t{ " << oid_to_hex_array(x.second) << ", \"" << x.first << "\" },\n";
}
cout << "};\n";
}
void oid_set::dump_oid_enum_dict_sorted() {
using namespace std;
struct pair_cmp {
inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) {
return (s1.second < s2.second);
}
};
vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end());
sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp());
cout << "std::unordered_map<std::basic_string<uint8_t>, std::string> oid_dict = {\n";
for (pair <string, vector<uint32_t>> x : ordered_dict) {
cout << "\t{ " << oid_to_hex_array(x.second) << ", \"" << x.first << "\" },\n";
}
cout << "};\n";
cout << "enum oid {\n";
unsigned int oid_num = 0;
cout << "\t" << "unknown" << " = " << oid_num++ << ",\n";
for (pair <string, vector<uint32_t>> x : ordered_dict) {
std::string tmp_string(x.first);
std::replace(tmp_string.begin(), tmp_string.end(), '-', '_');
std::replace(tmp_string.begin(), tmp_string.end(), '[', '_');
std::replace(tmp_string.begin(), tmp_string.end(), ']', '_');
cout << "\t" << tmp_string << " = " << oid_num << ",\n";
//const auto &syn = synonym.find(x.first);
//if (syn != synonym.end()) {
// std::cerr << syn->second << " is a synonym for " << x.first << std::endl;
// std::string tmp_string2(syn->second);
// std::replace(tmp_string2.begin(), tmp_string2.end(), '-', '_');
// std::replace(tmp_string2.begin(), tmp_string2.end(), '[', '_');
// std::replace(tmp_string2.begin(), tmp_string2.end(), ']', '_');
// cout << "\t" << tmp_string2 << " = " << oid_num << ",\n";
//}
oid_num++;
}
cout << "};\n";
cout << "std::unordered_map<std::basic_string<uint8_t>, enum oid> oid_to_enum = {\n";
for (pair <string, vector<uint32_t>> x : ordered_dict) {
std::string tmp_string(x.first);
std::replace(tmp_string.begin(), tmp_string.end(), '-', '_');
std::replace(tmp_string.begin(), tmp_string.end(), '[', '_');
std::replace(tmp_string.begin(), tmp_string.end(), ']', '_');
cout << "\t{ " << oid_to_hex_array(x.second) << ", " << tmp_string << " },\n";
}
cout << "};\n";
}
void oid_set::verify_oid_dict() {
using namespace std;
struct pair_cmp {
inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) {
return (s1.second < s2.second);
}
};
vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end());
sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp());
for (pair <string, vector<uint32_t>> x : ordered_dict) {
string s = oid_to_hex_string(x.second);
vector<uint32_t> v = hex_string_to_oid(s);
if (v != x.second) {
cout << "error with oid " << oid_to_hex_string(x.second) << "\n";
auto iv = v.begin();
auto ix = x.second.begin();
while (iv != v.end() || ix != x.second.end()) {
if (iv != v.end()) {
cout << "v: " << *iv;
if (*iv != *ix) {
cout << "\t***";
}
cout << endl;
iv++;
}
if (ix != x.second.end()) {
cout << "x: " << *ix << endl;
ix++;
}
}
}
}
}
int main(int argc, char *argv[]) {
using namespace std;
#if 0
auto unknown_oids =
{
"2a8648ce3d030107",
"2b81040022",
"2b0e03021d",
"2a864886f70d01010b",
"2a864886f70d01090f",
"2a864886f70d010914",
"2b0601040182371402",
"2b0601040182371501",
"2b0601040182371502",
"2b0601040182371507",
"2b060104018237150a",
"2b0601040182373c020101",
"2b0601040182373c020102",
"2b0601040182373c020103",
"2b060104018237540101",
"2b06010401d04701028245",
"2b06010401d679020402",
"2b06010505070101",
"2b06010505070103",
"550409",
"55040c",
"55040f",
"550411",
"55042a",
"550461",
"551d01",
"551d07",
"551d0a",
"551d10",
"551d11",
"551d12",
"551d13",
"551d1e",
"551d1f",
"551d20",
"551d23",
"6086480186f8420101",
"6086480186f8420103",
"6086480186f8420104",
"6086480186f842010c",
"6086480186f842010d"
};
for (auto &hexstring : unknown_oids) {
cout << hexstring << '\t';
auto v = hex_string_to_oid(hexstring);
const char *delimeter = ".";
output_oid(v, delimeter);
}
#endif /* 0 */
if (argc < 2) {
fprintf(stderr, "Usage: %s <file> [<file2> ... ]\n", argv[0]);
exit(EXIT_FAILURE);
}
for (int i=1; i<argc; i++) {
// cerr << "reading file " << argv[i] << endl;
parse_asn1_file(argv[i]);
}
#if 0
cout << "dictionary dump:" << endl;
for (pair <string, vector<uint32_t>> x : oid_dict) {
cout << x.first << " = { ";
for (auto c: x.second) {
cout << c << " ";
}
cout << "}\t";
cout << oid_to_hex_string(x.second) << endl;
}
cout << endl;
for (pair <string, vector<uint32_t>> x : oid_dict) {
cout << oid_to_hex_string(x.second) << "\t\t" << x.first << endl;
}
#endif
oid_set.remove_nonterminals();
oid_set.dump_oid_enum_dict_sorted();
// oid_set.verify_oid_dict();
// for (auto &x : oid_set.keyword_dict) {
// cout << x.first << "\t" << x.second << endl;
// }
return 0;
}
| 28.036885 | 117 | 0.489694 | 1computerguy |
796c39e81409a53f2ec85d3123a382684bb29c4b | 907 | cpp | C++ | src/medTest/medTestApplication.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | src/medTest/medTestApplication.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | src/medTest/medTestApplication.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medTestApplication.h>
#include <stdexcept>
medTestApplication::medTestApplication ( int & argc, char ** argv )
: QCoreApplication(argc, argv)
{
}
medTestApplication::~medTestApplication()
{
}
//static
void medTestApplication::CheckTestResult( bool condition, const char *cond, const char *file, const int line /*= 0*/ )
{
if (!condition) {
QString msg = QString("%1(%2): Test failed (%3)").arg(file).arg(line).arg(cond);
throw std::runtime_error(msg.toStdString());
}
}
| 23.868421 | 118 | 0.585447 | papadop |
79711981a6ebb023671dcaad360a7ecd25dc4056 | 3,995 | cpp | C++ | speedcc/stage/SCBehaviorCocos.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 7 | 2018-03-10T02:01:49.000Z | 2021-09-14T15:42:10.000Z | speedcc/stage/SCBehaviorCocos.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | null | null | null | speedcc/stage/SCBehaviorCocos.cpp | kevinwu1024/SpeedCC | 7b32e3444236d8aebf8198ebc3fede8faf201dee | [
"MIT"
] | 1 | 2018-03-10T02:01:58.000Z | 2018-03-10T02:01:58.000Z | /****************************************************************************
Copyright (c) 2017-2020 Kevin Wu (Wu Feng)
github: http://github.com/kevinwu1024
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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 NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "SCBehaviorCocos.h"
#include "../cocos/SCViewController.h"
#include "../cocos/SCViewControllerLog.h"
#include "../system/SCSystem.h"
NAMESPACE_SPEEDCC_BEGIN
///--------------- SCBehaviorViewGoto
SCBehaviorViewGoto::~SCBehaviorViewGoto()
{
}
SCBehaviorViewGoto::SCBehaviorViewGoto(const SCViewNavigator::SSceneSwitchInfo& swi,const SCDictionary& dic)
:_switch(swi)
,_parameterDic(dic)
,_bDirect(false)
{
}
void SCBehaviorViewGoto::execute(const SCDictionary& par)
{
SC_RETURN_V_IF(!this->getActive());
if(_bDirect)
{
this->onBvrFunc();
}
else if(_ptrDelayBvr==nullptr)
{
auto ptr = SCBehaviorCallFunc::create(SC_MAKE_FUNC(onBvrFunc, this));
_ptrDelayBvr = SCBehaviorDelayExecute::create(0, ptr);
_ptrDelayBvr->addObject(this->makeObjPtr(this)); // keep this instance alive
_ptrDelayBvr->execute(par);
}
}
void SCBehaviorViewGoto::setSceneParameter(const SCDictionary& dic)
{
_parameterDic = dic;
}
void SCBehaviorViewGoto::onBvrFunc()
{
SCViewNav()->setSceneParameter(_parameterDic);
SCViewNav()->gotoView(_switch);
_ptrDelayBvr->frameRetain(); // instance keep alive in current frame
_ptrDelayBvr = nullptr;
}
///--------------- SCBehaviorViewBack
void SCBehaviorViewBack::execute(const SCDictionary& par)
{
SC_RETURN_V_IF(!this->getActive());
if(_bDirect)
{
this->onBvrFunc();
}
else if(_ptrDelayBvr==nullptr)
{
auto ptr = SCBehaviorCallFunc::create(SC_MAKE_FUNC(onBvrFunc, this));
_ptrDelayBvr = SCBehaviorDelayExecute::create(0, ptr);
_ptrDelayBvr->addObject(this->makeObjPtr(this));
_ptrDelayBvr->execute(par);
}
}
void SCBehaviorViewBack::onBvrFunc()
{
SCViewNavigator::getInstance()->back(_nSceneNum);
_ptrDelayBvr->frameRetain(); // instance keep alive in current frame
_ptrDelayBvr = nullptr;
}
///--------------- SCBehaviorAlertBoxSelected
SCBehaviorAlertBoxSelected::SCBehaviorAlertBoxSelected()
:_pController(nullptr)
,_nSelected(0)
{
}
SCBehaviorAlertBoxSelected::SCBehaviorAlertBoxSelected(SCViewController* pController,const int nSelected)
:_pController(pController)
,_nSelected(nSelected)
{
}
void SCBehaviorAlertBoxSelected::setController(SCViewController* pController)
{
_pController = pController;
}
void SCBehaviorAlertBoxSelected::setSelectedIndex(const int nSelectedIndex)
{
_nSelected = nSelectedIndex;
}
void SCBehaviorAlertBoxSelected::execute(const SCDictionary& par)
{
SC_RETURN_V_IF(!this->getActive());
if(_pController!=nullptr)
{
SCBehaviorViewBack::create()->execute();
_pController->finish(SC_NUM_2_PVOID(_nSelected));
}
}
///----------- SCBehaviorShowLog
SCBehaviorShowLog::SCBehaviorShowLog()
{
}
SCBehaviorShowLog::~SCBehaviorShowLog()
{
}
void SCBehaviorShowLog::execute(const SCDictionary& par)
{
SC_RETURN_V_IF(!this->getActive());
SCBehaviorViewGoto::create<SCViewControllerLog>(SCViewNavigator::kLayerModal)->execute();
}
NAMESPACE_SPEEDCC_END
| 27.176871 | 108 | 0.690363 | kevinwu1024 |
7971b7f0d66aee308f86c5e4f098c13ae18881ff | 2,189 | cpp | C++ | examples/pangomm/measure-text-pixel-size-simple-example.cpp | zhanglin-wu/cairomm-pangomm-on-linux-docker | aaec738fdd35c4540173e40d8203c022d36155d2 | [
"BSD-3-Clause"
] | null | null | null | examples/pangomm/measure-text-pixel-size-simple-example.cpp | zhanglin-wu/cairomm-pangomm-on-linux-docker | aaec738fdd35c4540173e40d8203c022d36155d2 | [
"BSD-3-Clause"
] | null | null | null | examples/pangomm/measure-text-pixel-size-simple-example.cpp | zhanglin-wu/cairomm-pangomm-on-linux-docker | aaec738fdd35c4540173e40d8203c022d36155d2 | [
"BSD-3-Clause"
] | null | null | null |
// apt-get install libpangomm-1.4-dev -y
// mkdir -p build && cd build
// g++ -g -Wall -o measure-text-pixel-size-simple-example `pkg-config --cflags cairomm-1.0 pangomm-1.4` ../measure-text-pixel-size-simple-example.cpp `pkg-config --libs cairomm-1.0 pangomm-1.4`
#include <sstream>
#include <iostream>
#include <glibmm.h>
#include <string>
#include <pangomm.h>
#include <pangomm/fontdescription.h>
#include <pangomm/item.h>
#include <pangomm/glyphstring.h>
#include <cairomm/cairomm.h>
#include <pangomm.h>
#include <pangomm/init.h>
int main() {
Pango::init();
auto surf = Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 600, 800);
auto cr = Cairo::Context::create(surf);
cr->set_source_rgb(0.5, 0.7, 0.5);
cr->paint();
cr->move_to(0.0, 0.0);
cr->set_source_rgb(1.0, 1.0, 1.0);
auto layout = Pango::Layout::create(cr);
// auto font = Glib::ustring("OpenSansEmoji");
// Pango::FontDescription desc(font);
// std::cout << std::endl << desc.get_family() << std::endl;
// layout->set_font_description(desc);
// Glib::ustring text = Glib::locale_to_utf8("好人");
// auto text = Glib::ustring("Hello World!\n\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82");
// auto text = Glib::ustring("Hello World!");
auto text = Glib::ustring("\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82");
// auto text = Glib::ustring("\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82\n\n\xE2\x9A\xA1\xF0\x9F\x99\x82\xE2\x9A\xA1\xF0\x9F\x99\x82");
// auto text = Glib::ustring("\xE4\xB8\xAD");
// text = Glib::ustring("\xE5\x9B\xBD");
// text = Glib::ustring("\xE2\x9A\xA1");
// text = Glib::ustring("\xF0\x9F\x99\x82");
layout->set_text(text);
layout->update_from_cairo_context(cr);
layout->show_in_cairo_context(cr);
// Measure the text
int text_width;
int text_height;
layout->get_pixel_size(text_width, text_height);
std::stringstream ss;
ss << "\n(" << text_width << ", " << text_height << ")\n";
cr->move_to(10, 50);
layout->set_text(ss.str());
layout->update_from_cairo_context(cr);
layout->show_in_cairo_context(cr);
surf->write_to_png("measure-text-pixel-size-simple-example.png");
return 0;
}
| 32.671642 | 193 | 0.669255 | zhanglin-wu |
7974ef528620669111c7a8fd717287e38ccbdd65 | 51,002 | hpp | C++ | dsp/L1/include/aie/fir_interpolate_asym.hpp | dycz0fx/Vitis_Libraries | d3fc414b552493657101ddb5245f24528720823d | [
"Apache-2.0"
] | 1 | 2021-09-11T01:05:01.000Z | 2021-09-11T01:05:01.000Z | dsp/L1/include/aie/fir_interpolate_asym.hpp | maxpark/Vitis_Libraries | 4bd100518d93a8842d1678046ad7457f94eb355c | [
"Apache-2.0"
] | null | null | null | dsp/L1/include/aie/fir_interpolate_asym.hpp | maxpark/Vitis_Libraries | 4bd100518d93a8842d1678046ad7457f94eb355c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Xilinx, 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.
*/
#ifndef FIR_INTERPOLATE_ASYM_HPP
#define FIR_INTERPOLATE_ASYM_HPP
/*
Interpolating FIR class definition
The file holds the definition of the Asymmetric Interpolation FIR kernel class.
Note on Coefficient reversal. The AIE processor intrinsics naturally sum data and coefficients in the same order,
but the conventional definition of a FIR has data and coefficient indices in opposite order. The order of
coefficients is therefore reversed during construction to yield conventional FIR behaviour.
*/
/* Coding conventions
TT_ template type suffix
TP_ template parameter suffix
*/
#include <adf.h>
#include <assert.h>
#include <array>
#include <cstdint>
#include "fir_utils.hpp"
#include "fir_interpolate_asym_traits.hpp"
// CEIL rounds x up to the next multiple of y, which may be x itself.
#define CEIL(x, y) (((x + y - 1) / y) * y)
namespace xf {
namespace dsp {
namespace aie {
namespace fir {
namespace interpolate_asym {
//#define _DSPLIB_FIR_INTERPOLATE_ASYM_HPP_DEBUG_
//-----------------------------------------------------------------------------------------------------
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
bool TP_CASC_IN = CASC_IN_FALSE,
bool TP_CASC_OUT = CASC_OUT_FALSE,
unsigned int TP_FIR_RANGE_LEN = TP_FIR_LEN,
unsigned int TP_KERNEL_POSITION = 0,
unsigned int TP_CASC_LEN = 1,
unsigned int TP_USE_COEFF_RELOAD = 0,
unsigned int TP_NUM_OUTPUTS = 1>
class kernelFilterClass {
private:
// Two implementations have been written for this filter. They have identical behaviour, but one is optimised for an
// Interpolation factor
// greater than the number of accumulator registers available.
static constexpr unsigned int kArchIncr = 1;
static constexpr unsigned int kArchPhaseSeries = 2;
static constexpr unsigned int kArchPhaseParallel = 3;
// Parameter value defensive and legality checks
static_assert(TP_FIR_LEN <= FIR_LEN_MAX, "ERROR: Max supported FIR length exceeded. ");
static_assert(TP_FIR_RANGE_LEN >= FIR_LEN_MIN,
"ERROR: Illegal combination of design FIR length and cascade length, resulting in kernel FIR length "
"below minimum required value. ");
static_assert(TP_SHIFT >= SHIFT_MIN && TP_SHIFT <= SHIFT_MAX, "ERROR: SHIFT is out of the supported range.");
static_assert(TP_RND >= ROUND_MIN && TP_RND <= ROUND_MAX, "ERROR: RND is out of the supported range.");
static_assert((TP_FIR_LEN % TP_INTERPOLATE_FACTOR) == 0,
"ERROR: TP_FIR_LEN must be an integer multiple of INTERPOLATE_FACTOR.");
static_assert(fnEnumType<TT_DATA>() != enumUnknownType, "ERROR: TT_DATA is not a supported type.");
static_assert(fnEnumType<TT_COEFF>() != enumUnknownType, "ERROR: TT_COEFF is not a supported type.");
static_assert(fnTypeCheckDataCoeffSize<TT_DATA, TT_COEFF>() != 0,
"ERROR: TT_DATA type less precise than TT_COEFF is not supported.");
static_assert(fnTypeCheckDataCoeffCmplx<TT_DATA, TT_COEFF>() != 0,
"ERROR: real TT_DATA with complex TT_COEFF is not supported.");
static_assert(fnTypeCheckDataCoeffFltInt<TT_DATA, TT_COEFF>() != 0,
"ERROR: a mix of float and integer types of TT_DATA and TT_COEFF is not supported.");
//
static_assert(TP_INTERPOLATE_FACTOR >= INTERPOLATE_FACTOR_MIN && TP_INTERPOLATE_FACTOR <= INTERPOLATE_FACTOR_MAX,
"ERROR: TP_INTERPOLATE_FACTOR is out of the supported range");
static_assert(fnUnsupportedTypeCombo<TT_DATA, TT_COEFF>() != 0,
"ERROR: The combination of TT_DATA and TT_COEFF is not supported for this class.");
static_assert(TP_NUM_OUTPUTS > 0 && TP_NUM_OUTPUTS <= 2, "ERROR: only single or dual outputs are supported.");
// There are additional defensive checks after architectural constants have been calculated.
// The interpolation FIR calculates over multiple phases where such that the total number of lanes is an integer
// multiple of the
// interpolation factor. Hence an array of accumulators is needed for this set of lanes.
static constexpr unsigned int m_kNumAccRegs = fnAccRegsIntAsym<TT_DATA, TT_COEFF>();
static constexpr unsigned int m_kWinAccessByteSize =
16; // 16 Bytes. The memory data path is min 128-bits wide for vector operations
static constexpr unsigned int m_kColumns =
sizeof(TT_COEFF) == 2 ? 2 : 1; // number of mult-adds per lane for main intrinsic
static constexpr unsigned int m_kLanes = fnNumLanesIntAsym<TT_DATA, TT_COEFF>(); // number of operations in parallel
// of this type combinations that
// the vector processor can do.
static constexpr unsigned int m_kVOutSize =
fnVOutSizeIntAsym<TT_DATA, TT_COEFF>(); // This differs from kLanes for cint32/cint32
static constexpr unsigned int m_kDataLoadsInReg = 4; // ratio of 1024-bit data buffer to 256-bit load size.
static constexpr unsigned int m_kDataLoadVsize =
(32 / sizeof(TT_DATA)); // number of samples in a single 256-bit load
static constexpr unsigned int m_kSamplesInBuff = m_kDataLoadsInReg * m_kDataLoadVsize;
// static constexpr unsigned int m_kSamplesInBuff = 0;
static constexpr unsigned int m_kFirRangeOffset =
fnFirRangeOffset<TP_FIR_LEN, TP_CASC_LEN, TP_KERNEL_POSITION, TP_INTERPOLATE_FACTOR>() /
TP_INTERPOLATE_FACTOR; // FIR Cascade Offset for this kernel position
static constexpr unsigned int m_kFirMarginLen = TP_FIR_LEN / TP_INTERPOLATE_FACTOR;
static constexpr unsigned int m_kFirMarginOffset =
fnFirMargin<m_kFirMarginLen, TT_DATA>() - m_kFirMarginLen + 1; // FIR Margin Offset.
static constexpr unsigned int m_kFirInitOffset = m_kFirRangeOffset + m_kFirMarginOffset;
static constexpr unsigned int m_kDataWindowOffset =
TRUNC((m_kFirInitOffset), (m_kWinAccessByteSize / sizeof(TT_DATA))); // Window offset - increments by 128bit
static constexpr unsigned int m_kDataBuffXOffset =
m_kFirInitOffset % (m_kWinAccessByteSize / sizeof(TT_DATA)); // Remainder of m_kFirInitOffset divided by 128bit
// In some cases, the number of accumulators needed exceeds the number available in the processor leading to
// inefficency as the
// accumulators are loaded and stored on the stack. An alternative implementation is used to avoid this.
static constexpr unsigned int m_kArch =
(((m_kDataBuffXOffset + TP_FIR_RANGE_LEN + m_kLanes * m_kDataLoadVsize / m_kVOutSize) <= m_kSamplesInBuff) &&
(TP_INPUT_WINDOW_VSIZE % (m_kLanes * m_kDataLoadsInReg) == 0))
? kArchIncr
: // execute incremental load architecture
kArchPhaseSeries; // execute each phase in series (reloads data)
static constexpr unsigned int m_kZbuffSize = 32;
static constexpr unsigned int m_kCoeffRegVsize = m_kZbuffSize / sizeof(TT_COEFF);
static constexpr unsigned int m_kTotalLanes =
fnLCMIntAsym<TT_DATA, TT_COEFF, TP_INTERPOLATE_FACTOR>(); // Lowest common multiple of Lanes and
// Interpolatefactor
static constexpr unsigned int m_kLCMPhases = m_kTotalLanes / m_kLanes;
static constexpr unsigned int m_kPhases = TP_INTERPOLATE_FACTOR;
static constexpr unsigned int m_kNumOps = CEIL(TP_FIR_RANGE_LEN / TP_INTERPOLATE_FACTOR, m_kColumns) / m_kColumns;
static constexpr unsigned int m_kXbuffSize = 128; // data buffer size in Bytes
static constexpr unsigned int m_kDataRegVsize = m_kXbuffSize / sizeof(TT_DATA); // samples in data buffer
static constexpr unsigned int m_kLsize = TP_INPUT_WINDOW_VSIZE / m_kLanes; // loops required to consume input
static constexpr unsigned int m_kInitialLoads =
(m_kDataBuffXOffset + (m_kPhases * m_kLanes + m_kVOutSize) / TP_INTERPOLATE_FACTOR + m_kColumns - 1 +
(m_kLanes - 1)) /
m_kLanes; // effectively ceil[(kVOutsize+m_kColumns-1)/kLanes]
static constexpr unsigned int m_kInitialLoadsIncr =
CEIL(m_kDataBuffXOffset + TP_FIR_RANGE_LEN + m_kLanes * m_kDataLoadVsize / m_kVOutSize - 1, m_kDataLoadVsize) /
m_kDataLoadVsize;
static constexpr unsigned int m_kRepeatFactor = m_kDataLoadsInReg * m_kDataLoadVsize / m_kVOutSize;
// Additional defensive checks
static_assert(TP_INPUT_WINDOW_VSIZE % m_kLanes == 0,
"ERROR: TP_INPUT_WINDOW_VSIZE must be an integer multiple of the number of lanes for this data type");
// The m_internalTaps is defined in terms of samples, but loaded into a vector, so has to be memory-aligned to the
// vector size.
TT_COEFF chess_storage(% chess_alignof(v16int16)) m_internalTaps[m_kLCMPhases][m_kNumOps][m_kColumns][m_kLanes];
// Two implementations have been written for this filter. They have identical behaviour, but one is optimised for an
// Interpolation factor
// greater than the number of accumulator registers available.
void filter_impl1(T_inputIF<TP_CASC_IN, TT_DATA> inInterface,
T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Each phase is calculated in turn which avoids
// need for multiple accumulators, but requires
// data reloading.
void filter_impl2(
T_inputIF<TP_CASC_IN, TT_DATA> inInterface,
T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Parallel phase execution, requires multiple accumulators
void filterIncr(
T_inputIF<TP_CASC_IN, TT_DATA> inInterface,
T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Incremental load architecture which applies for short FIR_LEN
void filterSelectArch(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface);
// Constants for coeff reload
static constexpr unsigned int m_kCoeffLoadSize = 256 / 8 / sizeof(TT_COEFF);
TT_COEFF chess_storage(% chess_alignof(v8cint16))
m_oldInTaps[CEIL(TP_FIR_LEN, m_kCoeffLoadSize)]; // Previous user input coefficients with zero padding
bool m_coeffnEq; // Are coefficients sets equal?
public:
// Access function for AIE Synthesizer
static unsigned int get_m_kArch() { return m_kArch; };
// Constructors
kernelFilterClass() : m_oldInTaps{} {}
kernelFilterClass(const TT_COEFF (&taps)[TP_FIR_LEN]) {
// Loads taps/coefficients
firReload(taps);
};
void firReload(const TT_COEFF* taps) {
TT_COEFF* tapsPtr = (TT_COEFF*)taps;
firReload(tapsPtr);
}
void firReload(TT_COEFF* taps) {
const unsigned int bitsInNibble = 4;
// Since the intrinsics can have columns, any values in memory beyond the end of the taps array could
// contaminate the calculation.
// To avoid this hazard, the class has its own taps array which is zero-padded to the column width for the type
// of coefficient.
int tapIndex;
// Coefficients are pre-arranged such that during filter execution they may simply be read from a lookup table.
for (int phase = 0; phase < m_kLCMPhases; ++phase) {
for (int op = 0; op < m_kNumOps; ++op) {
for (int column = 0; column < m_kColumns; ++column) {
for (int lane = 0; lane < m_kLanes; ++lane) {
tapIndex = TP_INTERPOLATE_FACTOR - 1 -
((lane + phase * m_kLanes) % TP_INTERPOLATE_FACTOR) + // datum index of lane
(column * TP_INTERPOLATE_FACTOR) + // column offset is additive
((op * m_kColumns * TP_INTERPOLATE_FACTOR));
if (tapIndex < TP_FIR_RANGE_LEN && tapIndex >= 0) {
tapIndex = TP_FIR_LEN - 1 - tapIndex -
fnFirRangeOffset<TP_FIR_LEN, TP_CASC_LEN, TP_KERNEL_POSITION,
TP_INTERPOLATE_FACTOR>(); // Reverse coefficients and apply
// cascade range offset. See note at
// head of file.
m_internalTaps[phase][op][column][lane] = taps[tapIndex];
} else {
m_internalTaps[phase][op][column][lane] = nullElem<TT_COEFF>(); // 0 for the type.
}
}
}
}
}
};
// Filter kernel for static coefficient designs
void filterKernel(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface);
// Filter kernel for reloadable coefficient designs
void filterKernel(T_inputIF<TP_CASC_IN, TT_DATA> inInterface,
T_outputIF<TP_CASC_OUT, TT_DATA> outInterface,
const TT_COEFF (&inTaps)[TP_FIR_LEN]);
void filterKernelRtp(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface);
};
//-----------------------------------------------------------------------------------------------------
// Cascade layer class and specializations
//-----------------------------------------------------------------------------------------------------
// This is the main declaration of the fir_interpolate_asym class, and is also used for the Standalone kernel
// specialization with no cascade ports, no reload, single output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
bool TP_CASC_IN = CASC_IN_FALSE,
bool TP_CASC_OUT = CASC_OUT_FALSE,
unsigned int TP_FIR_RANGE_LEN = TP_FIR_LEN,
unsigned int TP_KERNEL_POSITION = 0,
unsigned int TP_CASC_LEN = 1,
unsigned int TP_USE_COEFF_RELOAD = 0, // 1 = use coeff reload, 0 = don't use coeff reload
unsigned int TP_NUM_OUTPUTS = 1>
class fir_interpolate_asym : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_LEN,
0,
1,
USE_COEFF_RELOAD_FALSE,
TP_NUM_OUTPUTS> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_LEN,
0,
1,
USE_COEFF_RELOAD_FALSE>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* restrict outWindow);
};
// Single kernel specialization. No cascade ports, with reload coefficients.
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
2> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
2> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_LEN,
0,
1,
USE_COEFF_RELOAD_FALSE,
2>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
output_window<TT_DATA>* restrict outWindow,
output_window<TT_DATA>* restrict outWindow2);
};
//-----------------------------------------------------------------------------------------------------
// Single kernel specialization. No cascade ports, with reload coefficients, single output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_LEN,
0,
1,
USE_COEFF_RELOAD_TRUE,
1>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
output_window<TT_DATA>* outWindow,
const TT_COEFF (&inTaps)[TP_FIR_LEN]);
};
// Single kernel specialization. No cascade ports, with reload coefficients, dual output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
2> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
2> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_FALSE,
TP_FIR_LEN,
0,
1,
USE_COEFF_RELOAD_TRUE,
2>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
output_window<TT_DATA>* outWindow,
output_window<TT_DATA>* outWindow2,
const TT_COEFF (&inTaps)[TP_FIR_LEN]);
};
//-----------------------------------------------------------------------------------------------------
// Partially specialized classes for cascaded interface (final kernel in cascade), no reload, single output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
input_stream_cacc48* inCascade,
output_window<TT_DATA>* restrict outWindow);
};
// Partially specialized classes for cascaded interface (final kernel in cascade), no reload, dual output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
2> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
2> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
2>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
input_stream_cacc48* inCascade,
output_window<TT_DATA>* restrict outWindow,
output_window<TT_DATA>* restrict outWindow2);
};
// Partially specialized classes for cascaded interface (final kernel in cascade), with reload, single output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_window<TT_DATA>* outWindow);
// output_window<TT_DATA>* restrict outWindow,
// const TT_COEFF (&inTaps)[TP_FIR_LEN]);
};
// Partially specialized classes for cascaded interface (final kernel in cascade), with reload, dual output
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
2> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
2> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_FALSE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
2>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
input_stream_cacc48* inCascade,
output_window<TT_DATA>* outWindow,
output_window<TT_DATA>* outWindow2);
// output_window<TT_DATA>* restrict outWindow,
// const TT_COEFF (&inTaps)[TP_FIR_LEN]);
};
//-----------------------------------------------------------------------------------------------------
// Partially specialized classes for cascaded interface (First kernel in cascade), no reload
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
output_stream_cacc48* outCascade,
output_window<TT_DATA>* broadcastWindow);
};
// Partially specialized classes for cascaded interface (First kernel in cascade), with reload
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_FALSE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
output_stream_cacc48* outCascade,
output_window<TT_DATA>* broadcastWindow,
const TT_COEFF (&inTaps)[TP_FIR_LEN]);
};
//-----------------------------------------------------------------------------------------------------
// Partially specialized classes for cascaded interface (middle kernels in cascade), no reload
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1> {
private:
public:
// Constructor
fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN])
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_FALSE,
1>(taps) {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
input_stream_cacc48* inCascade,
output_stream_cacc48* outCascade,
output_window<TT_DATA>* broadcastWindow);
};
// Partially specialized classes for cascaded interface (middle kernels in cascade), with reload
template <typename TT_DATA,
typename TT_COEFF,
unsigned int TP_FIR_LEN,
unsigned int TP_INTERPOLATE_FACTOR,
unsigned int TP_SHIFT,
unsigned int TP_RND,
unsigned int TP_INPUT_WINDOW_VSIZE,
unsigned int TP_FIR_RANGE_LEN,
unsigned int TP_KERNEL_POSITION,
unsigned int TP_CASC_LEN>
class fir_interpolate_asym<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> : public kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1> {
private:
public:
// Constructor
fir_interpolate_asym()
: kernelFilterClass<TT_DATA,
TT_COEFF,
TP_FIR_LEN,
TP_INTERPOLATE_FACTOR,
TP_SHIFT,
TP_RND,
TP_INPUT_WINDOW_VSIZE,
CASC_IN_TRUE,
CASC_OUT_TRUE,
TP_FIR_RANGE_LEN,
TP_KERNEL_POSITION,
TP_CASC_LEN,
USE_COEFF_RELOAD_TRUE,
1>() {}
// Register Kernel Class
static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); }
// FIR
void filter(input_window<TT_DATA>* inWindow,
input_stream_cacc48* inCascade,
output_stream_cacc48* outCascade,
output_window<TT_DATA>* broadcastWindow);
};
}
}
}
}
} // namespaces
#endif // fir_interpolate_asym_HPP
| 48.619638 | 120 | 0.463707 | dycz0fx |
7976518cf1e1d347ad3a55b752376b017a912b9f | 234 | cpp | C++ | RandomQuestions/001.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | RandomQuestions/001.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | RandomQuestions/001.cpp | harveyc95/ProgrammingProblems | d81dc58de0347fa155f5e25f27d3d426ce13cdc6 | [
"MIT"
] | null | null | null | // 1. Round a number to the next largest multiple of 16
#include <iostream>
int round_to_largest_16(int x) {
return (x & 0xF) ? ((x >> 4 << 4) + 16) : x;
}
int main () {
std::cout<<round_to_largest_16(30)<<std::endl;
return 0;
} | 19.5 | 55 | 0.628205 | harveyc95 |
797ac146c506afa27bc1836f6f6a83824b660c4b | 1,340 | cpp | C++ | poj/p2983_fucking.cpp | huanghongxun/ACM | b7595bbe6c0d82ceb271e81fca3e787dc4060a55 | [
"Unlicense"
] | 3 | 2018-06-05T13:57:13.000Z | 2020-08-05T14:19:02.000Z | poj/p2983_fucking.cpp | huanghongxun/ACM | b7595bbe6c0d82ceb271e81fca3e787dc4060a55 | [
"Unlicense"
] | null | null | null | poj/p2983_fucking.cpp | huanghongxun/ACM | b7595bbe6c0d82ceb271e81fca3e787dc4060a55 | [
"Unlicense"
] | null | null | null | #include <cstdio>
#include <cstring>
#define FOR(i,j,k) for(i=j;i<=k;i++)
const int N=1001,M=201000,inf=10000000;
int dis[N], vis[N], cnt[N];
int edge, n, m;
int head[N], next[M], to[M], wei[M], q[M];
inline bool spfa() {
int u,i,f=0,r=0;
FOR(i,0,n) vis[i]=cnt[i]=0,dis[i]=inf;
vis[0] = 1; dis[0] = 0; q[r++]=0;
while(f<r) {
u=q[f++]; vis[u]=0;
for(i=head[u];i!=-1;i=next[i])
if (dis[to[i]]>dis[u]+wei[i]) {
dis[to[i]]=dis[u]+wei[i];
if(!vis[to[i]]) {
vis[to[i]]=1;
q[r++]=to[i];
if(++cnt[to[i]]>n) return 0;
}
}
}
return 1;
}
inline void add(int u, int v, int w) {
to[edge]=v; wei[edge]=w; next[edge]=head[u]; head[u]=edge++;
}
int main() {
char ch[5];
int i,u,v,w;
while(scanf("%d%d",&n,&m)!=EOF) {
edge=0;
memset(head,-1,sizeof head);
FOR(i,1,m) {
scanf("%s",ch);
if(ch[0] == 'P') {
scanf("%d%d%d",&u,&v,&w);
add(v,u,w);
add(u,v,-w);
} else {
scanf("%d%d",&u,&v);
add(u,v,-1);
}
}
FOR(i,1,n) add(0,i,0);
if(!spfa()) printf("Unreliable\n");
else printf("Reliable\n");
}
return 0;
}
| 25.769231 | 64 | 0.4 | huanghongxun |
797c72447f93a0bbddb17cc3907cd1059127dff0 | 2,420 | cpp | C++ | m07/Pr16-1a_catch_types.cpp | dvcchern/CS200 | 333df210e70757da7cec481314b1a1e734fd03ed | [
"MIT"
] | 4 | 2020-02-14T23:54:05.000Z | 2022-01-30T18:29:06.000Z | m07/Pr16-1a_catch_types.cpp | dvcchern/CS200 | 333df210e70757da7cec481314b1a1e734fd03ed | [
"MIT"
] | null | null | null | m07/Pr16-1a_catch_types.cpp | dvcchern/CS200 | 333df210e70757da7cec481314b1a1e734fd03ed | [
"MIT"
] | 6 | 2020-02-24T07:06:47.000Z | 2022-02-03T02:46:46.000Z | //__________________________________________
// throw primitive types ...
#include <iostream>
#include <stdexcept> // for runtime_error
#include <string>
using namespace std;
int main() {
string choice, word, text; // User input for choices and input
auto menu = [] ( ) {
cout << "_______ Throw Primitive Types __________\n"
<< " m - menu\n"
<< " c - c_str\n"
<< " i - integer\n"
<< " f - float\n"
<< " s - string\n"
<< " u - undefined (double)\n"
<< " q - Quit\n"; };
menu();
string s("Worse");
int i=123;
float f=1.23;
double d=4.56;
const char *c = "foo bar";
bool stay = true;
while(stay) { // Main menu while starts
cout << " Enter your choice: ";
cin >> choice; // Take in user choice from menu
cin.ignore();
char ch = choice[0];
try {
switch(ch) { // menu switch start
case 'b': case 'B': // break out of loop
stay = false; break;
case 'c': case 'C': // c_str
throw("Bad"); break;
case 'i': case 'I': // integer
throw(123); break;
case 'f': case 'F': // float;
throw(f); break;
case 's': case 'S': // string
throw(s); break;
case 'm': case 'M':
menu(); break;
case 'r': case 'R':
throw runtime_error("Catastrophe");
break;
case 'u': case 'U': // undefined (double)
throw(d); break;
case 'q': case 'Q': // quit
stay = false; break;
default: // Invalid! Tells user to try again
cout << "\nInvalid command!\nTry again!\n\n";
}
} // end of try block
catch ( runtime_error &e ) { cout << e.what () << '\n'; }
catch (int i) { cout << i << '\n'; }
catch (float f) { cout << f << '\n'; }
catch (const char *e) { cout << e << '\n'; }
catch (string e) { cout << e << '\n'; }
catch (...) { cout << "some unknown exception.\n"; }
} // end of while
cout << "\nProgram exit!";
} | 31.025641 | 67 | 0.416116 | dvcchern |
797c73cc34365ed4dc4839424cc59b0cb06e4d07 | 2,213 | cpp | C++ | tests/test_data_loading.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | null | null | null | tests/test_data_loading.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | 1 | 2021-11-29T14:03:20.000Z | 2021-11-29T14:03:20.000Z | tests/test_data_loading.cpp | TobiasRp/mray | d59bb110c97c7f0a7263981ca0050132220f2688 | [
"MIT"
] | null | null | null | // Copyright (c) 2020, Tobias Rapp
// 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 Karlsruhe Institute of Technology nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h"
#include "regular_grid_loader.h"
#include "particle_loader.h"
TEST(test_data_loading, grid_test)
{
RegularGridLoader rgl("../../data/simple_volume.nc");
ASSERT_EQ(rgl.num_steps(), 5);
auto grid2 = rgl.get(2, "s");
ASSERT_EQ(grid2.get(0, 0, 0), 2);
ASSERT_EQ(grid2.sample(Vec3f(0.01f, 0.51f, 0.99f)), 2);
ASSERT_EQ(grid2.sample(Vec3f(-1.1f, 1.1f, 2.1f)), 2);
}
TEST(test_data_loading, particle_test)
{
ParticleLoader pl("../../data/ABC.h5part");
ASSERT_EQ(pl.num_steps(), 10);
auto p2 = pl.get(2, "u", 0.1f);
ASSERT_EQ(p2.size(), 17576);
} | 46.104167 | 87 | 0.729327 | TobiasRp |
797d6cc72e76b9b5dfdfa7de28f480987c8a673d | 206 | cpp | C++ | CppStrangeIoC/framework/context/icontext.cpp | AndreySkyFoxSidorov/CppStrangeIoC | cae0953ec4a1fce838d7c138153d4279d3fb2c4b | [
"Apache-2.0"
] | 2 | 2018-06-06T11:26:48.000Z | 2019-04-11T14:05:42.000Z | CppStrangeIoC/framework/context/icontext.cpp | AndreySkyFoxSidorov/CppStrangeIoC | cae0953ec4a1fce838d7c138153d4279d3fb2c4b | [
"Apache-2.0"
] | null | null | null | CppStrangeIoC/framework/context/icontext.cpp | AndreySkyFoxSidorov/CppStrangeIoC | cae0953ec4a1fce838d7c138153d4279d3fb2c4b | [
"Apache-2.0"
] | 2 | 2018-06-06T11:26:49.000Z | 2021-07-26T03:43:16.000Z | #include "IContext.h"
using namespace strange::framework::api;
using namespace strange::extensions::dispatcher::api;
namespace strange
{
namespace extensions
{
namespace context
{
namespace api
{
}
}
}
}
| 12.117647 | 53 | 0.757282 | AndreySkyFoxSidorov |
797f505532498773f395f24d9b664e3b2fd4cfbd | 1,016 | hpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#ifndef GUI_DEFINES_HPP
#define GUI_DEFINES_HPP
#include <touchgfx/hal/HAL.hpp>
class Defines
{
public:
enum MainMenuType
{
ANIMATING_BUTTONS_MENU = 0,
CAROUSEL_MENU,
NO_MENU
};
enum DemoID
{
GAME2048 = 0,
GAME2D,
CONTROLS,
AUDIO_PLAYER,
HOME_AUTOMATION,
SETTINGS,
VIDEO_PLAYER,
NUMBER_OF_DEMO_SCREENS,
NO_DEMO_SCREEN
};
};
#endif /* GUI_DEFINES_HPP */
| 20.734694 | 80 | 0.526575 | ramkumarkoppu |
7982bc247455564c345cae3863b9ae57b12b7957 | 9,354 | cpp | C++ | OverlordEngine/DebugRenderer.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | 1 | 2018-11-28T12:30:13.000Z | 2018-11-28T12:30:13.000Z | OverlordEngine/DebugRenderer.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | null | null | null | OverlordEngine/DebugRenderer.cpp | Ruvah/Overlord-Editor | 3193b4986b10edb0fa8fdbc493ee3b05fdea217d | [
"Apache-2.0"
] | 2 | 2019-12-28T12:34:51.000Z | 2021-03-08T08:37:33.000Z | #include "stdafx.h"
#include "DebugRenderer.h"
#include "Logger.h"
#include "ContentManager.h"
ID3DX11Effect* DebugRenderer::m_pEffect = nullptr;
ID3DX11EffectTechnique* DebugRenderer::m_pTechnique = nullptr;
unsigned int DebugRenderer::m_BufferSize = 100;
ID3D11Buffer* DebugRenderer::m_pVertexBuffer = nullptr;
physx::PxScene* DebugRenderer::m_pPhysxDebugScene = nullptr;
ID3D11InputLayout* DebugRenderer::m_pInputLayout = nullptr;
ID3DX11EffectMatrixVariable* DebugRenderer::m_pWvpVariable = nullptr;
std::vector<VertexPosCol> DebugRenderer::m_LineList = std::vector<VertexPosCol>();
std::vector<VertexPosCol> DebugRenderer::m_FixedLineList = std::vector<VertexPosCol>();
unsigned int DebugRenderer::m_FixedBufferSize = 0;
bool DebugRenderer::m_RendererEnabled = true;
void DebugRenderer::Release()
{
SafeRelease(m_pInputLayout);
SafeRelease(m_pVertexBuffer);
}
void DebugRenderer::InitRenderer(ID3D11Device *pDevice, unsigned int bufferSize)
{
m_BufferSize = bufferSize;
// TODO: paths shouldn't be hard coded.
m_pEffect = ContentManager::Load<ID3DX11Effect>(L"./Resources/Effects/DebugRenderer.fx");
m_pTechnique = m_pEffect->GetTechniqueByIndex(0);
m_pWvpVariable = m_pEffect->GetVariableBySemantic("WORLDVIEWPROJECTION")->AsMatrix();
if(!m_pWvpVariable->IsValid())
Logger::LogWarning(L"Debug Renderer: Invalid Shader Variable! (WVP)");
//Input Layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
};
D3DX11_PASS_DESC passDesc;
m_pTechnique->GetPassByIndex(0)->GetDesc(&passDesc);
pDevice->CreateInputLayout(layout, 2, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_pInputLayout);
CreateFixedLineList();
CreateVertexBuffer(pDevice);
}
void DebugRenderer::CreateVertexBuffer(ID3D11Device *pDevice)
{
SafeRelease(m_pVertexBuffer);
//Vertexbuffer
D3D11_BUFFER_DESC buffDesc;
buffDesc.Usage = D3D11_USAGE_DYNAMIC;
buffDesc.ByteWidth = sizeof(VertexPosCol) * (m_BufferSize + m_FixedBufferSize);
buffDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buffDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
buffDesc.MiscFlags = 0;
pDevice->CreateBuffer(&buffDesc,nullptr,&m_pVertexBuffer);
if(m_FixedBufferSize > 0)
{
//Map Fixed data manually
ID3D11DeviceContext* pDeviceContext;
pDevice->GetImmediateContext(&pDeviceContext);
D3D11_MAPPED_SUBRESOURCE mappedResource;
pDeviceContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
memcpy(mappedResource.pData, &m_FixedLineList[0], sizeof(VertexPosCol) * m_FixedBufferSize);
pDeviceContext->Unmap(m_pVertexBuffer, 0);
pDeviceContext->Release();
}
}
void DebugRenderer::CreateFixedLineList()
{
//*GRID*
const unsigned int numGridLines = 20;
const float gridSpacing = 1.0f;
const float startOffset = -(static_cast<int>(numGridLines)/2)*gridSpacing;
const float size = (numGridLines - 1) * gridSpacing;
const auto gridColor = static_cast<DirectX::XMFLOAT4>(DirectX::Colors::LightGray);
for(unsigned int i = 0; i < numGridLines; ++i)
{
//VERTICAL
const float lineOffset = startOffset + gridSpacing * i;
auto vertStart = DirectX::XMFLOAT3(startOffset, 0, lineOffset);
m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor));
vertStart.x += size;
m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor));
//HORIZONTAL
vertStart = DirectX::XMFLOAT3(lineOffset, 0, startOffset);
m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor));
vertStart.z += size;
m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor));
}
//*AXIS
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed)));
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(30,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed)));
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen)));
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,30,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen)));
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue)));
m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,30), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue)));
//@END!
m_FixedBufferSize = m_FixedLineList.size();
}
void DebugRenderer::ToggleDebugRenderer()
{
m_RendererEnabled = !m_RendererEnabled;
}
void DebugRenderer::DrawLine(DirectX::XMFLOAT3 start, DirectX::XMFLOAT3 end, DirectX::XMFLOAT4 color)
{
if(!m_RendererEnabled)
return;
m_LineList.emplace_back(VertexPosCol(start, color));
m_LineList.emplace_back(VertexPosCol(end, color));
}
void DebugRenderer::DrawLine(DirectX::XMFLOAT3 start, DirectX::XMFLOAT4 colorStart, DirectX::XMFLOAT3 end, DirectX::XMFLOAT4 colorEnd)
{
if(!m_RendererEnabled)
return;
m_LineList.emplace_back(VertexPosCol(start, colorStart));
m_LineList.emplace_back(VertexPosCol(end, colorEnd));
}
void DebugRenderer::DrawPhysX(physx::PxScene* pScene)
{
if(!m_RendererEnabled)
return;
//m_pPhysxDebugScene = pScene;
const auto pxDebugRenderer = &pScene->getRenderBuffer();
const auto debugLines = pxDebugRenderer->getLines();
for(unsigned int i = 0; i < pxDebugRenderer->getNbLines(); ++i)
{
const auto line = debugLines[i];
DrawLine(DirectX::XMFLOAT3(line.pos0.x, line.pos0.y, line.pos0.z),ConvertPxColor(line.color0), DirectX::XMFLOAT3(line.pos1.x, line.pos1.y, line.pos1.z),ConvertPxColor(line.color1));
}
}
DirectX::XMFLOAT4 DebugRenderer::ConvertPxColor(physx::PxU32 color)
{
//TODO: Check performance, Bitshift+divide vs switch
// Alex: maybe check implementation design too.
switch(color)
{
case 0xFF000000:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Black);
case 0xFFFF0000:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Red);
case 0xFF00FF00:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Green);
case 0xFF0000FF:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Blue);
case 0xFFFFFF00:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Yellow);
case 0xFFFF00FF:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Magenta);
case 0xFF00FFFF:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Cyan);
case 0xFFFFFFFF:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::White);
case 0xFF808080:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Gray);
case 0x88880000:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed);
case 0x88008800:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen);
case 0x88000088:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue);
default:
return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Black);
}
}
void DebugRenderer::Draw(const GameContext& gameContext)
{
if(!m_RendererEnabled)
return;
//PhysX RenderBuffer
unsigned int pxBuffSize = 0;
const physx::PxRenderBuffer* pPxRenderBuffer = nullptr;
if (m_pPhysxDebugScene)
{
pPxRenderBuffer = &m_pPhysxDebugScene->getRenderBuffer();
pxBuffSize = pPxRenderBuffer->getNbLines(); //PxDebugLine == 2* VertexPosCol
m_pPhysxDebugScene = nullptr;
}
//Current Size (DebugDraw + PhysXDraw)
const unsigned int regularSize = m_LineList.size();
const unsigned int dynamicSize = regularSize + pxBuffSize;
//Total size
const unsigned int totalSize = dynamicSize + m_FixedBufferSize;
if(totalSize <= 0)
return;
if(dynamicSize > m_BufferSize)
{
Logger::LogInfo(L"DebugRenderer::Draw() > Increasing Vertexbuffer Size!");
m_BufferSize = dynamicSize;
CreateVertexBuffer(gameContext.pDevice);
}
auto pDevContext = gameContext.pDeviceContext;
if(dynamicSize>0)
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
pDevContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
if (regularSize > 0)
{
memcpy(&(static_cast<VertexPosCol*>(mappedResource.pData)[m_FixedBufferSize]), &m_LineList[0], sizeof(VertexPosCol) * regularSize); //Engine Lines
}
if (pxBuffSize > 0)
{
auto lineBuffer = pPxRenderBuffer->getLines();
memcpy(&(static_cast<VertexPosCol*>(mappedResource.pData)[m_FixedBufferSize + regularSize]), &lineBuffer, sizeof(VertexPosCol) * pxBuffSize); //PhysX Lines
}
pDevContext->Unmap(m_pVertexBuffer, 0);
}
//Set Render Pipeline
pDevContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
unsigned int stride = sizeof(VertexPosCol);
unsigned int offset = 0;
pDevContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset);
pDevContext->IASetInputLayout(m_pInputLayout);
auto viewProj = gameContext.pCamera->GetViewProjection();
const DirectX::XMMATRIX wvp = DirectX::XMMatrixIdentity() * XMLoadFloat4x4(&viewProj);
DirectX::XMFLOAT4X4 wvpConverted;
XMStoreFloat4x4( &wvpConverted, wvp);
m_pWvpVariable->SetMatrix(reinterpret_cast<float*>(&wvpConverted));
D3DX11_TECHNIQUE_DESC techDesc;
m_pTechnique->GetDesc(&techDesc);
for(unsigned int i = 0; i < techDesc.Passes; ++i)
{
m_pTechnique->GetPassByIndex(i)->Apply(0, pDevContext);
pDevContext->Draw(totalSize, 0);
}
m_LineList.clear();
}
| 34.773234 | 183 | 0.770579 | Ruvah |
798316b442b839d46205c4851fa721d580d0d971 | 4,737 | cpp | C++ | cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cpdp/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cpdp::V20190820::Model;
using namespace std;
QueryOpenBankDailyReceiptDownloadUrlResult::QueryOpenBankDailyReceiptDownloadUrlResult() :
m_downloadUrlHasBeenSet(false),
m_expireTimeHasBeenSet(false),
m_receiptStatusHasBeenSet(false)
{
}
CoreInternalOutcome QueryOpenBankDailyReceiptDownloadUrlResult::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("DownloadUrl") && !value["DownloadUrl"].IsNull())
{
if (!value["DownloadUrl"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.DownloadUrl` IsString=false incorrectly").SetRequestId(requestId));
}
m_downloadUrl = string(value["DownloadUrl"].GetString());
m_downloadUrlHasBeenSet = true;
}
if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull())
{
if (!value["ExpireTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.ExpireTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_expireTime = string(value["ExpireTime"].GetString());
m_expireTimeHasBeenSet = true;
}
if (value.HasMember("ReceiptStatus") && !value["ReceiptStatus"].IsNull())
{
if (!value["ReceiptStatus"].IsString())
{
return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.ReceiptStatus` IsString=false incorrectly").SetRequestId(requestId));
}
m_receiptStatus = string(value["ReceiptStatus"].GetString());
m_receiptStatusHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void QueryOpenBankDailyReceiptDownloadUrlResult::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_downloadUrlHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DownloadUrl";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_downloadUrl.c_str(), allocator).Move(), allocator);
}
if (m_expireTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExpireTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_expireTime.c_str(), allocator).Move(), allocator);
}
if (m_receiptStatusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ReceiptStatus";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_receiptStatus.c_str(), allocator).Move(), allocator);
}
}
string QueryOpenBankDailyReceiptDownloadUrlResult::GetDownloadUrl() const
{
return m_downloadUrl;
}
void QueryOpenBankDailyReceiptDownloadUrlResult::SetDownloadUrl(const string& _downloadUrl)
{
m_downloadUrl = _downloadUrl;
m_downloadUrlHasBeenSet = true;
}
bool QueryOpenBankDailyReceiptDownloadUrlResult::DownloadUrlHasBeenSet() const
{
return m_downloadUrlHasBeenSet;
}
string QueryOpenBankDailyReceiptDownloadUrlResult::GetExpireTime() const
{
return m_expireTime;
}
void QueryOpenBankDailyReceiptDownloadUrlResult::SetExpireTime(const string& _expireTime)
{
m_expireTime = _expireTime;
m_expireTimeHasBeenSet = true;
}
bool QueryOpenBankDailyReceiptDownloadUrlResult::ExpireTimeHasBeenSet() const
{
return m_expireTimeHasBeenSet;
}
string QueryOpenBankDailyReceiptDownloadUrlResult::GetReceiptStatus() const
{
return m_receiptStatus;
}
void QueryOpenBankDailyReceiptDownloadUrlResult::SetReceiptStatus(const string& _receiptStatus)
{
m_receiptStatus = _receiptStatus;
m_receiptStatusHasBeenSet = true;
}
bool QueryOpenBankDailyReceiptDownloadUrlResult::ReceiptStatusHasBeenSet() const
{
return m_receiptStatusHasBeenSet;
}
| 32.22449 | 174 | 0.735487 | suluner |
79852cac7b2c8ae6cf2d3c08f2c8e96e430b4b61 | 1,041 | cpp | C++ | osrf_testing_tools_cpp/src/memory_tools/memory_tools.cpp | eboasson/osrf_testing_tools_cpp | 1869beaee97ccf2fc820950d05cc508a9a15590d | [
"MIT"
] | 24 | 2018-05-16T09:36:23.000Z | 2021-05-24T11:18:22.000Z | osrf_testing_tools_cpp/src/memory_tools/memory_tools.cpp | eboasson/osrf_testing_tools_cpp | 1869beaee97ccf2fc820950d05cc508a9a15590d | [
"MIT"
] | 59 | 2018-05-23T20:56:09.000Z | 2022-02-06T11:03:59.000Z | osrf_testing_tools_cpp/src/memory_tools/memory_tools.cpp | eboasson/osrf_testing_tools_cpp | 1869beaee97ccf2fc820950d05cc508a9a15590d | [
"MIT"
] | 22 | 2018-06-12T16:10:26.000Z | 2022-02-06T10:54:38.000Z | // Copyright 2015 Open Source Robotics Foundation, 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.
#if defined(__linux__) && !defined(__ANDROID__)
#include "./impl/linux.cpp"
#include "./impl/unix_common.cpp"
#elif defined(__APPLE__)
#include "./impl/apple.cpp"
#include "./impl/unix_common.cpp"
// #elif defined(_WIN32)
// TODO(wjwwood): install custom malloc (and others) for Windows.
#else
#include "./impl/unsupported_os.cpp"
#endif // if defined(__linux__) elif defined(__APPLE__) elif defined(_WIN32) else ...
| 30.617647 | 86 | 0.735831 | eboasson |
798556c70d2ecd19f9baafd5d61c3e305160d27f | 2,469 | cpp | C++ | Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp | CaioMS2000/Meus-projetos | 190c987514503125a36d688302eaa738b5f346e4 | [
"MIT"
] | null | null | null | Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp | CaioMS2000/Meus-projetos | 190c987514503125a36d688302eaa738b5f346e4 | [
"MIT"
] | null | null | null | Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp | CaioMS2000/Meus-projetos | 190c987514503125a36d688302eaa738b5f346e4 | [
"MIT"
] | null | null | null | #include "pessoafisica.h"
namespace Caio{
PessoaFisica::PessoaFisica():
Cliente(),
cpf(""),
nome(""),
celular("")
{
}
PessoaFisica::PessoaFisica(QString &log, QString &s, QString &c, QString &e, QString &t, QString &em, QString &cpf, QString &nome, QString &celular):
Cliente(log, s, c, e, t, em, "PF"),
cpf(cpf),
nome(nome),
celular(celular)
{
}
bool PessoaFisica::validarCPF(QString &ref)
{
string s(ref.toStdString());
int digitos[11];
if(s.size() != 11){ return false; }
else if(s == "00000000000" || s == "99999999999"){ return false; }
else{
for(unsigned long long x=0; x<11; x++)
if(isdigit(s[x]) == false){ return false;}
for(unsigned long long x=0; x<11; x++)
digitos[x]=(int)s[x]-48;
int pd=0;
bool validarpd=false;
for(int x=0, m=10; x<9; x++, m--)
pd+=digitos[x]*m;
pd=pd%11;
if(pd<2)
pd=0;
else pd=11-pd;
int sd=0;
bool validarsd=false;
int x=0, m=11;
for(; x<9; x++, m--){
sd+=digitos[x]*m;
}
sd+=pd*m;
sd=sd%11;
if(sd<2)
sd=0;
else sd=11-sd;
if(digitos[9]==pd)
validarpd=true;
if(digitos[10]==sd)
validarsd=true;
if(validarpd==true && validarsd==true){
return true;
}
else
return false;
}
}
QString PessoaFisica::toString() const
{
QString str("Nome: "+nome+"\nCodigo: "+codigo+"\nCPF: "+cpf+"\nLogradouro: "+logradouro+"\nSetor: "+setor+"\nCidade: "+cidade+"\nEstado: "+estado+"\nTelefone: "+telefone+"\nCelular: "+celular+"\nEmail: "+email);
return str;
//falta adicionar coisa
}
string PessoaFisica::registro() const
{
string s("pf;"+logradouro.toStdString()+';'+setor.toStdString()+';'+cidade.toStdString()+';'+estado.toStdString()+';'+telefone.toStdString()+';'+email.toStdString()+';'+cpf.toStdString()+';'+nome.toStdString()+';'+celular.toStdString());
return s;
}
}//namespace
| 28.709302 | 242 | 0.45565 | CaioMS2000 |
79890f70142c21ba0a3fcc6d4cdeced2a9663ade | 5,551 | cpp | C++ | OpenGL/text_ttf/freetype-wrap/wft2.cpp | bigov/daft-lib | 7890fdba0aab800022ab9afb958946bd06779f33 | [
"MIT"
] | 1 | 2022-03-14T08:20:58.000Z | 2022-03-14T08:20:58.000Z | OpenGL/text_ttf/freetype-wrap/wft2.cpp | bigov/daft-lib | 7890fdba0aab800022ab9afb958946bd06779f33 | [
"MIT"
] | null | null | null | OpenGL/text_ttf/freetype-wrap/wft2.cpp | bigov/daft-lib | 7890fdba0aab800022ab9afb958946bd06779f33 | [
"MIT"
] | 1 | 2020-12-22T08:36:48.000Z | 2020-12-22T08:36:48.000Z | #include "wft2.hpp"
namespace tr {
///
/// \brief string2unicode
/// \param Text
/// \return Unicode vector
///
std::vector<uint32_t> string2unicode(const std::string& Text)
{
std::vector<uint32_t> Result {};
for(size_t i = 0; i < Text.size();)
{
unsigned int a=Text[i++];
//if((a&0x80)==0);
if((a&0xE0)==0xC0){
a=(a&0x1F)<<6;
a|=Text[i++]&0x3F;
}else if((a&0xF0)==0xE0){
a=(a&0xF)<<12;
a|=(Text[i++]&0x3F)<<6;
a|=Text[i++]&0x3F;
}else if((a&0xF8)==0xF0){
a=(a&0x7)<<18;
a|=(a&0x3F)<<12;
a|=(Text[i++]&0x3F)<<6;
a|=Text[i++]&0x3F;
}
Result.push_back(a);
}
return Result;
}
///
/// \brief wft::wft
///
wft_lib::wft_lib(void)
{
FT_Error error = FT_Init_FreeType(&FtLib);
if (error) std::cerr << "FT_Init_FreeType() failed" << std::endl;
}
///
/// \brief wft_face::wft_face
/// \param library
/// \param filename
///
wft_face::wft_face(const char *filename, int face_index)
{
FT_Error error = FT_New_Face(wFtLib, filename, face_index, &FtFace);
if (error) std::cerr << "FT_New_Face() failed" << std::endl;
}
///
/// \brief wft_face::set_pixel_size
/// \param w
/// \param h
///
void wft_face::set_pixel_size(FT_UInt w, FT_UInt h)
{
FT_Error error = FT_Set_Pixel_Sizes(FtFace, w, h);
if(error) std::cerr << "FT_Set_Pixel_Sizes() failed" << std::endl;
}
///
/// \brief wft_face::get_kerning
/// \param leftCharcode
/// \param rightCharcode
/// \return Кернинг двух символов
///
int wft_face::get_kerning(uint32_t char_first, uint32_t char_second, FT_UInt kern_mode)
{
if(char_first == 0) return 0;
FT_UInt IndexFirst = FT_Get_Char_Index(FtFace, char_first);
FT_UInt IndexSecond = FT_Get_Char_Index(FtFace, char_second);
FT_Vector delta {};
FT_Error error = FT_Get_Kerning(FtFace, IndexFirst, IndexSecond, kern_mode, &delta);
if( error ) std::cerr << std::endl << __PRETTY_FUNCTION__ << std::endl
<< "FT_Get_Kerning(FtFace, IndexFirst, IndexSecond, FT_KERNING_DEFAULT, &delta) failed"
<< std::endl;
return delta.x >> 6; // x в формате 26.6, поэтому сдвигаем результат
}
///
/// \brief image::image
/// \param Bitmap
///
mask_bits::mask_bits(const FT_Face& F)
{
width = F->glyph->bitmap.width;
height = F->glyph->bitmap.rows;
top = F->glyph->bitmap_top;
left = F->glyph->bitmap_left;
Bits.resize(width * height, 0xFF);
memcpy(Bits.data(), F->glyph->bitmap.buffer, Bits.size());
}
///
/// \brief paint_over
/// \param Src
/// \param Dst
/// \param x
/// \param y
///
void paint_over(const mask_bits& Src, mask_bits& Dst, int x, int y)
{
if((Src.width + x > Dst.width ) || (Src.height + y > Dst.height ))
{
std::cerr << std::endl << __PRETTY_FUNCTION__ << std::endl
<< "ERROR: (Src.width + x > Dst.width ) || (Src.height + y > Dst.height )" << std::endl;
return;
}
unsigned int i = 0; // число скопированных пикселей
unsigned int i_max = Src.height * Src.width; // сумма пикселей источника, которые надо скопировать
unsigned int src_row_start = 0; // индекс в начале строки источника
unsigned int dst_row_start = x + y * Dst.width; // индекс начального пикселя приемника
while(i < i_max)
{
unsigned int row_n = Src.width;
unsigned int dst = dst_row_start;
unsigned int src = src_row_start;
while(row_n > 0)
{
Dst.Bits[dst] = Src.Bits[src];
dst += 1;
src += 1;
row_n -= 1;
i += 1;
}
src_row_start += Src.width; // переход на начало следующей строки источника
dst_row_start += Dst.width; // переход на начало следующей строки приемника
}
}
///
/// \brief wft_face::get_symbol
/// \param symbol_code
/// \return
///
mask_bits wft_face::get_symbol(uint32_t symbol_code)
{
FT_Error error = FT_Load_Char(FtFace, symbol_code, FT_LOAD_RENDER);
if( error )
{
std::cerr << std::endl << __PRETTY_FUNCTION__ << std::endl
<< "FT_Load_Char(FtFace, symbol_code, FT_LOAD_RENDER) failed" << std::endl;
return mask_bits {};
}
mask_bits Result {FtFace};
Result.symbol_uncode = symbol_code;
return Result;
}
///
/// \brief wft_face::get_symbols_row
/// \param TextUnicode
/// \return
///
mask_bits wft_face::make_bitmap_text(const std::string& Text)
{
std::vector<uint32_t> TextUnicode = string2unicode(Text);
mask_bits Result {};
std::vector<mask_bits> TmpArray {};
for(auto s: TextUnicode)
{
TmpArray.push_back(get_symbol(s));
Result.height = std::max(Result.height, TmpArray.back().height);
Result.width += TmpArray.back().width + TmpArray.back().left;
auto ts = TmpArray.size();
if(ts > 1)
{
Result.width += get_kerning(TmpArray[ts - 2].symbol_uncode, TmpArray[ts - 1].symbol_uncode);
// Обработка пробелов
if(TmpArray[ts - 2].width == 0)
{
TmpArray.back().left += TmpArray.back().width;
Result.width += TmpArray.back().left;
}
}
// Здесь назначение .top меняется - тут это максимальное смещение нижней границы
Result.top = std::max(Result.top, TmpArray.back().height - TmpArray.back().top);
}
Result.height += Result.top;
Result.Bits.resize(Result.width * Result.height, 0x00);
int x = 0;
uint32_t prev_symbol_unicode = 0;
for(auto& M: TmpArray)
{
x += M.left + get_kerning(prev_symbol_unicode, M.symbol_uncode);
paint_over(M, Result, x, Result.height - M.top - Result.top);
x += M.width;
}
return Result;
}
} // namespace tr
| 25.004505 | 117 | 0.62241 | bigov |
798b9477c4b0b8495021039105638641728d73fa | 18,531 | hpp | C++ | include/pfs/io/unix_socket.hpp | semenovf/io-lib | 6e008d0eac584194333f055c90d4810f0bbb74f6 | [
"MIT"
] | null | null | null | include/pfs/io/unix_socket.hpp | semenovf/io-lib | 6e008d0eac584194333f055c90d4810f0bbb74f6 | [
"MIT"
] | null | null | null | include/pfs/io/unix_socket.hpp | semenovf/io-lib | 6e008d0eac584194333f055c90d4810f0bbb74f6 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019 Vladislav Trifochkin
//
// This file is part of [pfs-io](https://github.com/semenovf/pfs-io) library.
//
// Changelog:
// 2019.10.16 Initial version
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "unix_file.hpp"
#include <vector>
#include <cassert>
#include <cstring>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
namespace pfs {
namespace io {
namespace unix_ns {
struct host_address
{
union {
sockaddr_in addr4;
sockaddr_in6 addr6;
} addr;
host_address ()
{
std::memset(& addr, 0, sizeof(addr));
}
};
inline void swap (host_address & a, host_address & b)
{
host_address tmp;
auto addlen = sizeof(tmp.addr);
std::memcpy(& tmp.addr, & a.addr, addlen);
std::memcpy(& a.addr, & b.addr, addlen);
std::memcpy(& b.addr, & tmp.addr, addlen);
}
namespace socket {
inline bool has_pending_data (device_handle * h)
{
char buf[1];
ssize_t n = recvfrom(h->fd, buf, 1, MSG_PEEK, nullptr, nullptr);
return n > 0;
}
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
inline ssize_t read (device_handle * h
, char * bytes
, size_t n
, error_code & ec) noexcept
{
ssize_t rc = recv(h->fd, bytes, n, 0);
if (rc < 0
&& errno == EAGAIN
|| (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK))
rc = 0;
if (rc < 0)
ec = get_last_system_error();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
inline ssize_t write (device_handle * h
, char const * bytes
, size_t n
, error_code & ec) noexcept
{
int total_written = 0; // total sent
while (n) {
// MSG_NOSIGNAL flag means:
// requests not to send SIGPIPE on errors on stream oriented sockets
// when the other end breaks the connection.
// The EPIPE error is still returned.
ssize_t written = send(h->fd, bytes + total_written, n, MSG_NOSIGNAL);
if (written < 0) {
if (errno == EAGAIN
|| (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK))
continue;
total_written = -1;
break;
}
total_written += written;
n -= written;
}
if (total_written < 0)
ec = get_last_system_error();
return total_written;
}
////////////////////////////////////////////////////////////////////////////////
// Close socket
////////////////////////////////////////////////////////////////////////////////
inline error_code close (device_handle * h, bool force_shutdown)
{
error_code ec;
if (h->fd > 0) {
if (force_shutdown)
shutdown(h->fd, SHUT_RDWR);
if (::close(h->fd) < 0)
ec = get_last_system_error();
}
h->fd = -1;
return ec;
}
} // socket
namespace local {
using file::open_mode;
using file::opened;
using socket::close;
using socket::read;
using socket::write;
using socket::has_pending_data;
////////////////////////////////////////////////////////////////////////////////
// Open local socket
////////////////////////////////////////////////////////////////////////////////
inline device_handle open (std::string const & name
, bool nonblocking
, error_code & ec)
{
sockaddr_un saddr;
device_handle result;
do {
if (sizeof(saddr.sun_path) < name.size() + 1) {
ec = make_error_code(errc::invalid_argument);
break;
}
int socktype = SOCK_STREAM;
if (nonblocking)
socktype |= SOCK_NONBLOCK;
int fd = ::socket(AF_LOCAL, socktype, 0);
if (fd < 0) {
ec = get_last_system_error();
break;
}
memset(& saddr, 0, sizeof(saddr));
saddr.sun_family = AF_LOCAL;
memcpy(saddr.sun_path, name.c_str(), name.size());
saddr.sun_path[name.size()] = '\0';
int rc = ::connect(fd
, reinterpret_cast<sockaddr *>(& saddr)
, sizeof(saddr));
if (rc < 0) {
ec = get_last_system_error();
break;
}
result.fd = fd;
} while (false);
if (ec && result.fd > 0) {
::close(result.fd);
return device_handle{};
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
// Open local server
////////////////////////////////////////////////////////////////////////////////
inline device_handle open_server (std::string const & name
, bool nonblocking
, int max_pending_connections
, error_code & ec)
{
sockaddr_un saddr;
int fd = -1;
do {
if (sizeof(saddr.sun_path) < name.size() + 1) {
ec = make_error_code(errc::invalid_argument);
break;
}
int socktype = SOCK_STREAM;
if (nonblocking)
socktype |= SOCK_NONBLOCK;
fd = ::socket(AF_LOCAL, socktype, 0);
if (fd < 0) {
ec = get_last_system_error();
break;
}
memset(& saddr, 0, sizeof(saddr));
saddr.sun_family = AF_LOCAL;
memcpy(saddr.sun_path, name.c_str(), name.size());
saddr.sun_path[name.size()] = '\0';
// TODO File deletion must be more reasonable
int rc = unlink(saddr.sun_path);
rc = ::bind(fd
, reinterpret_cast<sockaddr *>(& saddr)
, sizeof(saddr));
if (rc < 0) {
ec = get_last_system_error();
break;
}
rc = listen(fd, max_pending_connections);
if (rc < 0) {
ec = get_last_system_error();
break;
}
} while (false);
if (ec && fd > 0) {
::close(fd);
fd = -1;
}
return fd < 0 ? device_handle{} : device_handle{fd};
}
////////////////////////////////////////////////////////////////////////////////
// Accept local socket
////////////////////////////////////////////////////////////////////////////////
inline device_handle accept (device_handle * h, error_code & ec)
{
sockaddr_un peer_addr;
socklen_t peer_addr_len = sizeof(peer_addr);
int peer_fd = ::accept(h->fd
, reinterpret_cast<sockaddr *> (& peer_addr)
, & peer_addr_len);
if (peer_fd < 0)
ec = get_last_system_error();
return peer_fd < 0 ? device_handle{} : device_handle{peer_fd};
}
} // local
////////////////////////////////////////////////////////////////////////////////
// Open inet socket
////////////////////////////////////////////////////////////////////////////////
inline std::pair<native_handle,std::vector<uint8_t>> open_inet_socket (
std::string const & servername
, uint16_t port
, int base_socktype
, bool nonblocking
, error_code & ec)
{
native_handle fd = -1;
std::vector<uint8_t> serveraddr;
sockaddr_in serveraddr4;
sockaddr_in6 serveraddr6;
int socktype = base_socktype;
if (nonblocking)
socktype |= SOCK_NONBLOCK;
addrinfo host_addrinfo;
host_addrinfo.ai_family = AF_INET;
host_addrinfo.ai_socktype = socktype;
host_addrinfo.ai_protocol = 0;
host_addrinfo.ai_addrlen = 0;
host_addrinfo.ai_addr = nullptr;
host_addrinfo.ai_canonname = nullptr;
host_addrinfo.ai_next = nullptr;
addrinfo * result_addr = nullptr;
do {
int rc = 0;
memset(& serveraddr4, 0, sizeof(serveraddr4));
serveraddr4.sin_family = AF_INET;
serveraddr4.sin_port = htons(port);
rc = inet_pton(AF_INET, servername.c_str(), & serveraddr4.sin_addr.s_addr);
// Success
if (rc > 0) {
host_addrinfo.ai_family = AF_INET;
host_addrinfo.ai_addrlen = sizeof(serveraddr4);
host_addrinfo.ai_addr = reinterpret_cast<sockaddr *>(& serveraddr4);
result_addr = & host_addrinfo;
} else {
memset(& serveraddr6, 0, sizeof(serveraddr6));
serveraddr6.sin6_family = AF_INET6;
serveraddr6.sin6_port = htons(port);
rc = inet_pton(AF_INET6, servername.c_str(), & serveraddr6.sin6_addr.s6_addr);
// Success
if (rc > 0) {
host_addrinfo.ai_family = AF_INET6;
host_addrinfo.ai_addrlen = sizeof(serveraddr6);
host_addrinfo.ai_addr = reinterpret_cast<sockaddr *>(& serveraddr6);
result_addr = & host_addrinfo;
}
}
// servername does not contain a character string representing a
// valid network address in the specified address family.
if (!result_addr) {
addrinfo hints;
memset(& hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_flags = AI_V4MAPPED;
hints.ai_socktype = socktype;
rc = getaddrinfo(servername.c_str(), nullptr, & hints, & result_addr);
if (rc != 0) {
ec = make_error_code(errc::host_not_found);
break;
}
}
if (result_addr) {
for (addrinfo * p = result_addr; p != nullptr; p = result_addr->ai_next) {
reinterpret_cast<sockaddr_in*>(p->ai_addr)->sin_port = htons(port);
fd = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd < 0) {
ec = get_last_system_error();
continue;
}
serveraddr = decltype(serveraddr)(reinterpret_cast<uint8_t *>(p->ai_addr)
, reinterpret_cast<uint8_t *>(p->ai_addr) + p->ai_addrlen);
break;
}
}
if (fd < 0)
break;
if (ec) {
::close(fd);
break;
}
} while (false);
if (result_addr && result_addr != & host_addrinfo) {
freeaddrinfo(result_addr);
}
return std::make_pair(fd, serveraddr);
}
namespace tcp {
using file::open_mode;
using file::opened;
using socket::close;
using socket::read;
using socket::write;
using socket::has_pending_data;
////////////////////////////////////////////////////////////////////////////////
// Open TCP socket
////////////////////////////////////////////////////////////////////////////////
inline device_handle open (std::string const & servername
, uint16_t port
, bool nonblocking
, error_code & ec)
{
auto credentials = open_inet_socket(servername
, port
, SOCK_STREAM
, nonblocking
, ec);
native_handle & fd = credentials.first;
auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data());
auto addrlen = static_cast<socklen_t>(credentials.second.size());
if (fd >= 0) {
int rc = ::connect(fd, addr, addrlen);
if (rc < 0) {
ec = get_last_system_error();
::close(fd);
fd = -1;
}
}
return fd < 0 ? device_handle{} : device_handle{fd};
}
////////////////////////////////////////////////////////////////////////////////
// Open TCP server
////////////////////////////////////////////////////////////////////////////////
inline device_handle open_server (std::string const & servername
, uint16_t port
, bool nonblocking
, int max_pending_connections
, error_code & ec)
{
auto credentials = open_inet_socket(servername
, port
, SOCK_STREAM
, nonblocking
, ec);
native_handle & fd = credentials.first;
auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data());
auto addrlen = static_cast<socklen_t>(credentials.second.size());
if (fd >= 0) {
// The setsockopt() function is used to allow the local
// address to be reused when the server is restarted
// before the required wait time expires.
int on = 1;
int rc = setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, reinterpret_cast<char *>(& on)
, sizeof(on));
if (rc == 0) {
rc = ::bind(fd, addr, addrlen);
if (rc == 0) {
rc = ::listen(fd, max_pending_connections);
}
if (rc < 0) {
ec = get_last_system_error();
::close(fd);
fd = -1;
}
}
}
return fd < 0 ? device_handle{} : device_handle{fd};
}
////////////////////////////////////////////////////////////////////////////////
// Accept TCP socket
////////////////////////////////////////////////////////////////////////////////
inline device_handle accept (device_handle * h, error_code & ec)
{
sockaddr_in peer_addr4;
sockaddr_in6 peer_addr6;
socklen_t peer_addr_len = std::max(sizeof(peer_addr4), sizeof(peer_addr6));
sockaddr * peer_addr = sizeof(peer_addr4) > sizeof(peer_addr6)
? reinterpret_cast<sockaddr *> (& peer_addr4)
: reinterpret_cast<sockaddr *> (& peer_addr6);
auto peer_fd = ::accept(h->fd, peer_addr, & peer_addr_len);
if (peer_fd < 0)
ec = get_last_system_error();
return peer_fd < 0 ? device_handle{} : device_handle{peer_fd};
}
////////////////////////////////////////////////////////////////////////////////
// Enable keep alive
////////////////////////////////////////////////////////////////////////////////
inline error_code enable_keep_alive (device_handle * h, bool enable)
{
int optval = enable ? 1 : 0;
int rc = setsockopt(h->fd, SOL_SOCKET, SO_KEEPALIVE, & optval, sizeof(optval));
return rc < 0 ? get_last_system_error() : error_code{};
}
} // tcp
namespace udp {
using file::open_mode;
using file::opened;
using socket::close;
using socket::has_pending_data;
////////////////////////////////////////////////////////////////////////////////
// Open UDP socket
////////////////////////////////////////////////////////////////////////////////
inline device_handle open (std::string const & servername
, uint16_t port
, bool nonblocking
, host_address * paddr
, error_code & ec)
{
auto credentials = open_inet_socket(servername
, port
, SOCK_DGRAM
, nonblocking
, ec);
native_handle & fd = credentials.first;
auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data());
socklen_t addrlen = static_cast<socklen_t>(credentials.second.size());
if (paddr)
std::memcpy(& paddr->addr, addr
, std::min(addrlen, static_cast<socklen_t>(sizeof(paddr->addr))));
return fd < 0 ? device_handle{} : device_handle{fd};
}
////////////////////////////////////////////////////////////////////////////////
// Open UDP server
////////////////////////////////////////////////////////////////////////////////
inline device_handle open_server (std::string const & servername
, uint16_t port
, bool nonblocking
, error_code & ec)
{
auto credentials = open_inet_socket(servername
, port
, SOCK_DGRAM
, nonblocking
, ec);
native_handle & fd = credentials.first;
auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data());
auto addrlen = static_cast<socklen_t>(credentials.second.size());
if (fd >= 0) {
// The setsockopt() function is used to allow the local
// address to be reused when the server is restarted
// before the required wait time expires.
int on = 1;
int rc = setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, reinterpret_cast<char *>(& on)
, sizeof(on));
if (rc == 0) {
rc = ::bind(fd, addr, addrlen);
if (rc < 0) {
ec = get_last_system_error();
::close(fd);
fd = -1;
}
}
}
return fd < 0 ? device_handle{} : device_handle{fd};
}
////////////////////////////////////////////////////////////////////////////////
// Read from UDP socket
////////////////////////////////////////////////////////////////////////////////
inline ssize_t read (device_handle * h
, host_address * paddr
, char * bytes
, size_t n
, error_code & ec) noexcept
{
socklen_t addrlen = 0;
ssize_t rc = recvfrom(h->fd, bytes, n, 0
, reinterpret_cast<sockaddr *>(& paddr->addr), & addrlen);
if (rc < 0
&& errno == EAGAIN
|| (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK))
rc = 0;
if (rc < 0)
ec = get_last_system_error();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
// Write to UDP socket
////////////////////////////////////////////////////////////////////////////////
inline ssize_t write (device_handle * h
, host_address const * paddr
, char const * bytes
, size_t n
, error_code & ec) noexcept
{
int total_written = 0; // total sent
while (n) {
// MSG_NOSIGNAL flag means:
// requests not to send SIGPIPE on errors on stream oriented sockets
// when the other end breaks the connection.
// The EPIPE error is still returned.
ssize_t written = sendto(h->fd
, bytes + total_written
, n
, MSG_NOSIGNAL
, reinterpret_cast<sockaddr const *>(& paddr->addr)
, sizeof(paddr->addr));
if (written < 0) {
if (errno == EAGAIN
|| (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK))
continue;
total_written = -1;
break;
}
total_written += written;
n -= written;
}
if (total_written < 0)
ec = get_last_system_error();
return total_written;
}
} // udp
}}} // pfs::io::unix_ns
| 28.034796 | 90 | 0.480114 | semenovf |
7997a74616cde6309529b4e3e6819f16435f10c2 | 5,819 | cpp | C++ | src/caffe/layers/data/mtcnn_data_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | 7 | 2018-02-06T13:48:17.000Z | 2019-04-08T13:56:22.000Z | src/caffe/layers/data/mtcnn_data_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/data/mtcnn_data_layer.cpp | fireae/caffe_latte | a28559481c2864c79d4b393e91869eb77c0a75fe | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#endif // USE_OPENCV
#include <stdint.h>
#include <vector>
#include "caffe/data_transformer.hpp"
#include "caffe/layers/mtcnn_data_layer.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "opencv2/highgui.hpp"
namespace caffe {
template <typename Dtype>
MTCNNDataLayer<Dtype>::MTCNNDataLayer(const LayerParameter ¶m)
: BasePrefetchingDataLayer<Dtype>(param), offset_() {
db_.reset(db::GetDB(param.data_param().backend()));
db_->Open(param.data_param().source(), db::READ);
cursor_.reset(db_->NewCursor());
}
template <typename Dtype> MTCNNDataLayer<Dtype>::~MTCNNDataLayer() {
this->StopInternalThread();
}
template <typename Dtype>
void MTCNNDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype> *> &bottom,
const vector<Blob<Dtype> *> &top) {
const int batch_size = this->layer_param_.data_param().batch_size();
// Read a data point, and use it to initialize the top blob.
MTCNNDatum datum;
datum.ParseFromString(cursor_->value());
// Use data_transformer to infer the expected blob shape from datum.
vector<int> top_shape =
this->data_transformer_->InferBlobShape(datum.datum());
this->transformed_data_.Reshape(top_shape);
// Reshape top[0] and prefetch_data according to the batch_size.
top_shape[0] = batch_size;
top[0]->Reshape(top_shape);
for (int i = 0; i < this->prefetch_.size(); ++i) {
this->prefetch_[i]->data_.Reshape(top_shape);
}
LOG_IF(INFO, Caffe::root_solver())
<< "output data size: " << top[0]->num() << "," << top[0]->channels()
<< "," << top[0]->height() << "," << top[0]->width();
// label
if (this->output_labels_) {
vector<int> label_shape(1);
label_shape[0] = batch_size;
top[1]->Reshape(label_shape);
for (int i = 0; i < this->prefetch_.size(); ++i) {
this->prefetch_[i]->label_.Reshape(label_shape);
}
}
// roi
if (this->output_roi_) {
vector<int> roi_shape(2);
roi_shape[0] = batch_size;
roi_shape[1] = 4;
top[2]->Reshape(roi_shape);
for (int i = 0; i < this->prefetch_.size(); ++i) {
this->prefetch_[i]->roi_.Reshape(roi_shape);
}
// pts
if (this->output_pts_) {
vector<int> pts_shape(2);
pts_shape[0] = batch_size;
pts_shape[1] = 10; //默认为5个坐标点 即 10 个points
top[3]->Reshape(roi_shape);
for (int i = 0; i < this->prefetch_.size(); ++i) {
this->prefetch_[i]->roi_.Reshape(roi_shape);
}
}
}
}
template <typename Dtype> bool MTCNNDataLayer<Dtype>::Skip() {
int size = Caffe::solver_count();
int rank = Caffe::solver_rank();
bool keep = (offset_ % size) == rank ||
// In test mode, only rank 0 runs, so avoid skipping
this->layer_param_.phase() == TEST;
return !keep;
}
template <typename Dtype> void MTCNNDataLayer<Dtype>::Next() {
cursor_->Next();
if (!cursor_->valid()) {
// LOG_IF(INFO, Caffe::root_solver())
//<< "Restarting data prefetching from start.";
cursor_->SeekToFirst();
}
offset_++;
}
// This function is called on prefetch thread
template <typename Dtype>
void MTCNNDataLayer<Dtype>::load_batch(Batch<Dtype> *batch) {
CPUTimer batch_timer;
batch_timer.Start();
double read_time = 0;
double trans_time = 0;
CPUTimer timer;
CHECK(batch->data_.count());
CHECK(this->transformed_data_.count());
const int batch_size = this->layer_param_.data_param().batch_size();
MTCNNDatum datum;
for (int item_id = 0; item_id < batch_size; ++item_id) {
timer.Start();
while (Skip()) {
Next();
}
datum.ParseFromString(cursor_->value()); //数据库内读入一条数据
const Datum &data = datum.datum();
read_time += timer.MicroSeconds();
if (item_id == 0) {
// Reshape according to the first datum of each batch
// on single input batches allows for inputs of varying dimension.
// Use data_transformer to infer the expected blob shape from datum.
vector<int> top_shape = this->data_transformer_->InferBlobShape(data);
this->transformed_data_.Reshape(top_shape);
// Reshape batch according to the batch_size.
top_shape[0] = batch_size;
batch->data_.Reshape(top_shape);
}
// Apply data transformations (mirror, scale, crop...)
timer.Start();
int offset = batch->data_.offset(item_id);
Dtype *top_data = batch->data_.mutable_cpu_data();
this->transformed_data_.set_cpu_data(top_data + offset);
this->data_transformer_->Transform(data, &(this->transformed_data_));
// Copy label.
if (this->output_labels_) {
Dtype *top_label = batch->label_.mutable_cpu_data();
top_label[item_id] = data.label(0);
}
// Copy rois.
if (this->output_roi_) {
Dtype *top_roi = batch->roi_.mutable_cpu_data();
top_roi[item_id * 4 + 0] = datum.rois().xmin();
top_roi[item_id * 4 + 1] = datum.rois().ymin();
top_roi[item_id * 4 + 2] = datum.rois().xmax();
top_roi[item_id * 4 + 3] = datum.rois().ymax();
}
// Copy pts
if (this->output_pts_) {
Dtype *top_pts = batch->pts_.mutable_cpu_data();
// Dtype& bottom_pts = datum.pts();
int pts_size = datum.pts_size(); //默认应该为10
CHECK_EQ(pts_size, 10) << "pts size error";
for (int i = 0; i < pts_size; ++i) {
top_pts[item_id * pts_size + i] = datum.pts(i);
}
}
trans_time += timer.MicroSeconds();
Next(); //数据库指针后移
}
timer.Stop();
batch_timer.Stop();
LOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms.";
LOG(INFO) << " Read time: " << read_time / 1000 << " ms.";
LOG(INFO) << "Transform time: " << trans_time / 1000 << " ms.";
}
INSTANTIATE_CLASS(MTCNNDataLayer);
REGISTER_LAYER_CLASS(MTCNNData);
} // namespace caffe
| 33.635838 | 79 | 0.639801 | fireae |
7998f624a2a44372107a1e2f6da492cdcc072ca5 | 29,661 | cpp | C++ | TestMac/cpp/network_service.cpp | tinyvpn/tvpn_mac | 5bb67c8874a05561a05f87e5a9c3470471e5301b | [
"MIT"
] | null | null | null | TestMac/cpp/network_service.cpp | tinyvpn/tvpn_mac | 5bb67c8874a05561a05f87e5a9c3470471e5301b | [
"MIT"
] | null | null | null | TestMac/cpp/network_service.cpp | tinyvpn/tvpn_mac | 5bb67c8874a05561a05f87e5a9c3470471e5301b | [
"MIT"
] | null | null | null | #include "network_service.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <memory.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/kern_control.h>
#include <sys/uio.h>
#include <sys/sys_domain.h>
#include <netinet/ip.h>
#include <net/if_utun.h> //here defined _NET_IF_UTUN_H_
#include "log.h"
#include "fileutl.h"
#include "sockutl.h"
#include "ssl_client2.h"
#include "stringutl.h"
#include "http_client.h"
#include "sockhttp.h"
#include "sysutl.h"
#include "timeutl.h"
#include "obfuscation_utl.h"
const int BUF_SIZE = 4096*4;
int g_protocol = kSslType;
uint32_t g_private_ip;
std::string global_private_ip;
std::string global_default_gateway_ip;
int g_fd_tun_dev;
std::string target_test_ip; //="159.65.226.184";
uint16_t target_test_port;
std::string web_server_ip = "www.tinyvpn.xyz";
static uint32_t in_traffic, out_traffic;
static int g_isRun;
static int client_sock;
static int g_in_recv_tun;
static int g_in_recv_socket;
int premium = 2;
std::string g_user_name;// = "dudu@163.com";
std::string g_password;// = "123456";
std::string g_device_id;
static int firstOpen=0;
//int current_traffic = 0 ; //bytes
uint32_t g_day_traffic;
uint32_t g_month_traffic;
int popen_fill( char* data, int len, const char* cmd, ... )
{
FILE* output;
va_list vlist;
char line[2048];
int line_len, line_count, total_len, id;
if (!data || len <= 0 || !cmd)
return -1;
va_start(vlist, cmd);
line_len = vsnprintf(line, 2048, cmd, vlist);
if (line_len < 0) line_len = 0;
va_end(vlist);
line[line_len] = 0;
line_count = id = total_len = 0;
if ((output = popen(line, "r"))) {
while (!feof(output) && fgets(line, sizeof(line)-1, output)){
line_len = (int)strlen(line);
if (len - total_len - 1 < line_len){
break;
}
memcpy(data + total_len, line, line_len);
total_len += line_len;
line_count++;
id++;
}
pclose(output);
}
data[total_len] = 0;
return total_len;
}
int set_dns()
{
char ret_data[256];
INFO("networksetup -listnetworkserviceorder | grep '(1)' | awk '{print $2}'");
if (popen_fill(ret_data, sizeof(ret_data), "networksetup -listnetworkserviceorder | grep '(1)' | awk '{print $2}'") <= 0) {
ERROR("networksetup cmd listnetworkserviceorder fail.");
return 1;
}
for (int i=0;i<strlen(ret_data);i++)
if (ret_data[i] == 0x0A)
ret_data[i] = ' ';
std::string str_cmd;
str_cmd = std::string("networksetup -getdnsservers ") + ret_data;
std::string str_network_card = ret_data;
INFO("cmd: %s", str_cmd.c_str());
if (popen_fill(ret_data, sizeof(ret_data), str_cmd.c_str()) > 0) {
for (int i=0;i<strlen(ret_data);i++)
if (ret_data[i] == 0x0A)
ret_data[i] = ' ';
str_cmd = ret_data;
//INFO("networksetup getdnsservers ok: %s", string_utl::HexEncode(std::string(ret_data, strlen(ret_data))).c_str());
INFO("networksetup getdnsservers ok: %s", ret_data);
if (str_cmd.find("8.8.8.8") != std::string::npos)
return 0;
if (str_cmd.find("any") != std::string::npos) {
str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + " 8.8.8.8";
INFO("cmd: %s", str_cmd.c_str());
system(str_cmd.c_str());
return 0;
}
str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + std::string("8.8.8.8 ") + str_cmd;
INFO("cmd: %s", str_cmd.c_str());
system(str_cmd.c_str());
return 0;
}
str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + " 8.8.8.8";
INFO("cmd: %s", str_cmd.c_str());
system(str_cmd.c_str());
return 0;
}
bool ifconfig(const char * ifname, const char * va, const char *pa)
{
char cmd[2048] = {0};
snprintf(cmd, sizeof(cmd), "ifconfig %s %s %s netmask 255.255.0.0 up",ifname, va, pa);
INFO("ifconfig:%s\n", cmd);
if (system(cmd) < 0)
{
ERROR("sys_utl::ifconfig,interface(%s) with param(%s) and params(%s) fail at error:%d\n",ifname,va,pa,errno);
return false;
}
return true;
}
void exception_signal_handler(int nSignal)
{
INFO("capture exception signal: %d",nSignal);
if(global_default_gateway_ip.size() > 0)
{
system("sudo route delete default");
std::string add_org_gateway_cmd("sudo route add default ");
add_org_gateway_cmd += global_default_gateway_ip;
system(add_org_gateway_cmd.c_str());
}
}
void quit_signal_handler(int nSignal)
{
INFO("capture quit signal: %d",nSignal);
if(global_default_gateway_ip.size() > 0)
{
system("sudo route delete default");
std::string add_org_gateway_cmd("sudo route add default ");
add_org_gateway_cmd += global_default_gateway_ip;
system(add_org_gateway_cmd.c_str());
}
exit(0);
}
void add_host_to_route(const std::string ip, const std::string device)
{
std::string routing_cmd("route add -host ");
routing_cmd += ip.c_str();
routing_cmd += (" -interface ");
routing_cmd += device;
system(routing_cmd.c_str());
INFO("routing_cmd:%s", routing_cmd.c_str());
}
void add_host_to_gateway(const std::string ip, const std::string gateway)
{
std::string routing_cmd("route add -host ");
routing_cmd += ip.c_str();
routing_cmd += (" -gateway ");
routing_cmd += gateway;
system(routing_cmd.c_str());
INFO("routing_cmd:%s", routing_cmd.c_str());
}
void delete_host_to_gateway(const std::string ip, const std::string gateway)
{
std::string routing_cmd("route delete -host ");
routing_cmd += ip.c_str();
routing_cmd += (" -gateway ");
routing_cmd += gateway;
system(routing_cmd.c_str());
INFO("routing_cmd:%s", routing_cmd.c_str());
}
void add_network_to_route(const std::string network, const std::string device)
{
std::string routing_cmd("route add -net ");
routing_cmd += network.c_str();
routing_cmd += (" -interface ");
routing_cmd += device;
system(routing_cmd.c_str());
}
void add_network_to_gateway(const std::string network,std::string net_mask,const std::string gateway)
{
std::string routing_cmd("route add -net ");
routing_cmd += network.c_str();
routing_cmd += " netmask ";
routing_cmd += net_mask.c_str();
routing_cmd += (" -gateway ");
routing_cmd += gateway;
system(routing_cmd.c_str());
}
static char g_tcp_buf[BUF_SIZE*2];
static int g_tcp_len;
int write_tun(char* ip_packet_data, int ip_packet_len){
int len;
if (g_tcp_len != 0) {
if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) {
ERROR("relay size over %lu", sizeof(g_tcp_buf));
g_tcp_len = 0;
return 1;
}
memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len);
ip_packet_data = g_tcp_buf;
ip_packet_len += g_tcp_len;
g_tcp_len = 0;
DEBUG2("relayed packet:%d", ip_packet_len);
}
while(1) {
if (ip_packet_len == 0)
break;
// todo: recv from socket, send to utun1
if (ip_packet_len < sizeof(struct ip) ) {
ERROR("less than ip header:%d.", ip_packet_len);
memcpy(g_tcp_buf, ip_packet_data, ip_packet_len);
g_tcp_len = ip_packet_len;
break;
}
struct ip *iph = (struct ip *)ip_packet_data;
len = ntohs(iph->ip_len);
if (ip_packet_len < len) {
if (len > BUF_SIZE) {
ERROR("something error1.%x,%x,data:%s",len, ip_packet_len, string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str());
g_tcp_len = 0;
} else {
DEBUG2("relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len);
if (g_tcp_len == 0) {
memcpy(g_tcp_buf +g_tcp_len, ip_packet_data, ip_packet_len);
g_tcp_len += ip_packet_len;
}
}
break;
}
if (len > BUF_SIZE) {
ERROR("something error.%x,%x",len, ip_packet_len);
g_tcp_len = 0;
break;
} else if (len == 0) {
ERROR("len is zero.%x,%x",len, ip_packet_len); //string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str());
g_tcp_len = 0;
break;
}
char ip_src[INET_ADDRSTRLEN + 1];
char ip_dst[INET_ADDRSTRLEN + 1];
inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN);
inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN);
DEBUG2("send to utun, from(%s) to (%s) with size:%d",ip_src,ip_dst,len);
if (sys_utl::tun_dev_write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) {
//if (::write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) {
ERROR("write tun error:%d", g_fd_tun_dev);
return 1;
}
ip_packet_len -= len;
ip_packet_data += len;
}
return 0;
}
int write_tun_http(char* ip_packet_data, int ip_packet_len) {
static uint32_t g_iv = 0x87654321;
int len;
if (g_tcp_len != 0) {
if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) {
INFO("relay size over %d", sizeof(g_tcp_buf));
g_tcp_len = 0;
return 1;
}
memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len);
ip_packet_data = g_tcp_buf;
ip_packet_len += g_tcp_len;
g_tcp_len = 0;
INFO("relayed packet:%d", ip_packet_len);
}
std::string http_packet;
int http_head_length, http_body_length;
while (1) {
if (ip_packet_len == 0)
break;
http_packet.assign(ip_packet_data, ip_packet_len);
if (sock_http::pop_front_xdpi_head(http_packet, http_head_length, http_body_length) != 0) { // decode http header fail
DEBUG2("relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len);
if (g_tcp_len == 0) {
memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len);
g_tcp_len += ip_packet_len;
}
break;
}
ip_packet_len -= http_head_length;
ip_packet_data += http_head_length;
obfuscation_utl::decode((unsigned char *) ip_packet_data, 4, g_iv);
obfuscation_utl::decode((unsigned char *) ip_packet_data + 4, http_body_length - 4, g_iv);
struct ip *iph = (struct ip *) ip_packet_data;
len = ntohs(iph->ip_len);
char ip_src[INET_ADDRSTRLEN + 1];
char ip_dst[INET_ADDRSTRLEN + 1];
inet_ntop(AF_INET, &iph->ip_src.s_addr, ip_src, INET_ADDRSTRLEN);
inet_ntop(AF_INET, &iph->ip_dst.s_addr, ip_dst, INET_ADDRSTRLEN);
DEBUG2("send to tun,http, from(%s) to (%s) with size:%d, header:%d,body:%d", ip_src,
ip_dst, len, http_head_length, http_body_length);
sys_utl::tun_dev_write(g_fd_tun_dev, (void *) ip_packet_data, len);
ip_packet_len -= http_body_length;
ip_packet_data += http_body_length;
}
return 0;
}
int network_service::tun_and_socket(void(*trafficCallback)(long, long,long,long,void*), void* target)
{
INFO("start ssl thread,g_fd_tun_dev:%d,client_sock:%d", g_fd_tun_dev, client_sock);
g_isRun= 1;
g_in_recv_tun = 1;
g_tcp_len = 0;
in_traffic = 0;
out_traffic = 0;
//std::thread tun_thread(client_recv_tun, client_sock);
g_in_recv_socket = 1;
int ip_packet_len;
char ip_packet_data[BUF_SIZE];
int ret;
time_t lastTime = time_utl::localtime();
time_t currentTime;
time_t recvTime = time_utl::localtime();
time_t sendTime = time_utl::localtime();
fd_set fdsr;
int maxfd;
while(g_isRun == 1){
FD_ZERO(&fdsr);
FD_SET(client_sock, &fdsr);
FD_SET(g_fd_tun_dev, &fdsr);
maxfd = std::max(client_sock, g_fd_tun_dev);
struct timeval tv_select;
tv_select.tv_sec = 2;
tv_select.tv_usec = 0;
int nReady = select(maxfd + 1, &fdsr, NULL, NULL, &tv_select);
if (nReady < 0) {
ERROR("select error:%d", nReady);
break;
} else if (nReady == 0) {
INFO("select timeout");
continue;
}
if (FD_ISSET(g_fd_tun_dev, &fdsr)) { // recv from tun
static VpnPacket vpn_packet(4096);
int readed_from_tun;
vpn_packet.reset();
readed_from_tun = sys_utl::tun_dev_read(g_fd_tun_dev, vpn_packet.data(), vpn_packet.remain_size());
vpn_packet.set_back_offset(vpn_packet.front_offset()+readed_from_tun);
if(readed_from_tun < sizeof(struct ip)) {
ERROR("tun_dev_read error, size:%d", readed_from_tun);
break;
}
if(readed_from_tun > 0)
{
struct ip *iph = (struct ip *)vpn_packet.data();
char ip_src[INET_ADDRSTRLEN + 1];
char ip_dst[INET_ADDRSTRLEN + 1];
inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN);
inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN);
if(g_private_ip != iph->ip_src.s_addr) {
ERROR("src_ip mismatch:%x,%x",g_private_ip, iph->ip_src.s_addr);
continue;
}
DEBUG2("recv from tun, from(%s) to (%s) with size:%d",ip_src,ip_dst,readed_from_tun);
//file_utl::write(sockid, vpn_packet.data(), readed_from_tun);
out_traffic += readed_from_tun;
if (g_protocol == kSslType) {
if (ssl_write(vpn_packet.data(), readed_from_tun) != 0) {
ERROR("ssl_write error");
break;
}
} else if (g_protocol == kHttpType){
http_write(vpn_packet);
}
sendTime = time_utl::localtime();
}
// if (--nReady == 0) // read over
// continue;
}
if (FD_ISSET(client_sock, &fdsr)) { // recv from socket
ip_packet_len = 0;
if (g_protocol == kSslType) {
ret = ssl_read(ip_packet_data, ip_packet_len);
if (ret != 0) {
ERROR("ssl_read error");
break;
}
} else if (g_protocol == kHttpType) {
ip_packet_len = file_utl::read(client_sock, ip_packet_data, BUF_SIZE);
} else {
ERROR("protocol error.");
break;
}
if (ip_packet_len == 0)
continue;
in_traffic += ip_packet_len;
DEBUG2("recv from socket, size:%d", ip_packet_len);
if (g_protocol == kSslType) {
if (write_tun((char *) ip_packet_data, ip_packet_len) != 0) {
ERROR("write_tun error");
break;
}
} else if (g_protocol == kHttpType){
if (write_tun_http((char *) ip_packet_data, ip_packet_len) != 0) {
ERROR("write_tun error");
break;
}
}
recvTime = time_utl::localtime();
}
currentTime = time_utl::localtime();
if (currentTime - recvTime > 60 || currentTime - sendTime > 60) {
ERROR("send or recv timeout");
break;
}
if (currentTime - lastTime >= 1) {
/*jclass thisClass = (env)->GetObjectClass(thisObj);
jfieldID fidNumber = (env)->GetFieldID(thisClass, "current_traffic", "I");
if (NULL == fidNumber) {
ERROR("current_traffic error");
return 1;
}
// Change the variable
(env)->SetIntField(thisObj, fidNumber, in_traffic + out_traffic);
INFO("current traffic:%d", in_traffic+out_traffic);
jmethodID mtdCallBack = (env)->GetMethodID(thisClass, "trafficCallback", "()I");
if (NULL == mtdCallBack) {
ERROR("trafficCallback error");
return 1;
}
ret = (env)->CallIntMethod(thisObj, mtdCallBack);
*/
trafficCallback(g_day_traffic + (in_traffic + out_traffic)/1024, g_month_traffic+ (in_traffic + out_traffic)/1024, 0,0, target);
lastTime = time_utl::localtime();
}
}
INFO("main thread stop");
if(g_protocol == kSslType)
ssl_close();
else if (g_protocol == kHttpType)
close(client_sock);
close(g_fd_tun_dev);
g_isRun = 0;
// callback to app
/* jclass thisClass = (env)->GetObjectClass( thisObj);
jmethodID midCallBackAverage = (env)->GetMethodID(thisClass, "stopCallback", "()I");
if (NULL == midCallBackAverage)
return 1;
ret = (env)->CallIntMethod(thisObj, midCallBackAverage);
__android_log_print(ANDROID_LOG_DEBUG, "JNI", "stop callback:%d", ret);*/
return 0;
}
int network_service::init() {
signal(SIGKILL, quit_signal_handler);
signal(SIGINT, quit_signal_handler);
OpenFile("/tmp/tvpn.log");
SetLogLevel(0);
firstOpen = 1;
system("route -n get default | grep 'gateway' | awk '{print $2}' > /tmp/default_gateway.txt");
file_utl::read_file("/tmp/default_gateway.txt", global_default_gateway_ip);
if(global_default_gateway_ip.size() > 0)
{
//remove \n \r
const int last_char = *global_default_gateway_ip.rbegin();
if( (last_char == '\n') || (last_char == '\r') )
global_default_gateway_ip.resize(global_default_gateway_ip.size()-1);
}
string_utl::set_random_http_domains();
sock_http::init_http_head();
return 0;
}
int network_service::get_vpnserver_ip(std::string user_name, std::string password, std::string device_id, long premium, std::string country_code, void(*trafficCallback)(long, long,long,long,void*), void* target){
struct hostent *h;
if((h=gethostbyname(web_server_ip.c_str()))==NULL) {
return 1;
}
std::string web_ip = inet_ntoa(*((struct in_addr *)h->h_addr));
INFO("web ip:%s", web_ip.c_str());
struct sockaddr_in serv_addr;
int sock =socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
INFO("socket() error");
return 1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(web_ip.c_str());
serv_addr.sin_port=htons(60315);
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) {
INFO("connect() error!");
return 1;
}
INFO("connect web server ok.");
/* std::string::size_type found = country_code.find("\"");
if (found == std::string::npos)
return 1;
std::string strCountry = country_code.substr(found+1);
found = country_code.find("\"");
if (found == std::string::npos)
return 1;
strCountry = strCountry.substr(0,found - 1);
INFO("country code:%s",strCountry.c_str());*/
std::string strtemp;
strtemp += (char)0;
strtemp += (char)premium;
strtemp += country_code;
if (premium <= 1)
strtemp += device_id;
else
strtemp += user_name;
INFO("send:%s", string_utl::HexEncode(strtemp).c_str());
int ret=file_utl::write(sock, (char*)strtemp.c_str(), (int)strtemp.size());
char ip_packet_data[BUF_SIZE];
ret=file_utl::read(sock, ip_packet_data, BUF_SIZE);
ip_packet_data[ret] = 0;
INFO("recv from web_server:%s", string_utl::HexEncode(std::string(ip_packet_data,ret)).c_str());
//current_traffic = 0;
int pos = 0;
uint32_t day_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t month_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t day_limit = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t month_limit = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
g_day_traffic = day_traffic;
g_month_traffic = month_traffic;
if (premium<=1){
if (day_traffic > day_limit) {
trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target);
return 2;
}
} else{
if (month_traffic > month_limit) {
trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target);
return 2;
}
}
trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target);
std::string recv_ip(ip_packet_data + 16, ret-16);
std::vector<std::string> recv_data;
string_utl::split_string(recv_ip,',', recv_data);
if(recv_data.size() < 1) {
ERROR("recv server ip data error.");
//tunnel.close();
return 1;
}
INFO("recv:%s", recv_data[0].c_str());
std::vector<std::string> server_data;
string_utl::split_string(recv_data[0],':', server_data);
if(server_data.size() < 3) {
ERROR("parse server ip data error.");
//tunnel.close();
return 1;
}
//Log.i(TAG, "data:" + server_data[0]+","+server_data[1]+","+server_data[2]);
g_protocol = std::stoi(server_data[0]);
target_test_ip = server_data[1];
//g_ip = "192.168.50.218";
target_test_port = std::stoi(server_data[2]);
INFO("protocol:%d,%s,%d",g_protocol, target_test_ip.c_str(),target_test_port);
return 0;
}
int network_service::start_vpn(std::string user_name, std::string password, std::string device_id, long premium, std::string country_code, void(*stopCallback)(long, void*), void(*trafficCallback)(long, long,long,long,void*), void* target)
{
if(firstOpen==0) {
init();
}
g_user_name = user_name;
g_password = password;
g_device_id = device_id;
// get vpnserver ip
int ret = get_vpnserver_ip(user_name, password, device_id, premium, country_code, trafficCallback, target);
if ( ret == 1) {
stopCallback(1, target);
return 1;
} else if (ret == 2) {
stopCallback(1, target);
return 2;
}
if (connect_server()!=0){
stopCallback(1, target);
return 1;
}
std::string dev_name;
g_fd_tun_dev = sys_utl::open_tun_device(dev_name, false);
if (g_fd_tun_dev <= 0) {
INFO("open_tun_device error");
stopCallback(1, target);
return 1;
}
socket_utl::set_nonblock(g_fd_tun_dev,false);
ifconfig(dev_name.c_str(),global_private_ip.c_str(),global_private_ip.c_str());
if(global_default_gateway_ip.size() <= 0){
stopCallback(1, target);
INFO("global_default_gateway_ip empty.");
return 1;
}
add_host_to_gateway(target_test_ip,global_default_gateway_ip);
std::string add_default_gateway_cmd("sudo route add default ");
add_default_gateway_cmd += global_private_ip;
system(add_default_gateway_cmd.c_str());
INFO("add_default_gateway_cmd:%s", add_default_gateway_cmd.c_str());
std::string change_default_gateway_cmd("sudo route change default -interface ");
change_default_gateway_cmd += dev_name;
system(change_default_gateway_cmd.c_str());
INFO("change_default_gateway_cmd:%s", change_default_gateway_cmd.c_str());
std::string add_org_gateway_cmd("sudo route add default ");
add_org_gateway_cmd += global_default_gateway_ip;
system(add_org_gateway_cmd.c_str());
INFO("add_org_gateway_cmd:%s", add_org_gateway_cmd.c_str());
add_host_to_route(global_private_ip, dev_name);
set_dns();
stopCallback(0, target);
ret = tun_and_socket(trafficCallback, target);
if (ret != 0) {
stopCallback(1, target);
return ret;
}
delete_host_to_gateway(target_test_ip,global_default_gateway_ip);
system("sudo route delete default");
INFO("cmd: sudo route delete default");
add_org_gateway_cmd = "sudo route add default ";
add_org_gateway_cmd += global_default_gateway_ip;
system(add_org_gateway_cmd.c_str());
INFO("add_org_gateway_cmd:%s", add_org_gateway_cmd.c_str());
stopCallback(1, target);
return 0;
}
int network_service::connect_server()
{
int sock =socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
INFO("socket() error");
return 1;
}
//std::string strIp = "159.65.226.184";
//uint16_t port = 14455;
if (g_protocol == kSslType) {
if (init_ssl_client() != 0) {
ERROR( "init ssl fail.");
return 1;
}
INFO("connect ssl");
connect_ssl(target_test_ip, target_test_port, sock);
if (sock == 0) {
ERROR("sock is zero.");
return 1;
}
} else if (g_protocol == kHttpType) {
if (connect_tcp(target_test_ip, target_test_port, sock) != 0)
return 1;
} else {
ERROR( "protocol errror.");
return 1;
}
client_sock = sock;
INFO("connect ok.");
std::string strPrivateIp;
//INFO("get private_ip");
if (g_protocol == kSslType){
//std::string strId = "IOS.00000001";
//std::string strPassword = "123456";
get_private_ip(premium,g_device_id, g_user_name, g_password, strPrivateIp);
}
g_private_ip = *(uint32_t*)strPrivateIp.c_str();
global_private_ip = socket_utl::socketaddr_to_string(g_private_ip);
printf("private_ip:%s", global_private_ip.c_str());
//g_private_ip = ntohl(g_private_ip);
return 0;
}
int network_service::stop_vpn(long value)
{
g_isRun = 0;
return 0;
}
int network_service::connect_web_server(std::string user_name, long premium, uint32_t* private_ip )
{
return 0;
}
int network_service::login(std::string user_name, std::string password, std::string device_id,
void(*trafficCallback)(long, long,long,long,long,long, void*), void* target)
{
if(firstOpen==0) {
init();
}
struct hostent *h;
if((h=gethostbyname(web_server_ip.c_str()))==NULL) {
return 1;
}
std::string web_ip = inet_ntoa(*((struct in_addr *)h->h_addr));
INFO("web ip:%s", web_ip.c_str());
struct sockaddr_in serv_addr;
int sock =socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
INFO("socket() error");
return 1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(web_ip.c_str());
serv_addr.sin_port=htons(60315);
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) {
INFO("connect() error!");
return 1;
}
INFO("connect web server ok.");
/*
std::string::size_type found = country_code.find("\"");
if (found == std::string::npos)
return 1;
std::string strtemp = country_code.substr(found+1);
found = country_code.find("\"");
if (found == std::string::npos)
return 1;
strtemp = strtemp.substr(0,found - 1);
INFO("country code:%s",strtemp.c_str());*/
std::string strtemp;
strtemp += (char)1;
strtemp += device_id;
strtemp += (char)'\n';
strtemp += user_name;
strtemp += (char)'\n';
strtemp += password;
int ret=file_utl::write(sock, (char*)strtemp.c_str(), (int)strtemp.size());
char ip_packet_data[BUF_SIZE];
ret=file_utl::read(sock, ip_packet_data, BUF_SIZE);
if (ret < 2 + 4*sizeof(uint32_t))
return 1;
ip_packet_data[ret] = 0;
INFO("recv from web_server:%s", string_utl::HexEncode(std::string(ip_packet_data,ret)).c_str());
int pos=0;
int ret1 = ip_packet_data[pos++];
int ret2 = ip_packet_data[pos++];
uint32_t day_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t month_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t day_limit = ntohl(*(uint32_t*)(ip_packet_data + pos));
pos += sizeof(uint32_t);
uint32_t month_limit = ntohl(*(uint32_t*)(ip_packet_data + pos));
close(sock);
INFO("recv login:%d,%d,%x,%x,%x,%x" , ret1 , ret2, day_traffic , month_traffic, day_limit,month_limit);
/*
std::string ip_list;
ip_list.assign(ip_packet_data, ret);
std :: vector < std :: string > values;
values.clear();
string_utl::split_string(ip_list, ',', values);
if (values.empty()) {
printf("get ip fail.\n");
return 1;
}
std::string one_ip = values[0];
values.clear();
string_utl::split_string(ip_list, ':', values);
if (values.size() < 3) {
printf("parse ip addr fail.\n");
return 1;
}
g_protocol = std::stoi(values[0]);
target_test_ip = values[1]; // need to fix.
target_test_port = std::stoi(values[2]);
INFO("protocol:%d, server_ip:%s,port:%d", g_protocol, target_test_ip.c_str(), target_test_port);
*/
g_user_name = user_name;
g_password = password;
trafficCallback(day_traffic,month_traffic,day_limit,month_limit,ret1,ret2,target);
return 0;
}
| 34.73185 | 238 | 0.605677 | tinyvpn |
799affc25619cf70aca038f6e678b55d4664b2e7 | 1,194 | cpp | C++ | king/src/king/Utils/FileUtils.cpp | tobiasbu/king | 7a6892a93d5d4c5f14e2618104f2955281f0bada | [
"MIT"
] | 3 | 2017-03-10T13:57:25.000Z | 2017-05-31T19:05:35.000Z | king/src/king/Utils/FileUtils.cpp | tobiasbu/king | 7a6892a93d5d4c5f14e2618104f2955281f0bada | [
"MIT"
] | null | null | null | king/src/king/Utils/FileUtils.cpp | tobiasbu/king | 7a6892a93d5d4c5f14e2618104f2955281f0bada | [
"MIT"
] | null | null | null |
#include <king\Utils\FileUtils.hpp>
namespace king {
std::string FileUtils::getFileName(std::string path) {
int i = path.find_last_of('\\');
if (i != std::string::npos)
return path.substr(i + 1); // f contains the result :)
else {
i = path.find_last_of('/');
return path.substr(i + 1);
}
return path;
};
std::string FileUtils::getFileNameWithoutExtension(std::string fname) {
fname = getFileName(fname);
size_t pos = fname.rfind(("."));
if (pos == std::string::npos) //No extension.
return fname;
if (pos == 0) //. is at the front. Not an extension.
return fname;
return fname.substr(0, pos);
}
std::string FileUtils::getFileExtension(std::string fname) {
size_t pos = fname.find_last_of(".");
if (pos != std::string::npos)
return fname.substr(pos + 1);
return "";
}
std::string FileUtils::getFileDirectory(std::string path) {
std::string dir = path;
bool found = false;
for (int i = path.length() - 1; i >= 0; i--)
{
if (i == 0) {
dir = "";
break;
}
else {
if (path[i] == '\\' || path[i] == '/') {
dir = path.substr(0, i + 1);
break;
}
}
}
return dir;
}
} | 16.135135 | 72 | 0.571189 | tobiasbu |
799b1829f213293f3f5ef9a602f1c5f05003bf8e | 239 | cpp | C++ | model/variable.cpp | kalanzun/fire | 5a7f6ca413efa2c64109d36be9db0ca050a076cd | [
"MIT"
] | null | null | null | model/variable.cpp | kalanzun/fire | 5a7f6ca413efa2c64109d36be9db0ca050a076cd | [
"MIT"
] | null | null | null | model/variable.cpp | kalanzun/fire | 5a7f6ca413efa2c64109d36be9db0ca050a076cd | [
"MIT"
] | null | null | null | #include "variable.h"
Variable::Variable(QString label, int index, QObject *parent)
: QObject(parent)
, label(label)
, index(index)
{
}
QString Variable::getLabel()
{
return QString("<big><b>%1</b></big>").arg(label);
}
| 15.933333 | 61 | 0.631799 | kalanzun |
799fae5dabdccb69e094ad56a358f312baf8dfe2 | 3,636 | cpp | C++ | active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp | danielduberg/mav_active_3d_planning | 0790e7d26175bf7d315975a4d91548b56f9ee877 | [
"BSD-3-Clause"
] | 1 | 2021-01-05T10:17:04.000Z | 2021-01-05T10:17:04.000Z | active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp | danielduberg/mav_active_3d_planning | 0790e7d26175bf7d315975a4d91548b56f9ee877 | [
"BSD-3-Clause"
] | null | null | null | active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp | danielduberg/mav_active_3d_planning | 0790e7d26175bf7d315975a4d91548b56f9ee877 | [
"BSD-3-Clause"
] | null | null | null | #include "active_3d_planning_core/module/trajectory_evaluator/next_selector/subsequent_best_complete.h"
#include <algorithm>
#include <vector>
namespace active_3d_planning {
namespace next_selector {
// SubsequentBestComplete
ModuleFactoryRegistry::Registration<SubsequentBestComplete>
SubsequentBestComplete::registration("SubsequentBestComplete");
SubsequentBestComplete::SubsequentBestComplete(PlannerI &planner)
: NextSelector(planner) {}
void SubsequentBestComplete::setupFromParamMap(Module::ParamMap *param_map) {}
// This is super hacky because for some reason it returns an int and not a
// trajsegment* (which would allow us to select w/e a lot easier)
int SubsequentBestComplete::selectNextBest(TrajectorySegment *traj_in) {
std::vector<int> candidates = {0};
std::vector<TrajectorySegment *> bestSegment = {traj_in->children[0].get()};
double current_max = evaluateSingle(traj_in->children[0].get()).value;
for (int i = 1; i < traj_in->children.size(); ++i) {
auto current_value = evaluateSingle(traj_in->children[i].get());
if (current_value.value > current_max) {
current_max = current_value.value;
candidates.clear();
candidates.push_back(i);
bestSegment.clear();
bestSegment.push_back(current_value.traj);
} else if (current_value.value == current_max) {
candidates.push_back(i);
bestSegment.push_back(current_value.traj);
}
}
// randomize if multiple maxima (note this is not perfectly uniform, but shoud
// do for now)
int selected = rand() % candidates.size();
// here we expand the cadidated to include all parts up to the root and update
// the tree accordingly
//we do break info here... (TODO require info to overload operator + and fix this)
std::vector<TrajectorySegment *> allsegs;
auto tmptraj = bestSegment[selected];
//parent->parent because we dont want the base segment to be inserted aswell as this get choosen anyways
while (tmptraj->parent->parent) {
allsegs.insert(allsegs.begin(), tmptraj);
tmptraj = tmptraj->parent;
}
//add data
auto nextraj = traj_in->children[candidates[selected]].get();
for (auto seg : allsegs) {
auto currtime = nextraj->trajectory.back().time_from_start_ns;
for (auto &&trajPoint : seg->trajectory) {
trajPoint.time_from_start_ns += currtime;
nextraj->trajectory.push_back(trajPoint);
}
}
//adjust children (this will kill alot I think but is fine)
nextraj->children = std::move(bestSegment[selected]->children);
return candidates[selected];
}
ValueTrajectoryPair
SubsequentBestComplete::evaluateSingle(TrajectorySegment *traj_in) {
// Recursively find highest value
ValueTrajectoryPair res;
res.value = traj_in->value;
res.traj = traj_in;
for (int i = 0; i < traj_in->children.size(); ++i) {
res = std::max(res, evaluateSingle(traj_in->children[i].get()));
}
return res;
}
} // namespace next_selector
} // namespace active_3d_planning
| 45.45 | 116 | 0.59516 | danielduberg |
79a2c818f616bfa0ca48bae2e45f77a8c0fe8d76 | 1,470 | cpp | C++ | CPP.Part_2/week_3/algorithms/count_permutations.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | 4 | 2017-11-17T12:02:21.000Z | 2021-02-08T11:24:16.000Z | CPP.Part_2/week_3/algorithms/count_permutations.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | CPP.Part_2/week_3/algorithms/count_permutations.cpp | DGolgovsky/Courses | 01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0 | [
"Unlicense"
] | null | null | null | #include <deque>
#include <array>
#include <iostream>
#include <algorithm>
/*
template<class Iterator>
size_t count_permutations(Iterator p1, Iterator q1)
{
if (p1 == q1) return 1;
auto p = *reinterpret_cast<Iterator*>(&p1);
auto q = *reinterpret_cast<Iterator*>(&q1);
size_t count = 0;
std::sort(p, q);
do {
auto i1 = std::adjacent_find(p, q);
if (i1 == q)
count++;
} while (std::next_permutation(p, q));
return count;
}
*/
/* Better solution */
template <typename Iterator>
std::size_t count_permutations(Iterator p, Iterator q)
{
using ItType = typename std::iterator_traits<Iterator>::value_type;
if (p == q) {
return 1;
}
std::vector<ItType> v(p, q);
std::sort(v.begin(), v.end());
std::size_t perm_count = (std::adjacent_find(v.cbegin(), v.cend()) == v.cend());
while (std::next_permutation(v.begin(), v.end())) {
if (std::adjacent_find(v.cbegin(), v.cend()) == v.cend()) {
++perm_count;
}
}
return perm_count;
}
int main()
{
std::array<int, 3> a1 = {3,2,1};
size_t c1 = count_permutations(a1.begin(), a1.end()); // 6
std::cout << c1 << '\n';
std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_permutations(a2.begin(), a2.end()); // 36
std::cout << c2 << '\n';
std::deque<int> a3 = {1,2,2,3,4,4};
size_t c3 = count_permutations(a3.begin(), a3.end()); // 36
std::cout << c3 << '\n';
}
| 24.5 | 84 | 0.565306 | DGolgovsky |
79a4a0cf6e2b982d3814b0429367b6c799c0f0a9 | 1,164 | cpp | C++ | OOP_Noob/1/main4.cpp | Yuk1n0/Homework | 74030c6ba1947866913a2a57ab92850f29aef2dc | [
"MIT"
] | 3 | 2020-03-30T10:04:30.000Z | 2020-03-30T10:04:37.000Z | OOP_Noob/1/main4.cpp | Yuk1n0/Homework | 74030c6ba1947866913a2a57ab92850f29aef2dc | [
"MIT"
] | null | null | null | OOP_Noob/1/main4.cpp | Yuk1n0/Homework | 74030c6ba1947866913a2a57ab92850f29aef2dc | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
class myPoint
{
public:
myPoint(double x0 = 0.0, double y0 = 0.0) : x(x0), y(y0) { cout << "Start" << endl; }
myPoint(myPoint &np) : x(np.x), y(np.y) {}
double GetX() { return x; }
double GetY() { return y; }
void SetX(double x0) { x = x0; }
void SetY(double y0) { x = y0; }
void SetPoint(double x0, double y0)
{
x = x0;
y = y0;
}
void SetPoint(myPoint &np)
{
x = np.x;
y = np.y;
}
double GetLength(myPoint p)
{
return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}
void Printit() { cout << " (" << x << "," << y << ") "; }
private:
double x, y;
};
int main(void)
{
myPoint p1, p2(0, 1), p3(1, 0);
p1.Printit();
p2.Printit();
p3.Printit();
cout << endl;
double a, b, c, d, e;
a = p2.GetLength(p1);
b = p3.GetLength(p1);
c = p2.GetLength(p3);
cout << a << endl;
cout << b << endl;
cout << c << endl;
d = (1 / 2) * (a + b + c);
e = sqrt(d * (d - a) * (d - b) * (d - c));
cout << d << endl;
cout << e << endl;
return 0;
}
| 21.555556 | 89 | 0.455326 | Yuk1n0 |
79a55b4bd0d6ea16a645973861f67ad07fa16d93 | 7,345 | cpp | C++ | src/solvers/smt2/smt2_dec.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 412 | 2016-04-02T01:14:27.000Z | 2022-03-27T09:24:09.000Z | src/solvers/smt2/smt2_dec.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 4,671 | 2016-02-25T13:52:16.000Z | 2022-03-31T22:14:46.000Z | src/solvers/smt2/smt2_dec.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 266 | 2016-02-23T12:48:00.000Z | 2022-03-22T18:15:51.000Z | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include "smt2_dec.h"
#include <util/invariant.h>
#include <util/message.h>
#include <util/run.h>
#include <util/tempfile.h>
#include "smt2irep.h"
std::string smt2_dect::decision_procedure_text() const
{
// clang-format off
return "SMT2 " + logic + (use_FPA_theory ? " (with FPA)" : "") + " using " +
(solver==solvert::GENERIC?"Generic":
solver==solvert::BOOLECTOR?"Boolector":
solver==solvert::CPROVER_SMT2?"CPROVER SMT2":
solver==solvert::CVC3?"CVC3":
solver==solvert::CVC4?"CVC4":
solver==solvert::MATHSAT?"MathSAT":
solver==solvert::YICES?"Yices":
solver==solvert::Z3?"Z3":
"(unknown)");
// clang-format on
}
decision_proceduret::resultt smt2_dect::dec_solve()
{
++number_of_solver_calls;
temporary_filet temp_file_problem("smt2_dec_problem_", ""),
temp_file_stdout("smt2_dec_stdout_", ""),
temp_file_stderr("smt2_dec_stderr_", "");
const auto write_problem_to_file = [&](std::ofstream problem_out) {
cached_output << stringstream.str();
stringstream.str(std::string{});
write_footer();
problem_out << cached_output.str() << stringstream.str();
stringstream.str(std::string{});
};
write_problem_to_file(std::ofstream(
temp_file_problem(), std::ios_base::out | std::ios_base::trunc));
std::vector<std::string> argv;
std::string stdin_filename;
switch(solver)
{
case solvert::BOOLECTOR:
argv = {"boolector", "--smt2", temp_file_problem(), "-m"};
break;
case solvert::CPROVER_SMT2:
argv = {"smt2_solver"};
stdin_filename = temp_file_problem();
break;
case solvert::CVC3:
argv = {"cvc3",
"+model",
"-lang",
"smtlib",
"-output-lang",
"smtlib",
temp_file_problem()};
break;
case solvert::CVC4:
// The flags --bitblast=eager --bv-div-zero-const help but only
// work for pure bit-vector formulas.
argv = {"cvc4", "-L", "smt2", temp_file_problem()};
break;
case solvert::MATHSAT:
// The options below were recommended by Alberto Griggio
// on 10 July 2013
argv = {"mathsat",
"-input=smt2",
"-preprocessor.toplevel_propagation=true",
"-preprocessor.simplification=7",
"-dpll.branching_random_frequency=0.01",
"-dpll.branching_random_invalidate_phase_cache=true",
"-dpll.restart_strategy=3",
"-dpll.glucose_var_activity=true",
"-dpll.glucose_learnt_minimization=true",
"-theory.bv.eager=true",
"-theory.bv.bit_blast_mode=1",
"-theory.bv.delay_propagated_eqs=true",
"-theory.fp.mode=1",
"-theory.fp.bit_blast_mode=2",
"-theory.arr.mode=1"};
stdin_filename = temp_file_problem();
break;
case solvert::YICES:
// command = "yices -smt -e " // Calling convention for older versions
// Convention for 2.2.1
argv = {"yices-smt2", temp_file_problem()};
break;
case solvert::Z3:
argv = {"z3", "-smt2", temp_file_problem()};
break;
case solvert::GENERIC:
UNREACHABLE;
}
int res =
run(argv[0], argv, stdin_filename, temp_file_stdout(), temp_file_stderr());
if(res<0)
{
messaget log{message_handler};
log.error() << "error running SMT2 solver" << messaget::eom;
return decision_proceduret::resultt::D_ERROR;
}
std::ifstream in(temp_file_stdout());
return read_result(in);
}
decision_proceduret::resultt smt2_dect::read_result(std::istream &in)
{
std::string line;
decision_proceduret::resultt res=resultt::D_ERROR;
boolean_assignment.clear();
boolean_assignment.resize(no_boolean_variables, false);
typedef std::unordered_map<irep_idt, irept> valuest;
valuest parsed_values;
while(in)
{
auto parsed_opt = smt2irep(in, message_handler);
if(!parsed_opt.has_value())
break;
const auto &parsed = parsed_opt.value();
if(parsed.id()=="sat")
res=resultt::D_SATISFIABLE;
else if(parsed.id()=="unsat")
res=resultt::D_UNSATISFIABLE;
else if(parsed.id() == "unknown")
{
messaget log{message_handler};
log.error() << "SMT2 solver returned \"unknown\"" << messaget::eom;
return decision_proceduret::resultt::D_ERROR;
}
else if(
parsed.id().empty() && parsed.get_sub().size() == 1 &&
parsed.get_sub().front().get_sub().size() == 2)
{
const irept &s0=parsed.get_sub().front().get_sub()[0];
const irept &s1=parsed.get_sub().front().get_sub()[1];
// Examples:
// ( (B0 true) )
// ( (|__CPROVER_pipe_count#1| (_ bv0 32)) )
// ( (|some_integer| 0) )
// ( (|some_integer| (- 10)) )
parsed_values[s0.id()] = s1;
}
else if(
parsed.id().empty() && parsed.get_sub().size() == 2 &&
parsed.get_sub().front().id() == "error")
{
// We ignore errors after UNSAT because get-value after check-sat
// returns unsat will give an error.
if(res != resultt::D_UNSATISFIABLE)
{
const auto &message = id2string(parsed.get_sub()[1].id());
// Special case error handling
if(
solver == solvert::Z3 &&
message.find("must not contain quantifiers") != std::string::npos)
{
// We tried to "(get-value |XXXX|)" where |XXXX| is determined to
// include a quantified expression
// Nothing to do, this should be caught and value assigned by the
// set_to defaults later.
}
// Unhandled error, log the error and report it back up to caller
else
{
messaget log{message_handler};
log.error() << "SMT2 solver returned error message:\n"
<< "\t\"" << message << "\"" << messaget::eom;
return decision_proceduret::resultt::D_ERROR;
}
}
}
}
// If the result is not satisfiable don't bother updating the assignments and
// values (since we didn't get any), just return.
if(res != resultt::D_SATISFIABLE)
return res;
for(auto &assignment : identifier_map)
{
std::string conv_id = convert_identifier(assignment.first);
const irept &value = parsed_values[conv_id];
assignment.second.value = parse_rec(value, assignment.second.type);
}
// Booleans
for(unsigned v=0; v<no_boolean_variables; v++)
{
const std::string boolean_identifier = "B" + std::to_string(v);
boolean_assignment[v] = [&]() {
const auto found_parsed_value = parsed_values.find(boolean_identifier);
if(found_parsed_value != parsed_values.end())
return found_parsed_value->second.id() == ID_true;
// Work out the value based on what set_to was called with.
const auto found_set_value =
set_values.find('|' + boolean_identifier + '|');
if(found_set_value != set_values.end())
return found_set_value->second;
// Old code used the computation
// const irept &value=values["B"+std::to_string(v)];
// boolean_assignment[v]=(value.id()==ID_true);
return parsed_values[boolean_identifier].id() == ID_true;
}();
}
return res;
}
| 30.226337 | 79 | 0.607352 | tobireinhard |
79a9ff1cce485f56e1fbebcfe5df11990b15dfd1 | 11,661 | hh | C++ | include/click/flow/level/flow_level.hh | MassimoGirondi/fastclick | 71b9a3392c2e847a22de3c354be1d9f61216cb5b | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | include/click/flow/level/flow_level.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | include/click/flow/level/flow_level.hh | nic-bench/fastclick | 2812f0684050cec07e08f30d643ed121871cf25d | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | #ifndef CLICK_FLOWLEVEL_HH
#define CLICK_FLOWLEVEL_HH 1
#include <click/packet.hh>
#if HAVE_DPDK
#include <rte_flow.h>
#endif
#include "../common.hh"
#define FLOW_LEVEL_DEFINE(T,fnt) \
static FlowNodeData get_data_ptr(void* thunk, Packet* p) {\
return static_cast<T*>(thunk)->fnt(p);\
}
class FlowNode;
class FlowNodePtr {
private:
bool _is_leaf;
public :
union {
FlowNode* node;
FlowControlBlock* leaf;
void* ptr;
};
FlowNodePtr() : _is_leaf(false), ptr(0) {
}
FlowNodePtr(FlowNode* n) : _is_leaf(false), node(n) {
}
FlowNodePtr(FlowControlBlock* sfcb) : _is_leaf(true), leaf(sfcb) {
}
inline FlowNodeData data();
inline FlowNode* parent() const;
inline void set_data(FlowNodeData data);
inline void set_parent(FlowNode* parent);
inline void set_leaf(FlowControlBlock* l) {
leaf = l;
_is_leaf = true;
}
inline void set_node(FlowNode* n) {
node = n;
_is_leaf = false;
}
inline bool is_leaf() const {
return _is_leaf;
}
inline bool is_node() const {
return !_is_leaf;
}
/* inline FlowNodePtr duplicate() {
FlowNodePtr v;
v.ptr = ptr;
v._is_leaf = _is_leaf;
v.set_data(data());
return v;
}
*/
void print(int data_offset = -1) const;
//---
//Compile time functions
//---
FlowNodePtr optimize(Bitvector threads);
bool else_drop();
inline void traverse_all_leaves(std::function<void(FlowNodePtr*)>);
inline void check();
bool replace_leaf_with_node(FlowNode*, bool discard, Element* origin);
void node_combine_ptr(FlowNode* parent, FlowNodePtr, bool as_child, bool priority, bool no_dynamic, Element* origin);
void default_combine(FlowNode* parent, FlowNodePtr*, bool as_child, bool priority, Element* origin);
};
class FlowLevel {
private:
//bool deletable;
protected:
bool _dynamic;
#if HAVE_LONG_CLASSIFICATION
bool _islong = false;
#endif
public:
FlowLevel() :
//deletable(true),
_dynamic(false) {
};
typedef FlowNodeData (*GetDataFn)(void*, Packet* packet);
GetDataFn _get_data;
virtual ~FlowLevel() {};
/**
* Maximum value this level can return, included.
* Eg 255 for an array of 256 values. In most cases this is actually
* equal to the mask.
*/
virtual long unsigned get_max_value() = 0;
virtual void add_offset(int offset) {};
virtual bool is_mt_safe() const { return false;};
virtual bool is_usefull() {
return true;
}
/**
* Prune this level with another level, that is we know that this level
* is a sub-path of the other one, and there is no need to classify on
* the given level
* @return true if something changed
*/
virtual bool prune(FlowLevel*) {return false;};
virtual FlowNodePtr prune(FlowLevel* other, FlowNodeData data, FlowNode* node, bool &changed);
/**
* Tell if two node are of the same type, and on the same field/value/mask if applicable
*
* However this is not checking if runtime data and dynamic are equals
*/
virtual bool equals(FlowLevel* level) {
return typeid(*this) == typeid(*level) &&
#if HAVE_LONG_CLASSIFICATION
_islong == level->_islong &&
#endif
_dynamic == level->_dynamic;
}
inline FlowNodeData get_data(Packet* p) {
flow_assert(_get_data);
flow_assert(this);
return _get_data(this,p);
}
int current_level = 0;
FlowNode* create_node(FlowNode* parent, bool better, bool better_impl);
bool is_dynamic() {
return _dynamic;
}
void set_dynamic() {
_dynamic = true;
}
/*bool is_deletable() {
return deletable;
}*/
virtual String print() = 0;
#if HAVE_LONG_CLASSIFICATION
inline bool is_long() const {
return _islong;
}
#else
inline bool is_long() const {
return false;
}
#endif
FlowLevel* assign(FlowLevel* l) {
_dynamic = l->_dynamic;
//deletable = l->deletable;
#if HAVE_LONG_CLASSIFICATION
_islong = l->_islong;
#endif
return this;
}
virtual FlowLevel *duplicate() = 0;
virtual FlowLevel *optimize(FlowNode*) {
return this;
}
#if HAVE_DPDK
virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) {
return -1;
}
#endif
};
/**
* Dummy FlowLevel used for the default path before merging a table
*/
class FlowLevelDummy : public FlowLevel {
public:
FlowLevelDummy() {
_get_data = &get_data_ptr;
}
FLOW_LEVEL_DEFINE(FlowLevelDummy,get_data_dummy);
inline long unsigned get_max_value() {
return 0;
}
inline FlowNodeData get_data_dummy(Packet* packet) {
/* click_chatter("FlowLevelDummy should be stripped !");
abort();*/
return FlowNodeData();
}
String print() {
return String("ANY");
}
FlowLevel* duplicate() override {
return (new FlowLevelDummy())->assign(this);
}
#if HAVE_DPDK
virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) override {
rte_flow_item pat;
pat.type = RTE_FLOW_ITEM_TYPE_VOID;
next_layer = last_layer;
next_layer_offset = offset;
pattern.push_back(pat);
return 1;
}
#endif
};
/**
* FlowLevel based on the aggregate
*/
class FlowLevelAggregate : public FlowLevel {
public:
FlowLevelAggregate(int offset, uint32_t mask) : offset(offset), mask(mask) {
_get_data = &get_data_ptr;
}
FlowLevelAggregate() : FlowLevelAggregate(0,-1) {
_get_data = &get_data_ptr;
}
FLOW_LEVEL_DEFINE(FlowLevelAggregate,get_data_agg);
int offset;
uint32_t mask;
inline long unsigned get_max_value() {
return mask;
}
inline FlowNodeData get_data_agg(Packet* packet) {
FlowNodeData data;
data.data_32 = (AGGREGATE_ANNO(packet) >> offset) & mask;
return data;
}
String print() {
return String("AGG");
}
FlowLevel* duplicate() override {
return (new FlowLevelAggregate(0,-1))->assign(this);
}
};
/**
* FlowLevel based on the current thread
*/
class FlowLevelThread : public FlowLevel {
int _numthreads;
public:
FlowLevelThread(int nthreads) : _numthreads(nthreads) {
_get_data = &get_data_ptr;
}
FLOW_LEVEL_DEFINE(FlowLevelThread,get_data_thread);
virtual bool is_mt_safe() const override { return true;};
inline long unsigned get_max_value() {
return _numthreads - 1;
}
inline FlowNodeData get_data_thread(Packet*) {
return FlowNodeData((uint32_t)click_current_cpu_id());
}
String print() {
return String("THREAD");
}
FlowLevel* duplicate() override {
return (new FlowLevelThread(_numthreads))->assign(this);
}
};
class FlowLevelOffset : public FlowLevel {
protected:
int _offset;
public:
FlowLevelOffset(int offset) : _offset(offset) {
}
FlowLevelOffset() : FlowLevelOffset(0) {
}
void add_offset(int offset) {
_offset += offset;
}
int offset() const {
return _offset;
}
virtual int mask_size() const = 0;
virtual uint8_t get_mask(int o) const = 0;
bool equals(FlowLevel* level) {
return ((FlowLevel::equals(level))&& (_offset == dynamic_cast<FlowLevelOffset*>(level)->_offset));
}
#if HAVE_DPDK
virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) override;
#endif
};
static const char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','F'};
/**
* Flow level for any offset/mask of T bits
*/
template <typename T>
class FlowLevelGeneric : public FlowLevelOffset {
private:
T _mask;
public:
FlowLevelGeneric(T mask, int offset) : _mask(mask), FlowLevelOffset(offset) {
_get_data = &get_data_ptr;
}
FLOW_LEVEL_DEFINE(FlowLevelGeneric<T>,get_data);
FlowLevelGeneric() : FlowLevelGeneric(0,0) {
}
void set_match(int offset, T mask) {
_mask = mask;
_offset = offset;
}
T mask() const {
return _mask;
}
virtual int mask_size() const {
return sizeof(T);
}
virtual uint8_t get_mask(int o) const override {
if (o < _offset) //2 < 0
return 0;
if (o >= _offset + mask_size())
return 0;
return ((uint8_t*)&_mask)[o-_offset];
}
virtual bool is_usefull() override {
return _mask != 0;
}
//Remove from the mask what is already set in other
virtual bool prune(FlowLevel* other) override;
/**
* Remove children that don't match data at offset overlaps
*/
virtual FlowNodePtr prune(FlowLevel* other, FlowNodeData data, FlowNode* node, bool &changed) override;
inline long unsigned get_max_value() {
return _mask;
}
inline FlowNodeData get_data(Packet* packet) {
return FlowNodeData((T)(*((T*)(packet->data() + _offset)) & _mask));
}
String print();
FlowLevel* duplicate() override {
return (new FlowLevelGeneric<T>(_mask,_offset))->assign(this);
}
bool equals(FlowLevel* level) {
return ((FlowLevelOffset::equals(level)) && (_mask == dynamic_cast<FlowLevelGeneric<T>*>(level)->_mask));
}
virtual FlowLevel *optimize(FlowNode* parent) override;
};
/**
* Flow level for any offset/mask of T bits
*/
template <typename T>
class FlowLevelField : public FlowLevelOffset {
public:
FlowLevelField(int offset) : FlowLevelOffset(offset) {
_get_data = &get_data_ptr;
}
FLOW_LEVEL_DEFINE(FlowLevelField<T>,get_data);
FlowLevelField() : FlowLevelField(0) {
}
T mask() const {
return (T)-1;
}
virtual uint8_t get_mask(int o) const {
if (o < _offset)
return 0;
if (o >= _offset + mask_size())
return 0;
return 0xff;
}
virtual int mask_size() const {
return sizeof(T);
}
inline long unsigned get_max_value() {
return mask();
}
inline FlowNodeData get_data(Packet* packet) {
//click_chatter("FlowLevelField %d %x, sz %d",_offset,*(T*)(packet->data() + _offset),sizeof(T));
return FlowNodeData(*(T*)(packet->data() + _offset));
}
String print() {
StringAccum s;
s << _offset;
s << "/";
for (int i = 0; i < sizeof(T); i++) {
s << "FF";
}
return s.take_string();
}
FlowLevel* duplicate() override {
return (new FlowLevelField<T>(_offset))->assign(this);
}
};
using FlowLevelGeneric8 = FlowLevelGeneric<uint8_t>;
using FlowLevelGeneric16 = FlowLevelGeneric<uint16_t>;
using FlowLevelGeneric32 = FlowLevelGeneric<uint32_t>;
#if HAVE_LONG_CLASSIFICATION
using FlowLevelGeneric64 = FlowLevelGeneric<uint64_t>;
#endif
using FlowLevelField8 = FlowLevelField<uint8_t>;
using FlowLevelField16 = FlowLevelField<uint16_t>;
using FlowLevelField32 = FlowLevelField<uint32_t>;
#if HAVE_LONG_CLASSIFICATION
using FlowLevelField64 = FlowLevelField<uint64_t>;
#endif
#endif
| 23.462777 | 206 | 0.632364 | MassimoGirondi |
79ab026f56ed8d11e90f8f9e5beb32fb37518e9b | 220 | cpp | C++ | Tests/test2Flow.cpp | ZakosDryiakk/SystemsModel | 20906b4a32405fa7e6a90321a977142e471fc04f | [
"MIT"
] | null | null | null | Tests/test2Flow.cpp | ZakosDryiakk/SystemsModel | 20906b4a32405fa7e6a90321a977142e471fc04f | [
"MIT"
] | 3 | 2019-09-04T17:16:28.000Z | 2019-09-04T17:18:23.000Z | Tests/test2Flow.cpp | ZakosDryiakk/SystemsModel | 20906b4a32405fa7e6a90321a977142e471fc04f | [
"MIT"
] | null | null | null | #include "test2Flow.h"
using namespace std;
LogFlow::LogFlow() {}
LogFlow::LogFlow(string name):Flow(name) {}
LogFlow::~LogFlow() {}
void LogFlow::execute()
{
change = 0.01*s2->getEnergy()*(1-s2->getEnergy()/70);
} | 15.714286 | 54 | 0.663636 | ZakosDryiakk |
79ac28ac1a8fe33b6f9f66a2726c9f49604b030b | 33,869 | cpp | C++ | src/org/apache/poi/ss/format/CellNumberFormatter.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/format/CellNumberFormatter.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/ss/format/CellNumberFormatter.cpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/ss/format/CellNumberFormatter.java
#include <org/apache/poi/ss/format/CellNumberFormatter.hpp>
#include <java/lang/Appendable.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/CharSequence.hpp>
#include <java/lang/Character.hpp>
#include <java/lang/Class.hpp>
#include <java/lang/ClassCastException.hpp>
#include <java/lang/Double.hpp>
#include <java/lang/IllegalStateException.hpp>
#include <java/lang/Integer.hpp>
#include <java/lang/Iterable.hpp>
#include <java/lang/Math.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Number.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>
#include <java/lang/StringBuffer.hpp>
#include <java/lang/StringBuilder.hpp>
#include <java/text/DecimalFormat.hpp>
#include <java/text/DecimalFormatSymbols.hpp>
#include <java/text/FieldPosition.hpp>
#include <java/util/ArrayList.hpp>
#include <java/util/BitSet.hpp>
#include <java/util/Collection.hpp>
#include <java/util/Collections.hpp>
#include <java/util/Formatter.hpp>
#include <java/util/Iterator.hpp>
#include <java/util/List.hpp>
#include <java/util/ListIterator.hpp>
#include <java/util/Set.hpp>
#include <java/util/TreeSet.hpp>
#include <org/apache/poi/ss/format/CellFormatPart.hpp>
#include <org/apache/poi/ss/format/CellFormatType.hpp>
#include <org/apache/poi/ss/format/CellFormatter.hpp>
#include <org/apache/poi/ss/format/CellNumberFormatter_GeneralNumberFormatter.hpp>
#include <org/apache/poi/ss/format/CellNumberFormatter_Special.hpp>
#include <org/apache/poi/ss/format/CellNumberPartHandler.hpp>
#include <org/apache/poi/ss/format/CellNumberStringMod.hpp>
#include <org/apache/poi/ss/format/SimpleFraction.hpp>
#include <org/apache/poi/util/LocaleUtil.hpp>
#include <org/apache/poi/util/POILogFactory.hpp>
#include <org/apache/poi/util/POILogger.hpp>
#include <Array.hpp>
#include <SubArray.hpp>
#include <ObjectArray.hpp>
#include <cmath>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
namespace lang
{
typedef ::SubArray< ::java::lang::Iterable, ObjectArray > IterableArray;
} // lang
namespace util
{
typedef ::SubArray< ::java::util::Collection, ::java::lang::ObjectArray, ::java::lang::IterableArray > CollectionArray;
typedef ::SubArray< ::java::util::List, ::java::lang::ObjectArray, CollectionArray > ListArray;
} // util
} // java
template<typename T, typename U>
static T java_cast(U* u)
{
if(!u) return static_cast<T>(nullptr);
auto t = dynamic_cast<T>(u);
if(!t) throw new ::java::lang::ClassCastException();
return t;
}
template<typename T>
static T* npc(T* t)
{
if(!t) throw new ::java::lang::NullPointerException();
return t;
}
namespace
{
template<typename F>
struct finally_
{
finally_(F f) : f(f), moved(false) { }
finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; }
~finally_() { if(!moved) f(); }
private:
finally_(const finally_&); finally_& operator=(const finally_&);
F f;
bool moved;
};
template<typename F> finally_<F> finally(F f) { return finally_<F>(f); }
}
poi::ss::format::CellNumberFormatter::CellNumberFormatter(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
poi::ss::format::CellNumberFormatter::CellNumberFormatter(::java::lang::String* format)
: CellNumberFormatter(*static_cast< ::default_init_tag* >(0))
{
ctor(format);
}
poi::ss::format::CellNumberFormatter::CellNumberFormatter(::java::util::Locale* locale, ::java::lang::String* format)
: CellNumberFormatter(*static_cast< ::default_init_tag* >(0))
{
ctor(locale,format);
}
void poi::ss::format::CellNumberFormatter::init()
{
specials = new ::java::util::ArrayList();
integerSpecials = new ::java::util::ArrayList();
fractionalSpecials = new ::java::util::ArrayList();
numeratorSpecials = new ::java::util::ArrayList();
denominatorSpecials = new ::java::util::ArrayList();
exponentSpecials = new ::java::util::ArrayList();
exponentDigitSpecials = new ::java::util::ArrayList();
SIMPLE_NUMBER = new CellNumberFormatter_GeneralNumberFormatter(locale);
}
poi::util::POILogger*& poi::ss::format::CellNumberFormatter::LOG()
{
clinit();
return LOG_;
}
poi::util::POILogger* poi::ss::format::CellNumberFormatter::LOG_;
void poi::ss::format::CellNumberFormatter::ctor(::java::lang::String* format)
{
ctor(::poi::util::LocaleUtil::getUserLocale(), format);
}
void poi::ss::format::CellNumberFormatter::ctor(::java::util::Locale* locale, ::java::lang::String* format)
{
super::ctor(locale, format);
init();
auto ph = new CellNumberPartHandler();
auto descBuf = CellFormatPart::parseFormat(format, CellFormatType::NUMBER, ph);
exponent = npc(ph)->getExponent();
npc(specials)->addAll(static_cast< ::java::util::Collection* >(npc(ph)->getSpecials()));
improperFraction = npc(ph)->isImproperFraction();
if((npc(ph)->getDecimalPoint() != nullptr || npc(ph)->getExponent() != nullptr) && npc(ph)->getSlash() != nullptr) {
slash = nullptr;
numerator = nullptr;
} else {
slash = npc(ph)->getSlash();
numerator = npc(ph)->getNumerator();
}
auto const precision = interpretPrecision(npc(ph)->getDecimalPoint(), specials);
auto fractionPartWidth = int32_t(0);
if(npc(ph)->getDecimalPoint() != nullptr) {
fractionPartWidth = int32_t(1) + precision;
if(precision == 0) {
npc(specials)->remove(static_cast< ::java::lang::Object* >(npc(ph)->getDecimalPoint()));
decimalPoint = nullptr;
} else {
decimalPoint = npc(ph)->getDecimalPoint();
}
} else {
decimalPoint = nullptr;
}
if(decimalPoint != nullptr) {
afterInteger = decimalPoint;
} else if(exponent != nullptr) {
afterInteger = exponent;
} else if(numerator != nullptr) {
afterInteger = numerator;
} else {
afterInteger = nullptr;
}
if(exponent != nullptr) {
afterFractional = exponent;
} else if(numerator != nullptr) {
afterFractional = numerator;
} else {
afterFractional = nullptr;
}
auto scaleByRef = (new ::doubleArray({npc(ph)->getScale()}));
showGroupingSeparator = interpretIntegerCommas(descBuf, specials, decimalPoint, integerEnd(), fractionalEnd(), scaleByRef);
if(exponent == nullptr) {
scale = (*scaleByRef)[int32_t(0)];
} else {
scale = 1;
}
if(precision != 0) {
npc(fractionalSpecials)->addAll(static_cast< ::java::util::Collection* >(npc(specials)->subList(npc(specials)->indexOf(decimalPoint) + int32_t(1), fractionalEnd())));
}
if(exponent != nullptr) {
auto exponentPos = npc(specials)->indexOf(exponent);
npc(exponentSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(exponentPos, 2)));
npc(exponentDigitSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(exponentPos + int32_t(2))));
}
if(slash != nullptr) {
if(numerator != nullptr) {
npc(numeratorSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(npc(specials)->indexOf(numerator))));
}
npc(denominatorSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(npc(specials)->indexOf(slash) + int32_t(1))));
if(npc(denominatorSpecials)->isEmpty()) {
npc(numeratorSpecials)->clear();
maxDenominator = 1;
numeratorFmt = nullptr;
denominatorFmt = nullptr;
} else {
maxDenominator = maxValue(denominatorSpecials);
numeratorFmt = singleNumberFormat(numeratorSpecials);
denominatorFmt = singleNumberFormat(denominatorSpecials);
}
} else {
maxDenominator = 1;
numeratorFmt = nullptr;
denominatorFmt = nullptr;
}
npc(integerSpecials)->addAll(static_cast< ::java::util::Collection* >(npc(specials)->subList(0, integerEnd())));
if(exponent == nullptr) {
auto fmtBuf = new ::java::lang::StringBuffer(u"%"_j);
auto integerPartWidth = calculateIntegerPartWidth();
auto totalWidth = integerPartWidth + fractionPartWidth;
npc(npc(npc(npc(fmtBuf)->append(u'0'))->append(totalWidth))->append(u'.'))->append(precision);
npc(fmtBuf)->append(u"f"_j);
printfFmt = npc(fmtBuf)->toString();
decimalFmt = nullptr;
} else {
auto fmtBuf = new ::java::lang::StringBuffer();
auto first = true;
auto specialList = integerSpecials;
if(npc(integerSpecials)->size() == 1) {
npc(fmtBuf)->append(u"0"_j);
first = false;
} else
for (auto _i = npc(specialList)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
if(isDigitFmt(s)) {
npc(fmtBuf)->append(first ? u'#' : u'0');
first = false;
}
}
}
if(npc(fractionalSpecials)->size() > 0) {
npc(fmtBuf)->append(u'.');
for (auto _i = npc(fractionalSpecials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
if(isDigitFmt(s)) {
if(!first)
npc(fmtBuf)->append(u'0');
first = false;
}
}
}
}
npc(fmtBuf)->append(u'E');
placeZeros(fmtBuf, npc(exponentSpecials)->subList(2, npc(exponentSpecials)->size()));
decimalFmt = new ::java::text::DecimalFormat(npc(fmtBuf)->toString(), getDecimalFormatSymbols());
printfFmt = nullptr;
}
desc = npc(descBuf)->toString();
}
java::text::DecimalFormatSymbols* poi::ss::format::CellNumberFormatter::getDecimalFormatSymbols()
{
return ::java::text::DecimalFormatSymbols::getInstance(locale);
}
void poi::ss::format::CellNumberFormatter::placeZeros(::java::lang::StringBuffer* sb, ::java::util::List* specials)
{
clinit();
for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
if(isDigitFmt(s)) {
npc(sb)->append(u'0');
}
}
}
}
poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::insertMod(CellNumberFormatter_Special* special, ::java::lang::CharSequence* toAdd, int32_t where)
{
clinit();
return new CellNumberStringMod(special, toAdd, where);
}
poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::deleteMod(CellNumberFormatter_Special* start, bool startInclusive, CellNumberFormatter_Special* end, bool endInclusive)
{
clinit();
return new CellNumberStringMod(start, startInclusive, end, endInclusive);
}
poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::replaceMod(CellNumberFormatter_Special* start, bool startInclusive, CellNumberFormatter_Special* end, bool endInclusive, char16_t withChar)
{
clinit();
return new CellNumberStringMod(start, startInclusive, end, endInclusive, withChar);
}
java::lang::String* poi::ss::format::CellNumberFormatter::singleNumberFormat(::java::util::List* numSpecials)
{
clinit();
return ::java::lang::StringBuilder().append(u"%0"_j)->append(npc(numSpecials)->size())
->append(u"d"_j)->toString();
}
int32_t poi::ss::format::CellNumberFormatter::maxValue(::java::util::List* s)
{
clinit();
return static_cast< int32_t >(::java::lang::Math::round(::java::lang::Math::pow(10, npc(s)->size()) - int32_t(1)));
}
java::util::List* poi::ss::format::CellNumberFormatter::specialsFor(int32_t pos, int32_t takeFirst)
{
if(pos >= npc(specials)->size()) {
return ::java::util::Collections::emptyList();
}
auto it = npc(specials)->listIterator(pos + takeFirst);
auto last = java_cast< CellNumberFormatter_Special* >(npc(it)->next());
auto end = pos + takeFirst;
while (npc(it)->hasNext()) {
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next());
if(!isDigitFmt(s) || npc(s)->pos - npc(last)->pos > 1)
break;
end++;
last = s;
}
return npc(specials)->subList(pos, end + int32_t(1));
}
java::util::List* poi::ss::format::CellNumberFormatter::specialsFor(int32_t pos)
{
return specialsFor(pos, 0);
}
bool poi::ss::format::CellNumberFormatter::isDigitFmt(CellNumberFormatter_Special* s)
{
clinit();
return npc(s)->ch == u'0' || npc(s)->ch == u'?' || npc(s)->ch == u'#';
}
int32_t poi::ss::format::CellNumberFormatter::calculateIntegerPartWidth()
{
auto digitCount = int32_t(0);
for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
if(s == afterInteger) {
break;
} else if(isDigitFmt(s)) {
digitCount++;
}
}
}
return digitCount;
}
int32_t poi::ss::format::CellNumberFormatter::interpretPrecision(CellNumberFormatter_Special* decimalPoint, ::java::util::List* specials)
{
clinit();
auto idx = npc(specials)->indexOf(decimalPoint);
auto precision = int32_t(0);
if(idx != -int32_t(1)) {
auto it = npc(specials)->listIterator(idx + int32_t(1));
while (npc(it)->hasNext()) {
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next());
if(!isDigitFmt(s)) {
break;
}
precision++;
}
}
return precision;
}
bool poi::ss::format::CellNumberFormatter::interpretIntegerCommas(::java::lang::StringBuffer* sb, ::java::util::List* specials, CellNumberFormatter_Special* decimalPoint, int32_t integerEnd, int32_t fractionalEnd, ::doubleArray* scale)
{
clinit();
auto it = npc(specials)->listIterator(integerEnd);
auto stillScaling = true;
auto integerCommas = false;
while (npc(it)->hasPrevious()) {
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous());
if(npc(s)->ch != u',') {
stillScaling = false;
} else {
if(stillScaling) {
(*scale)[int32_t(0)] /= 1000;
} else {
integerCommas = true;
}
}
}
if(decimalPoint != nullptr) {
it = npc(specials)->listIterator(fractionalEnd);
while (npc(it)->hasPrevious()) {
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous());
if(npc(s)->ch != u',') {
break;
} else {
(*scale)[int32_t(0)] /= 1000;
}
}
}
it = npc(specials)->listIterator();
auto removed = int32_t(0);
while (npc(it)->hasNext()) {
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next());
npc(s)->pos -= removed;
if(npc(s)->ch == u',') {
removed++;
npc(it)->remove();
npc(sb)->deleteCharAt(npc(s)->pos);
}
}
return integerCommas;
}
int32_t poi::ss::format::CellNumberFormatter::integerEnd()
{
return (afterInteger == nullptr) ? npc(specials)->size() : npc(specials)->indexOf(afterInteger);
}
int32_t poi::ss::format::CellNumberFormatter::fractionalEnd()
{
return (afterFractional == nullptr) ? npc(specials)->size() : npc(specials)->indexOf(afterFractional);
}
void poi::ss::format::CellNumberFormatter::formatValue(::java::lang::StringBuffer* toAppendTo, ::java::lang::Object* valueObject)
{
auto value = npc((java_cast< ::java::lang::Number* >(valueObject)))->doubleValue();
value *= scale;
auto negative = value < 0;
if(negative)
value = -value;
double fractional = int32_t(0);
if(slash != nullptr) {
if(improperFraction) {
fractional = value;
value = 0;
} else {
fractional = std::fmod(value, 1.0);
value = static_cast< int64_t >(value);
}
}
::java::util::Set* mods = new ::java::util::TreeSet();
auto output = new ::java::lang::StringBuffer(localiseFormat(desc));
if(exponent != nullptr) {
writeScientific(value, output, mods);
} else if(improperFraction) {
writeFraction(value, nullptr, fractional, output, mods);
} else {
auto result = new ::java::lang::StringBuffer();
auto f = new ::java::util::Formatter(static_cast< ::java::lang::Appendable* >(result), locale);
{
auto finally0 = finally([&] {
npc(f)->close();
});
{
npc(f)->format(locale, printfFmt, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Double::valueOf(value))}));
}
}
if(numerator == nullptr) {
writeFractional(result, output);
writeInteger(result, output, integerSpecials, mods, showGroupingSeparator);
} else {
writeFraction(value, result, fractional, output, mods);
}
}
auto dfs = getDecimalFormatSymbols();
auto groupingSeparator = ::java::lang::Character::toString(npc(dfs)->getGroupingSeparator());
auto changes = npc(mods)->iterator();
auto nextChange = (npc(changes)->hasNext() ? java_cast< CellNumberStringMod* >(npc(changes)->next()) : static_cast< CellNumberStringMod* >(nullptr));
auto deletedChars = new ::java::util::BitSet();
auto adjust = int32_t(0);
for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
auto adjustedPos = npc(s)->pos + adjust;
if(!npc(deletedChars)->get(npc(s)->pos) && npc(output)->charAt(adjustedPos) == u'#') {
npc(output)->deleteCharAt(adjustedPos);
adjust--;
npc(deletedChars)->set(npc(s)->pos);
}
while (nextChange != nullptr && s == npc(nextChange)->getSpecial()) {
auto lenBefore = npc(output)->length();
auto modPos = npc(s)->pos + adjust;
{
int32_t delPos;
int32_t delEndPos;
int32_t modEndPos;
switch (npc(nextChange)->getOp()) {
case CellNumberStringMod::AFTER:
if(npc(npc(nextChange)->getToAdd())->equals(groupingSeparator) && npc(deletedChars)->get(npc(s)->pos)) {
break;
}
npc(output)->insert(modPos + int32_t(1), npc(nextChange)->getToAdd());
break;
case CellNumberStringMod::BEFORE:
npc(output)->insert(modPos, npc(nextChange)->getToAdd());
break;
case CellNumberStringMod::REPLACE:
delPos = npc(s)->pos;
if(!npc(nextChange)->isStartInclusive()) {
delPos++;
modPos++;
}
while (npc(deletedChars)->get(delPos)) {
delPos++;
modPos++;
}
delEndPos = npc(npc(nextChange)->getEnd())->pos;
if(npc(nextChange)->isEndInclusive()) {
delEndPos++;
}
modEndPos = delEndPos + adjust;
if(modPos < modEndPos) {
if(npc(u""_j)->equals(static_cast< ::java::lang::Object* >(npc(nextChange)->getToAdd()))) {
npc(output)->delete_(modPos, modEndPos);
} else {
auto fillCh = npc(npc(nextChange)->getToAdd())->charAt(0);
for (auto i = modPos; i < modEndPos; i++) {
npc(output)->setCharAt(i, fillCh);
}
}
npc(deletedChars)->set(delPos, delEndPos);
}
break;
default:
throw new ::java::lang::IllegalStateException(::java::lang::StringBuilder().append(u"Unknown op: "_j)->append(npc(nextChange)->getOp())->toString());
}
}
adjust += npc(output)->length() - lenBefore;
nextChange = (npc(changes)->hasNext()) ? java_cast< CellNumberStringMod* >(npc(changes)->next()) : static_cast< CellNumberStringMod* >(nullptr);
}
}
}
if(negative) {
npc(toAppendTo)->append(u'-');
}
npc(toAppendTo)->append(output);
}
void poi::ss::format::CellNumberFormatter::writeScientific(double value, ::java::lang::StringBuffer* output, ::java::util::Set* mods)
{
auto result = new ::java::lang::StringBuffer();
auto fractionPos = new ::java::text::FieldPosition(::java::text::DecimalFormat::FRACTION_FIELD);
npc(decimalFmt)->format(value, result, fractionPos);
writeInteger(result, output, integerSpecials, mods, showGroupingSeparator);
writeFractional(result, output);
auto ePos = npc(fractionPos)->getEndIndex();
auto signPos = ePos + int32_t(1);
auto expSignRes = npc(result)->charAt(signPos);
if(expSignRes != u'-') {
expSignRes = u'+';
npc(result)->insert(signPos, u'+');
}
auto it = npc(exponentSpecials)->listIterator(1);
auto expSign = java_cast< CellNumberFormatter_Special* >(npc(it)->next());
auto expSignFmt = npc(expSign)->ch;
if(expSignRes == u'-' || expSignFmt == u'+') {
npc(mods)->add(static_cast< ::java::lang::Object* >(replaceMod(expSign, true, expSign, true, expSignRes)));
} else {
npc(mods)->add(static_cast< ::java::lang::Object* >(deleteMod(expSign, true, expSign, true)));
}
auto exponentNum = new ::java::lang::StringBuffer(npc(result)->substring(signPos + int32_t(1)));
writeInteger(exponentNum, output, exponentDigitSpecials, mods, false);
}
void poi::ss::format::CellNumberFormatter::writeFraction(double value, ::java::lang::StringBuffer* result, double fractional, ::java::lang::StringBuffer* output, ::java::util::Set* mods)
{
if(!improperFraction) {
if(fractional == 0 && !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(numeratorSpecials)}))) {
writeInteger(result, output, integerSpecials, mods, false);
auto start = lastSpecial(integerSpecials);
auto end = lastSpecial(denominatorSpecials);
if(hasChar(u'?', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials), static_cast< ::java::util::List* >(numeratorSpecials), static_cast< ::java::util::List* >(denominatorSpecials)}))) {
npc(mods)->add(static_cast< ::java::lang::Object* >(replaceMod(start, false, end, true, u' ')));
} else {
npc(mods)->add(static_cast< ::java::lang::Object* >(deleteMod(start, false, end, true)));
}
return;
} else {
auto numNoZero = !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(numeratorSpecials)}));
auto intNoZero = !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials)}));
auto intOnlyHash = npc(integerSpecials)->isEmpty() || (npc(integerSpecials)->size() == 1 && hasChar(u'#', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials)})));
auto removeBecauseZero = fractional == 0 && (intOnlyHash || numNoZero);
auto removeBecauseFraction = fractional != 0 && intNoZero;
if(value == 0 && (removeBecauseZero || removeBecauseFraction)) {
auto start = lastSpecial(integerSpecials);
auto hasPlaceHolder = hasChar(u'?', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials), static_cast< ::java::util::List* >(numeratorSpecials)}));
auto sm = hasPlaceHolder ? replaceMod(start, true, numerator, false, u' ') : deleteMod(start, true, numerator, false);
npc(mods)->add(static_cast< ::java::lang::Object* >(sm));
} else {
writeInteger(result, output, integerSpecials, mods, false);
}
}
}
try {
int32_t n;
int32_t d;
if(fractional == 0 || (improperFraction && std::fmod(fractional, static_cast< double >(int32_t(1))) == 0)) {
n = static_cast< int32_t >(::java::lang::Math::round(fractional));
d = 1;
} else {
auto frac = SimpleFraction::buildFractionMaxDenominator(fractional, maxDenominator);
n = npc(frac)->getNumerator();
d = npc(frac)->getDenominator();
}
if(improperFraction) {
n += ::java::lang::Math::round(value * d);
}
writeSingleInteger(numeratorFmt, n, output, numeratorSpecials, mods);
writeSingleInteger(denominatorFmt, d, output, denominatorSpecials, mods);
} catch (::java::lang::RuntimeException* ignored) {
npc(LOG_)->log(::poi::util::POILogger::ERROR, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"error while fraction evaluation"_j), static_cast< ::java::lang::Object* >(ignored)}));
}
}
java::lang::String* poi::ss::format::CellNumberFormatter::localiseFormat(::java::lang::String* format)
{
auto dfs = getDecimalFormatSymbols();
if(npc(format)->contains(u","_j) && npc(dfs)->getGroupingSeparator() != u',') {
if(npc(format)->contains(u"."_j) && npc(dfs)->getDecimalSeparator() != u'.') {
format = replaceLast(format, u"\\."_j, u"[DECIMAL_SEPARATOR]"_j);
format = npc(npc(format)->replace(u',', npc(dfs)->getGroupingSeparator()))->replace(static_cast< ::java::lang::CharSequence* >(u"[DECIMAL_SEPARATOR]"_j), static_cast< ::java::lang::CharSequence* >(::java::lang::Character::toString(npc(dfs)->getDecimalSeparator())));
} else {
format = npc(format)->replace(u',', npc(dfs)->getGroupingSeparator());
}
} else if(npc(format)->contains(u"."_j) && npc(dfs)->getDecimalSeparator() != u'.') {
format = npc(format)->replace(u'.', npc(dfs)->getDecimalSeparator());
}
return format;
}
java::lang::String* poi::ss::format::CellNumberFormatter::replaceLast(::java::lang::String* text, ::java::lang::String* regex, ::java::lang::String* replacement)
{
clinit();
return npc(text)->replaceFirst(::java::lang::StringBuilder().append(u"(?s)(.*)"_j)->append(regex)->toString(), ::java::lang::StringBuilder().append(u"$1"_j)->append(replacement)->toString());
}
bool poi::ss::format::CellNumberFormatter::hasChar(char16_t ch, ::java::util::ListArray*/*...*/ numSpecials)
{
clinit();
for(auto specials : *npc(numSpecials)) {
for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
if(npc(s)->ch == ch) {
return true;
}
}
}
}
return false;
}
void poi::ss::format::CellNumberFormatter::writeSingleInteger(::java::lang::String* fmt, int32_t num, ::java::lang::StringBuffer* output, ::java::util::List* numSpecials, ::java::util::Set* mods)
{
auto sb = new ::java::lang::StringBuffer();
auto formatter = new ::java::util::Formatter(static_cast< ::java::lang::Appendable* >(sb), locale);
{
auto finally1 = finally([&] {
npc(formatter)->close();
});
{
npc(formatter)->format(locale, fmt, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Integer::valueOf(num))}));
}
}
writeInteger(sb, output, numSpecials, mods, false);
}
void poi::ss::format::CellNumberFormatter::writeInteger(::java::lang::StringBuffer* result, ::java::lang::StringBuffer* output, ::java::util::List* numSpecials, ::java::util::Set* mods, bool showGroupingSeparator)
{
auto dfs = getDecimalFormatSymbols();
auto decimalSeparator = ::java::lang::Character::toString(npc(dfs)->getDecimalSeparator());
auto groupingSeparator = ::java::lang::Character::toString(npc(dfs)->getGroupingSeparator());
auto pos = npc(result)->indexOf(decimalSeparator) - int32_t(1);
if(pos < 0) {
if(exponent != nullptr && numSpecials == integerSpecials) {
pos = npc(result)->indexOf(u"E"_j) - int32_t(1);
} else {
pos = npc(result)->length() - int32_t(1);
}
}
int32_t strip;
for (strip = 0; strip < pos; strip++) {
auto resultCh = npc(result)->charAt(strip);
if(resultCh != u'0' && resultCh != npc(dfs)->getGroupingSeparator()) {
break;
}
}
auto it = npc(numSpecials)->listIterator(npc(numSpecials)->size());
auto followWithGroupingSeparator = false;
CellNumberFormatter_Special* lastOutputIntegerDigit = nullptr;
auto digit = int32_t(0);
while (npc(it)->hasPrevious()) {
char16_t resultCh;
if(pos >= 0) {
resultCh = npc(result)->charAt(pos);
} else {
resultCh = u'0';
}
auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous());
followWithGroupingSeparator = showGroupingSeparator && digit > 0 && digit % int32_t(3) == 0;
auto zeroStrip = false;
if(resultCh != u'0' || npc(s)->ch == u'0' || npc(s)->ch == u'?' || pos >= strip) {
zeroStrip = npc(s)->ch == u'?' && pos < strip;
npc(output)->setCharAt(npc(s)->pos, (zeroStrip ? u' ' : resultCh));
lastOutputIntegerDigit = s;
}
if(followWithGroupingSeparator) {
npc(mods)->add(static_cast< ::java::lang::Object* >(insertMod(s, zeroStrip ? static_cast< ::java::lang::CharSequence* >(u" "_j) : static_cast< ::java::lang::CharSequence* >(groupingSeparator), CellNumberStringMod::AFTER)));
followWithGroupingSeparator = false;
}
digit++;
--pos;
}
auto extraLeadingDigits = new ::java::lang::StringBuffer();
if(pos >= 0) {
++pos;
extraLeadingDigits = new ::java::lang::StringBuffer(npc(result)->substring(int32_t(0), pos));
if(showGroupingSeparator) {
while (pos > 0) {
if(digit > 0 && digit % int32_t(3) == 0) {
npc(extraLeadingDigits)->insert(pos, groupingSeparator);
}
digit++;
--pos;
}
}
npc(mods)->add(static_cast< ::java::lang::Object* >(insertMod(lastOutputIntegerDigit, extraLeadingDigits, CellNumberStringMod::BEFORE)));
}
}
void poi::ss::format::CellNumberFormatter::writeFractional(::java::lang::StringBuffer* result, ::java::lang::StringBuffer* output)
{
int32_t digit;
int32_t strip;
if(npc(fractionalSpecials)->size() > 0) {
auto decimalSeparator = ::java::lang::Character::toString(npc(getDecimalFormatSymbols())->getDecimalSeparator());
digit = npc(result)->indexOf(decimalSeparator) + int32_t(1);
if(exponent != nullptr) {
strip = npc(result)->indexOf(u"e"_j) - int32_t(1);
} else {
strip = npc(result)->length() - int32_t(1);
}
while (strip > digit && npc(result)->charAt(strip) == u'0') {
strip--;
}
for (auto _i = npc(fractionalSpecials)->iterator(); _i->hasNext(); ) {
CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next());
{
auto resultCh = npc(result)->charAt(digit);
if(resultCh != u'0' || npc(s)->ch == u'0' || digit < strip) {
npc(output)->setCharAt(npc(s)->pos, resultCh);
} else if(npc(s)->ch == u'?') {
npc(output)->setCharAt(npc(s)->pos, u' ');
}
digit++;
}
}
}
}
void poi::ss::format::CellNumberFormatter::simpleValue(::java::lang::StringBuffer* toAppendTo, ::java::lang::Object* value)
{
npc(SIMPLE_NUMBER)->formatValue(toAppendTo, value);
}
poi::ss::format::CellNumberFormatter_Special* poi::ss::format::CellNumberFormatter::lastSpecial(::java::util::List* s)
{
clinit();
return java_cast< CellNumberFormatter_Special* >(npc(s)->get(npc(s)->size() - int32_t(1)));
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* poi::ss::format::CellNumberFormatter::class_()
{
static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.format.CellNumberFormatter", 44);
return c;
}
void poi::ss::format::CellNumberFormatter::clinit()
{
super::clinit();
static bool in_cl_init = false;
struct clinit_ {
clinit_() {
in_cl_init = true;
LOG_ = ::poi::util::POILogFactory::getLogger(static_cast< ::java::lang::Class* >(CellNumberFormatter::class_()));
}
};
if(!in_cl_init) {
static clinit_ clinit_instance;
}
}
java::lang::Class* poi::ss::format::CellNumberFormatter::getClass0()
{
return class_();
}
| 41.557055 | 278 | 0.597685 | pebble2015 |
79ade633f77a3915e418479db88f5a8d8db54a74 | 523 | cpp | C++ | 7.06/7_06.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | null | null | null | 7.06/7_06.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | null | null | null | 7.06/7_06.cpp | dengxianglong/cplusplusprimerplusstudy | eefc5d7bf5ab31186c04171fadade3552838f4b2 | [
"MIT"
] | 1 | 2018-08-29T07:40:20.000Z | 2018-08-29T07:40:20.000Z | #include<iostream>
const int arsize=8;
int sum_arr(int arr[],int n);
int main()
{
using namespace std;
int cookies[arsize]={1,2,4,8,13,32,64,128};
cout<<cookies<<endl;
cout<<sizeof cookies<<endl;
int sum=sum_arr(cookies,arsize);
cout<<sum<<endl;
sum=sum_arr(cookies,3);
cout<<sum<<endl;
sum=sum_arr(cookies+4,4);
cout<<sum<<endl;
return 0;
}
int sum_arr(int arr[],int n)
{
using namespace std;
int total=0;
cout<<arr<<endl;
cout<<sizeof arr<<endl;
for(int i=0;i<n;i++)
total=total+arr[i];
return total;
} | 19.37037 | 44 | 0.67304 | dengxianglong |
79ae5370f0233194782d48bd327f2802cebb3302 | 1,120 | cpp | C++ | Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp | jesushilarioh/C-Plus-Plus | bbff921460ac4267af48558f040c7d82ccf42d5e | [
"MIT"
] | 3 | 2019-10-28T01:12:46.000Z | 2021-10-16T09:16:31.000Z | Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | null | null | null | Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp | jesushilariohernandez/DelMarCSi.cpp | 6dd7905daea510452691fd25b0e3b0d2da0b06aa | [
"MIT"
] | 4 | 2020-04-10T17:22:17.000Z | 2021-11-04T14:34:00.000Z | /********************************************************************
*
* 003. Ocean Levels
*
* Assuming the ocean’s level is currently rising at
* about 1.5 millimeters per year, write a program that
* displays a table showing the number of
* millimeters that the ocean will have risen each year for
* the next 25 years.
*
* Jesus Hilario Hernandez
* March 12th 2018
*
********************************************************************/
#include <iostream>
using namespace std;
int main()
{
// Constants
const float MIL_PER_YEAR = 1.5; // 1.5 millimeters per year.
// Variables
float num_of_mil_each_year = 0; // Initialize counter.
// Display a table of mil risen each year (25 years)
cout << "--------------------------------------------------\n";
for (int i = 1; i <= 25; i++)
{
num_of_mil_each_year += MIL_PER_YEAR;
cout << "Year " << i << ": " << num_of_mil_each_year << endl;
}
cout << "--------------------------------------------------\n";
// Terminate program
return 0;
}
| 28.717949 | 72 | 0.460714 | jesushilarioh |
79b1e0f70579f6379503877afa7a459c78651cb5 | 3,236 | cpp | C++ | studio/src/sequence/key_item.cpp | blagodarin/aulos | c78ec06fd812c889ec618ac2e9f0cab9ad9db756 | [
"Apache-2.0"
] | null | null | null | studio/src/sequence/key_item.cpp | blagodarin/aulos | c78ec06fd812c889ec618ac2e9f0cab9ad9db756 | [
"Apache-2.0"
] | null | null | null | studio/src/sequence/key_item.cpp | blagodarin/aulos | c78ec06fd812c889ec618ac2e9f0cab9ad9db756 | [
"Apache-2.0"
] | null | null | null | // This file is part of the Aulos toolkit.
// Copyright (C) Sergei Blagodarin.
// SPDX-License-Identifier: Apache-2.0
#include "key_item.hpp"
#include "../theme.hpp"
#include <QPainter>
namespace
{
enum class KeyStyle : size_t
{
White,
Black,
};
}
struct KeyItem::StyleInfo
{
struct Colors
{
QColor _normal;
QColor _hovered;
QColor _pressed;
const QColor& operator()(bool hovered, bool pressed) const noexcept
{
return pressed ? _pressed : (hovered ? _hovered : _normal);
}
};
qreal _width;
Colors _backgroundColors;
Colors _borderColors;
Colors _textColors;
qreal _z;
};
const std::array<KeyItem::StyleInfo, 2> KeyItem::kStyleInfo{
StyleInfo{ kWhiteKeyWidth, { "#fff", "#fdd", "#fcc" }, { "#aaa", "#aaa", "#aaa" }, { "#999", "#944", "#900" }, 0.5 },
StyleInfo{ kBlackKeyWidth, { "#000", "#200", "#300" }, { "#555", "#500", "#500" }, { "#999", "#f99", "#f99" }, 1.0 },
};
struct KeyItem::NoteInfo
{
QString _name;
qreal _y;
qreal _height;
qreal _textOffset;
KeyStyle _style;
};
const std::array<KeyItem::NoteInfo, aulos::kNotesPerOctave> KeyItem::kNoteInfo{
NoteInfo{ QStringLiteral("C%1"), 10.5, 1.5, 0.5, KeyStyle::White },
NoteInfo{ QStringLiteral("C#%1"), 10.0, 1.0, 0.0, KeyStyle::Black },
NoteInfo{ QStringLiteral("D%1"), 8.5, 2.0, 0.5, KeyStyle::White },
NoteInfo{ QStringLiteral("D#%1"), 8.0, 1.0, 0.0, KeyStyle::Black },
NoteInfo{ QStringLiteral("E%1"), 7.0, 1.5, 0.0, KeyStyle::White },
NoteInfo{ QStringLiteral("F%1"), 5.5, 1.5, 0.5, KeyStyle::White },
NoteInfo{ QStringLiteral("F#%1"), 5.0, 1.0, 0.0, KeyStyle::Black },
NoteInfo{ QStringLiteral("G%1"), 3.5, 2.0, 0.5, KeyStyle::White },
NoteInfo{ QStringLiteral("G#%1"), 3.0, 1.0, 0.0, KeyStyle::Black },
NoteInfo{ QStringLiteral("A%1"), 1.5, 2.0, 0.5, KeyStyle::White },
NoteInfo{ QStringLiteral("A#%1"), 1.0, 1.0, 0.0, KeyStyle::Black },
NoteInfo{ QStringLiteral("B%1"), 0.0, 1.5, 0.0, KeyStyle::White },
};
KeyItem::KeyItem(aulos::Note note, QGraphicsItem* parent)
: ButtonItem{ Mode::Press, parent }
, _octave{ static_cast<size_t>(note) / kNoteInfo.size() }
, _noteInfo{ kNoteInfo[static_cast<size_t>(note) % kNoteInfo.size()] }
, _styleInfo{ kStyleInfo[static_cast<size_t>(_noteInfo._style)] }
{
setPos(0, ((aulos::kOctaveCount - 1 - _octave) * kNoteInfo.size() + _noteInfo._y) * kNoteHeight);
setZValue(_styleInfo._z);
}
QRectF KeyItem::boundingRect() const
{
return { 0, 0, _styleInfo._width, _noteInfo._height * kNoteHeight };
}
void KeyItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
const auto rect = boundingRect();
painter->setBrush(_styleInfo._backgroundColors(isHovered(), isPressed()));
painter->setPen(Qt::transparent);
painter->drawRect(rect);
painter->setPen(_styleInfo._borderColors(isHovered(), isPressed()));
painter->drawLine(rect.topLeft(), rect.topRight());
painter->drawLine(rect.topRight(), rect.bottomRight());
painter->drawLine(rect.bottomRight(), rect.bottomLeft());
painter->setPen(_styleInfo._textColors(isHovered(), isPressed()));
painter->drawText(QRectF{ { 0, _noteInfo._textOffset * kNoteHeight }, QSizeF{ _styleInfo._width - kNoteHeight * 0.125, kNoteHeight } }, Qt::AlignVCenter | Qt::AlignRight, _noteInfo._name.arg(_octave));
}
| 33.020408 | 202 | 0.680779 | blagodarin |
79b22f57db86656ee8df7a3a06f815cd61b8ff54 | 497 | cc | C++ | src/type/type.cc | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | 1 | 2020-11-24T05:24:26.000Z | 2020-11-24T05:24:26.000Z | src/type/type.cc | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | null | null | null | src/type/type.cc | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | null | null | null | #include <type/type.hh>
#include <type/polymorphic.hh>
namespace type
{
Type::Type()
{}
Type::~Type()
{}
bool Type::compatible_with(const Type& t)
{
if (&t == &Polymorphic::instance())
return true;
return this == &t;
}
std::ostream& operator<<(std::ostream& o, const type::Type& type)
{
type.dump(o);
return o;
}
std::string Type::cpp_type() const
{
return "lol";
}
} // namespace type
| 15.53125 | 69 | 0.515091 | Nakrez |
79b36db545d6c2a2a4385ec454ad1e5e6867a9d2 | 1,070 | cpp | C++ | libglplayground/src/element_buffer_object.cpp | jbeda/libglplayground | d35b5660e305d186e9ea5c87ee5d23365868d0ce | [
"Apache-2.0"
] | 2 | 2021-06-20T01:52:51.000Z | 2021-07-06T07:26:35.000Z | libglplayground/src/element_buffer_object.cpp | jbeda/libglplayground | d35b5660e305d186e9ea5c87ee5d23365868d0ce | [
"Apache-2.0"
] | 129 | 2021-06-23T10:19:01.000Z | 2021-11-11T10:17:24.000Z | libglplayground/src/element_buffer_object.cpp | jbeda/libglplayground | d35b5660e305d186e9ea5c87ee5d23365868d0ce | [
"Apache-2.0"
] | 1 | 2021-07-05T21:10:23.000Z | 2021-07-05T21:10:23.000Z | #include "libglppch.h"
#include "element_buffer_object.h"
namespace libplayground {
namespace gl {
element_buffer_object::element_buffer_object(const std::vector<uint32_t>& data) {
glGenBuffers(1, &this->m_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->m_id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, data.size() * sizeof(uint32_t), data.data(), GL_STATIC_DRAW); // for now
this->m_index_count = data.size();
}
element_buffer_object::~element_buffer_object() {
glDeleteBuffers(1, &this->m_id);
}
void element_buffer_object::bind() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->m_id);
}
void element_buffer_object::unbind() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void element_buffer_object::draw(GLenum mode) {
glDrawElements(mode, (GLsizei)this->m_index_count, GL_UNSIGNED_INT, nullptr);
}
GLuint element_buffer_object::get() {
return this->m_id;
}
}
} | 39.62963 | 122 | 0.628972 | jbeda |
79bbe8c0ca5fcfa0a553799eeb1b7d7702cd4a8d | 305 | cpp | C++ | src/parser_brute_force.cpp | Auterion/mavlink-fuzz-testing | 9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1 | [
"BSD-3-Clause"
] | 9 | 2019-08-20T17:04:28.000Z | 2021-06-29T11:28:29.000Z | src/parser_brute_force.cpp | Auterion/mavlink-fuzz-testing | 9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1 | [
"BSD-3-Clause"
] | null | null | null | src/parser_brute_force.cpp | Auterion/mavlink-fuzz-testing | 9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1 | [
"BSD-3-Clause"
] | 2 | 2020-08-03T04:57:13.000Z | 2022-03-25T02:51:04.000Z | #include <common/mavlink.h>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
for (size_t i = 0; i < Size; ++i) {
mavlink_message_t message;
mavlink_status_t status;
mavlink_parse_char(MAVLINK_COMM_0, Data[i], &message, &status);
}
return 0;
}
| 27.727273 | 73 | 0.652459 | Auterion |
79bd11fbcf5ef5a4d6a1c2aafb0bce8465b5b751 | 377 | hpp | C++ | srook/semaphore.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | 1 | 2018-07-01T07:54:37.000Z | 2018-07-01T07:54:37.000Z | srook/semaphore.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | null | null | null | srook/semaphore.hpp | falgon/srookCppLibraries | ebcfacafa56026f6558bcd1c584ec774cc751e57 | [
"MIT"
] | null | null | null | // Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_SEMAPHORE_HPP
#define INCLUDED_SROOK_SEMAPHORE_HPP
#include <srook/semaphore/semaphore.hpp>
#include <srook/semaphore/timed_semaphore.hpp>
#include <srook/semaphore/binary_semaphore.hpp>
#include <srook/semaphore/binary_timed_semaphore.hpp>
#include <srook/semaphore/generic.hpp>
#endif
| 37.7 | 66 | 0.830239 | falgon |
79c106420a33dc215d662329fb09b207588d2d91 | 1,445 | cpp | C++ | src/utils/logger.cpp | hir12111/pvAccessCPP | 50b1d01ba67d89a7b96cf614b38b43672086ff69 | [
"MIT"
] | 9 | 2015-02-09T08:58:38.000Z | 2021-02-26T03:17:03.000Z | src/utils/logger.cpp | hir12111/pvAccessCPP | 50b1d01ba67d89a7b96cf614b38b43672086ff69 | [
"MIT"
] | 165 | 2015-06-10T11:27:33.000Z | 2022-02-23T00:25:46.000Z | src/utils/logger.cpp | hir12111/pvAccessCPP | 50b1d01ba67d89a7b96cf614b38b43672086ff69 | [
"MIT"
] | 22 | 2015-04-29T19:00:49.000Z | 2021-11-10T12:45:07.000Z | /**
* Copyright - See the COPYRIGHT that is included with this distribution.
* pvAccessCPP is distributed subject to a Software License Agreement found
* in file LICENSE that is included with this distribution.
*/
#include <fstream>
#include <iostream>
#include <time.h>
#include <cstring>
#include <stdio.h>
#include <epicsExit.h>
#include <errlog.h>
#include <epicsTime.h>
#include <pv/noDefaultMethods.h>
#include <pv/lock.h>
#include <pv/pvType.h>
#define epicsExportSharedSymbols
#include <pv/logger.h>
using namespace epics::pvData;
using std::ofstream;
using std::ios;
using std::endl;
namespace epics {
namespace pvAccess {
#define TIMETEXTLEN 32
static pvAccessLogLevel g_pvAccessLogLevel = logLevelInfo;
void pvAccessLog(pvAccessLogLevel level, const char* format, ...)
{
// TODO lock
if (level >= g_pvAccessLogLevel)
{
char timeText[TIMETEXTLEN];
epicsTimeStamp tsNow;
epicsTimeGetCurrent(&tsNow);
epicsTimeToStrftime(timeText, TIMETEXTLEN, "%Y-%m-%dT%H:%M:%S.%03f", &tsNow);
printf("%s ", timeText);
va_list arg;
va_start(arg, format);
vprintf(format, arg);
va_end(arg);
printf("\n");
fflush(stdout); // needed for WIN32
}
}
void pvAccessSetLogLevel(pvAccessLogLevel level)
{
g_pvAccessLogLevel = level;
}
bool pvAccessIsLoggable(pvAccessLogLevel level)
{
return level >= g_pvAccessLogLevel;
}
}
}
| 20.352113 | 85 | 0.687889 | hir12111 |
79c1204b5529a04cc26832618439aab55b99d7f6 | 13,071 | cpp | C++ | diamond-dpct/masking.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | diamond-dpct/masking.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | diamond-dpct/masking.dp.cpp | jchlanda/oneAPI-DirectProgramming | 82a1be635f89b4b2a83e36965a60b19fd71e46b2 | [
"BSD-3-Clause"
] | null | null | null | /****
DIAMOND protein aligner
Copyright (C) 2013-2017 Benjamin Buchfink <buchfink@gmail.com>
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 <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include "../diamond-sycl/src/basic/masking.h"
#include <cmath>
#define SEQ_LEN 33
inline double firstRepeatOffsetProb(const double probMult, const int maxRepeatOffset) {
if (probMult < 1 || probMult > 1)
return (1 - probMult) / (1 - sycl::pow(probMult, (double)maxRepeatOffset));
else
return 1.0 / maxRepeatOffset;
}
void maskProbableLetters(const int size,
unsigned char *seqBeg,
const float *probabilities,
const unsigned char *maskTable) {
const double minMaskProb = 0.5;
for (int i=0; i<size; i++)
if (probabilities[i] >= minMaskProb)
seqBeg[i] = maskTable[seqBeg[i]];
}
int calcRepeatProbs(float *letterProbs,
const unsigned char *seqBeg,
const int size,
const int maxRepeatOffset,
const double *likelihoodRatioMatrix, // 64 by 64 matrix,
const double b2b,
const double f2f0,
const double f2b,
const double b2fLast_inv,
const double *pow_lkp,
double *foregroundProbs,
const int scaleStepSize,
double *scaleFactors)
{
double backgroundProb = 1.0;
for (int k=0; k < size ; k++) {
const int v0 = seqBeg[k];
const int k_cap = k < maxRepeatOffset ? k : maxRepeatOffset;
const int pad1 = k_cap - 1;
const int pad2 = maxRepeatOffset - k_cap; // maxRepeatOffset - k, then 0 when k > maxRepeatOffset
const int pad3 = k - k_cap; // 0 , then maxRepeatOffset - k when k > maxRepeatOffset
double accu = 0;
for (int i = 0; i < k; i++) {
const int idx1 = pad1 - i;
const int idx2 = pad2 + i;
const int idx3 = pad3 + i;
const int v1 = seqBeg[idx3];
accu += foregroundProbs[idx1];
foregroundProbs[idx1] = ( (f2f0 * foregroundProbs[idx1]) +
(backgroundProb * pow_lkp[idx2]) ) *
likelihoodRatioMatrix[v0*size+v1];
}
backgroundProb = (backgroundProb * b2b) + (accu * f2b);
if (k % scaleStepSize == scaleStepSize - 1) {
const double scale = 1 / backgroundProb;
scaleFactors[k / scaleStepSize] = scale;
for (int i=0; i< k_cap; i++)
foregroundProbs[i] = foregroundProbs[i] * scale;
backgroundProb = 1;
}
letterProbs[k] = (float)(backgroundProb);
}
double accu = 0;
for (int i=0 ; i < maxRepeatOffset; i++) {
accu += foregroundProbs[i];
foregroundProbs[i] = f2b;
}
const double fTot = backgroundProb * b2b + accu * f2b;
backgroundProb = b2b;
const double fTot_inv = 1/ fTot ;
for (int k=(size-1) ; k >= 0 ; k--){
double nonRepeatProb = letterProbs[k] * backgroundProb * fTot_inv;
letterProbs[k] = 1 - (float)(nonRepeatProb);
//const int k_cap = std::min(k, maxRepeatOffset);
const int k_cap = k < maxRepeatOffset ? k : maxRepeatOffset;
if (k % scaleStepSize == scaleStepSize - 1) {
const double scale = scaleFactors[k/ scaleStepSize];
for (int i=0; i< k_cap; i++)
foregroundProbs[i] = foregroundProbs[i] * scale;
backgroundProb *= scale;
}
const double c0 = f2b * backgroundProb;
const int v0= seqBeg[k];
double accu = 0;
for (int i = 0; i < k_cap; i++) {
const int v1 = seqBeg[k-(i+1)];
const double f = foregroundProbs[i] * likelihoodRatioMatrix[v0*size+v1];
accu += pow_lkp[k_cap-(i+1)]*f;
foregroundProbs[i] = c0 + f2f0 * f;
}
const double p = k > maxRepeatOffset ? 1. : pow_lkp[maxRepeatOffset - k]*b2fLast_inv;
backgroundProb = (b2b * backgroundProb) + accu*p;
}
const double bTot = backgroundProb;
return (sycl::fabs(fTot - bTot) >
sycl::fmax((double)fTot, (double)bTot) / 1e6);
}
void
maskSequences(unsigned char * seqs,
const double * likelihoodRatioMatrix,
const unsigned char * maskTable,
const int size ,
const int maxRepeatOffset ,
const double repeatProb ,
const double repeatEndProb ,
const double repeatOffsetProbDecay ,
const double firstGapProb ,
const double otherGapProb ,
const double minMaskProb ,
int seqs_len ,
sycl::nd_item<3> item_ct1)
{
int gid = item_ct1.get_group(2) * item_ct1.get_local_range().get(2) +
item_ct1.get_local_id(2);
if (gid >= seqs_len) return;
unsigned char* seqBeg = seqs+gid*33;
float probabilities[SEQ_LEN];
const double b2b = 1 - repeatProb;
const double f2f0 = 1 - repeatEndProb;
const double f2b = repeatEndProb;
const double b2fGrowth = 1 / repeatOffsetProbDecay;
const double b2fLast = repeatProb * firstRepeatOffsetProb(b2fGrowth, maxRepeatOffset);
const double b2fLast_inv = 1 / b2fLast ;
double p = b2fLast;
double ar_1[50];
for (int i=0 ; i < maxRepeatOffset; i++){
ar_1[i] = p ;
p *= b2fGrowth;
}
const int scaleStepSize = 16;
double scaleFactors[SEQ_LEN / scaleStepSize];
double foregroundProbs[50];
for (int i=0 ; i < maxRepeatOffset; i++){
foregroundProbs[i] = 0;
};
const int err = calcRepeatProbs(probabilities,seqBeg, size,
maxRepeatOffset, likelihoodRatioMatrix,
b2b, f2f0, f2b,
b2fLast_inv,ar_1,foregroundProbs,scaleStepSize, scaleFactors);
//if (err) printf("tantan: warning: possible numeric inaccuracy\n");
maskProbableLetters(size,seqBeg, probabilities, maskTable);
}
auto_ptr<Masking> Masking::instance;
const uint8_t Masking::bit_mask = 128;
Masking::Masking(const Score_matrix &score_matrix)
{
const double lambda = score_matrix.lambda(); // 0.324032
for (unsigned i = 0; i < size; ++i) {
mask_table_x_[i] = value_traits.mask_char;
mask_table_bit_[i] = (uint8_t)i | bit_mask;
for (unsigned j = 0; j < size; ++j)
if (i < value_traits.alphabet_size && j < value_traits.alphabet_size)
likelihoodRatioMatrix_[i][j] = exp(lambda * score_matrix(i, j));
}
std::copy(likelihoodRatioMatrix_, likelihoodRatioMatrix_ + size, probMatrixPointers_);
int firstGapCost = score_matrix.gap_extend() + score_matrix.gap_open();
firstGapProb_ = exp(-lambda * firstGapCost);
otherGapProb_ = exp(-lambda * score_matrix.gap_extend());
firstGapProb_ /= (1 - otherGapProb_);
}
void Masking::operator()(Letter *seq, size_t len) const
{
tantan::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50,
(tantan::const_double_ptr*)probMatrixPointers_,
0.005, 0.05,
0.9,
0, 0,
0.5, (const tantan::uchar*)mask_table_x_);
}
unsigned char* Masking::call_opt(Sequence_set &seqs) const
{
dpct::device_ext &dev_ct1 = dpct::get_current_device();
sycl::queue &q_ct1 = dev_ct1.default_queue();
const int n = seqs.get_length();
int total = 0;
for (int i=0; i < n; i++)
total += seqs.length(i);
printf("There are %d sequences and the total sequence length is %d\n", n, total);
unsigned char *seqs_device = NULL;
posix_memalign((void**)&seqs_device, 1024, total);
unsigned char *p = seqs_device;
for (int i=0; i < n; i++) {
memcpy(p, seqs.ptr(i), seqs.length(i));
p += seqs.length(i);
}
double *probMat_device = NULL;
posix_memalign((void**)&probMat_device, 1024, size*size*sizeof(double));
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
probMat_device[i*size+j] = probMatrixPointers_[i][j];
unsigned char *mask_table_device = NULL;
posix_memalign((void**)&mask_table_device, 1024, size*sizeof(unsigned char));
for (int i = 0; i < size; i++)
mask_table_device[i] = mask_table_x_[i];
int len = 33;
printf("Timing the mask sequences on device...\n");
Timer t;
t.start();
const int size = len;
const int maxRepeatOffset = 50;
const double repeatProb = 0.005;
const double repeatEndProb = 0.05;
const double repeatOffsetProbDecay = 0.9;
const double firstGapProb = 0;
const double otherGapProb = 0;
const double minMaskProb = 0.5;
const int seqs_len = n;
unsigned char* d_seqs;
d_seqs = (unsigned char *)sycl::malloc_device(total, q_ct1);
q_ct1.memcpy(d_seqs, seqs_device, total).wait();
unsigned char* d_maskTable;
d_maskTable = (unsigned char *)sycl::malloc_device(size * size, q_ct1);
q_ct1.memcpy(d_maskTable, mask_table_device, size).wait();
double* d_probMat;
d_probMat = (double *)sycl::malloc_device(size * size, q_ct1);
q_ct1.memcpy(d_probMat, probMat_device, sizeof(double) * size * size).wait();
sycl::range<3> grids((seqs_len + 128) / 128, 1, 1);
sycl::range<3> threads(128, 1, 1);
q_ct1.submit([&](sycl::handler &cgh) {
auto dpct_global_range = grids * threads;
cgh.parallel_for(
sycl::nd_range<3>(
sycl::range<3>(dpct_global_range.get(2), dpct_global_range.get(1),
dpct_global_range.get(0)),
sycl::range<3>(threads.get(2), threads.get(1), threads.get(0))),
[=](sycl::nd_item<3> item_ct1) {
maskSequences(d_seqs, d_probMat, d_maskTable, size, maxRepeatOffset,
repeatProb, repeatEndProb, repeatOffsetProbDecay,
firstGapProb, otherGapProb, minMaskProb, seqs_len,
item_ct1);
});
});
q_ct1.memcpy(seqs_device, d_seqs, total).wait();
sycl::free(d_seqs, q_ct1);
sycl::free(d_maskTable, q_ct1);
sycl::free(d_probMat, q_ct1);
message_stream << "Total time (maskSequences) on the device = " <<
t.getElapsedTimeInMicroSec() / 1e6 << " s" << std::endl;
free(probMat_device);
free(mask_table_device);
return seqs_device;
}
void Masking::call_opt(Letter *seq, size_t len) const
{
// CPU
tantale::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50,
(tantan::const_double_ptr*)probMatrixPointers_,
0.005, 0.05,
0.9,
0, 0,
0.5, (const tantan::uchar*)mask_table_x_);
}
void Masking::mask_bit(Letter *seq, size_t len) const
{
tantan::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50,
(tantan::const_double_ptr*)probMatrixPointers_,
0.005, 0.05,
0.9,
0, 0,
0.5, (const tantan::uchar*)mask_table_bit_);
}
void Masking::bit_to_hard_mask(Letter *seq, size_t len, size_t &n) const
{
for (size_t i = 0; i < len; ++i)
if (seq[i] & bit_mask) {
seq[i] = value_traits.mask_char;
++n;
}
}
void Masking::remove_bit_mask(Letter *seq, size_t len) const
{
for (size_t i = 0; i < len; ++i)
if (seq[i] & bit_mask)
seq[i] &= ~bit_mask;
}
void mask_worker(Atomic<size_t> *next, Sequence_set *seqs, const Masking *masking, bool hard_mask)
{
size_t i;
int cnt = 0;
while ((i = (*next)++) < seqs->get_length())
{
if (hard_mask)
//masking->operator()(seqs->ptr(i), seqs->length(i));
masking->call_opt(seqs->ptr(i), seqs->length(i));
else
masking->mask_bit(seqs->ptr(i), seqs->length(i));
//cnt++;
//if (cnt == 2) break;
}
}
void mask_seqs(Sequence_set &seqs, const Masking &masking, bool hard_mask)
{
assert(hard_mask==true);
const int n = seqs.get_length();
printf("Timing the mask sequences on CPU...\n");
Timer total;
total.start();
#if not defined(_OPENMP)
Thread_pool threads;
Atomic<size_t> next(0);
for (size_t i = 0; i < config.threads_; ++i)
threads.push_back(launch_thread(mask_worker, &next, &seqs, &masking, hard_mask));
threads.join_all();
#else
#pragma omp parallel for num_threads(config.threads_)
for (int i=0; i < n; i++){
masking.call_opt(seqs.ptr(i), seqs.length(i));
}
#endif
message_stream << "Total time (maskSequences) on the CPU = " <<
total.getElapsedTimeInMicroSec() / 1e6 << " s" << std::endl;
// on the device
unsigned char* seqs_device = masking.call_opt(seqs);
printf("Verify the sequences...\n");
unsigned char* p = seqs_device;
int error = 0;
for (int i = 0; i < n; i++) {
if (0 != strncmp((const char*)p, seqs.ptr(i), seqs.length(i))) {
printf("error at i=%d length=%zu\n", i, seqs.length(i));
printf("host=");
char* s = seqs.ptr(i);
for (int j = 0; j < seqs.length(i); j++) {
printf("%02d", s[j]);
}
printf("\ndevice=");
for (int j = 0; j < seqs.length(i); j++)
printf("%02d", *(seqs_device+i*33+j));
printf("\n");
error++;
}
p += seqs.length(i);
}
if (error == 0) printf("Success\n");
}
| 29.439189 | 119 | 0.638742 | jchlanda |
79c4b094e8b2c96e913d2b959c1499addf6b865c | 6,511 | cc | C++ | cpp/core/internal/wifi_lan_service_info_test.cc | jdapena/nearby-connections | ae277748ce068ef1730d5104002d4324fc4ed89e | [
"Apache-2.0"
] | null | null | null | cpp/core/internal/wifi_lan_service_info_test.cc | jdapena/nearby-connections | ae277748ce068ef1730d5104002d4324fc4ed89e | [
"Apache-2.0"
] | null | null | null | cpp/core/internal/wifi_lan_service_info_test.cc | jdapena/nearby-connections | ae277748ce068ef1730d5104002d4324fc4ed89e | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 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 "core/internal/wifi_lan_service_info.h"
#include <cstring>
#include "platform/base64_utils.h"
#include "platform/port/string.h"
#include "gtest/gtest.h"
namespace location {
namespace nearby {
namespace connections {
namespace {
const WifiLanServiceInfo::Version kVersion = WifiLanServiceInfo::Version::kV1;
const PCP::Value kPcp = PCP::P2P_CLUSTER;
const char kEndPointID[] = "AB12";
const char kServiceIDHashBytes[] = {0x0A, 0x0B, 0x0C};
// TODO(b/149806065): Implements test endpoint_name.
TEST(WifiLanServiceInfoTest, SerializationDeserializationWorks) {
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(
kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get()));
ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info(
WifiLanServiceInfo::FromString(wifi_lan_service_info_string));
EXPECT_EQ(kPcp, scoped_wifi_lan_service_info->GetPcp());
EXPECT_EQ(kVersion, scoped_wifi_lan_service_info->GetVersion());
EXPECT_EQ(kEndPointID, scoped_wifi_lan_service_info->GetEndpointId());
EXPECT_EQ(*scoped_service_id_hash,
*(scoped_wifi_lan_service_info->GetServiceIdHash()));
}
TEST(WifiLanServiceInfoTest,
SerializationDeserializationWorksWithEmptyEndpointName) {
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(
kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get()));
ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info(
WifiLanServiceInfo::FromString(wifi_lan_service_info_string));
EXPECT_EQ(kPcp, scoped_wifi_lan_service_info->GetPcp());
EXPECT_EQ(kVersion, scoped_wifi_lan_service_info->GetVersion());
EXPECT_EQ(kEndPointID, scoped_wifi_lan_service_info->GetEndpointId());
EXPECT_EQ(*scoped_service_id_hash,
*(scoped_wifi_lan_service_info->GetServiceIdHash()));
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithBadVersion) {
WifiLanServiceInfo::Version bad_version =
static_cast<WifiLanServiceInfo::Version>(666);
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string =
WifiLanServiceInfo::AsString(bad_version, kPcp, kEndPointID,
ConstifyPtr(scoped_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithBadPCP) {
PCP::Value bad_pcp = static_cast<PCP::Value>(666);
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string =
WifiLanServiceInfo::AsString(kVersion, bad_pcp, kEndPointID,
ConstifyPtr(scoped_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithShortEndpointId) {
std::string short_endpoint_id("AB1");
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string =
WifiLanServiceInfo::AsString(kVersion, kPcp, short_endpoint_id,
ConstifyPtr(scoped_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithLongEndpointId) {
std::string long_endpoint_id("AB12X");
ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray(
kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char)));
std::string wifi_lan_service_info_string =
WifiLanServiceInfo::AsString(kVersion, kPcp, long_endpoint_id,
ConstifyPtr(scoped_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithShortServiceIdHash) {
char short_service_id_hash_bytes[] = {0x0A, 0x0B};
ScopedPtr<Ptr<ByteArray> > scoped_short_service_id_hash(
new ByteArray(short_service_id_hash_bytes,
sizeof(short_service_id_hash_bytes) / sizeof(char)));
std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(
kVersion, kPcp, kEndPointID,
ConstifyPtr(scoped_short_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, SerializationFailsWithLongServiceIdHash) {
char long_service_id_hash_bytes[] = {0x0A, 0x0B, 0x0C, 0x0D};
ScopedPtr<Ptr<ByteArray> > scoped_long_service_id_hash(
new ByteArray(long_service_id_hash_bytes,
sizeof(long_service_id_hash_bytes) / sizeof(char)));
std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(
kVersion, kPcp, kEndPointID,
ConstifyPtr(scoped_long_service_id_hash.get()));
EXPECT_TRUE(wifi_lan_service_info_string.empty());
}
TEST(WifiLanServiceInfoTest, DeserializationFailsWithShortLength) {
char wifi_lan_service_info_bytes[] = {'X'};
ScopedPtr<Ptr<ByteArray> > scoped_wifi_lan_service_info_bytes(
new ByteArray(wifi_lan_service_info_bytes,
sizeof(wifi_lan_service_info_bytes) / sizeof(char)));
ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info(
WifiLanServiceInfo::FromString(Base64Utils::encode(
ConstifyPtr(scoped_wifi_lan_service_info_bytes.get()))));
EXPECT_TRUE(scoped_wifi_lan_service_info.isNull());
}
} // namespace
} // namespace connections
} // namespace nearby
} // namespace location
| 39.222892 | 78 | 0.762402 | jdapena |
79c8029e5cfc8810f496c4c017a5f35d9ef79287 | 2,051 | hpp | C++ | kernel/eir/arch/arm/eir-internal/arch/pl011.hpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 935 | 2018-05-23T14:56:18.000Z | 2022-03-29T07:27:20.000Z | kernel/eir/arch/arm/eir-internal/arch/pl011.hpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 314 | 2018-05-04T15:58:06.000Z | 2022-03-30T16:24:17.000Z | kernel/eir/arch/arm/eir-internal/arch/pl011.hpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 65 | 2019-04-21T14:26:51.000Z | 2022-03-12T03:16:41.000Z | #pragma once
#include <stdint.h>
#include <arch/mem_space.hpp>
#include <arch/register.hpp>
namespace eir {
namespace pl011_reg {
static constexpr arch::scalar_register<uint32_t> data{0x00};
static constexpr arch::bit_register<uint32_t> status{0x18};
static constexpr arch::scalar_register<uint32_t> i_baud{0x24};
static constexpr arch::scalar_register<uint32_t> f_baud{0x28};
static constexpr arch::bit_register<uint32_t> control{0x30};
static constexpr arch::bit_register<uint32_t> line_control{0x2c};
static constexpr arch::scalar_register<uint32_t> int_clear{0x44};
}
namespace pl011_status {
static constexpr arch::field<uint32_t, bool> tx_full{5, 1};
};
namespace pl011_control {
static constexpr arch::field<uint32_t, bool> rx_en{9, 1};
static constexpr arch::field<uint32_t, bool> tx_en{8, 1};
static constexpr arch::field<uint32_t, bool> uart_en{0, 1};
};
namespace pl011_line_control {
static constexpr arch::field<uint32_t, uint8_t> word_len{5, 2};
static constexpr arch::field<uint32_t, bool> fifo_en{4, 1};
}
struct PL011 {
PL011(uintptr_t base, uint64_t clock)
: space_{base}, clock_{clock} { }
void disable() {
space_.store(pl011_reg::control, pl011_control::uart_en(false));
}
void init(uint64_t baud) {
disable();
uint64_t int_part = clock_ / (16 * baud);
// 3 decimal places of precision should be enough :^)
uint64_t frac_part = (((clock_ * 1000) / (16 * baud) - (int_part * 1000))
* 64 + 500) / 1000;
space_.store(pl011_reg::i_baud, int_part);
space_.store(pl011_reg::f_baud, frac_part);
// 8n1, fifo enabled
space_.store(pl011_reg::line_control,
pl011_line_control::word_len(3)
| pl011_line_control::fifo_en(true));
space_.store(pl011_reg::control,
pl011_control::rx_en(true)
| pl011_control::tx_en(true)
| pl011_control::uart_en(true));
}
void send(uint8_t val) {
while (space_.load(pl011_reg::status) & pl011_status::tx_full)
;
space_.store(pl011_reg::data, val);
}
private:
arch::mem_space space_;
uint64_t clock_;
};
} // namespace eir
| 26.636364 | 75 | 0.7255 | kITerE |