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 float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7cb0565cdf3ef1b07f4fedd4818055fb2bb9932a | 1,326 | cc | C++ | lang/c++/impl/Types.cc | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | lang/c++/impl/Types.cc | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | lang/c++/impl/Types.cc | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | /**
*/
#include "Types.hh"
#include <iostream>
#include <string>
namespace aingle {
namespace strings {
const std::string typeToString[] = {
"string",
"bytes",
"int",
"long",
"float",
"double",
"boolean",
"null",
"record",
"enum",
"array",
"map",
"union",
"fixed",
"symbolic"};
static_assert((sizeof(typeToString) / sizeof(std::string)) == (AINGLE_NUM_TYPES + 1),
"Incorrect AIngle typeToString");
} // namespace strings
// this static assert exists because a 32 bit integer is used as a bit-flag for each type,
// and it would be a problem for this flag if we ever supported more than 32 types
static_assert(AINGLE_NUM_TYPES < 32, "Too many AIngle types");
const std::string &toString(Type type) noexcept {
static std::string undefinedType = "Undefined type";
if (isAIngleTypeOrPseudoType(type)) {
return strings::typeToString[type];
} else {
return undefinedType;
}
}
std::ostream &operator<<(std::ostream &os, Type type) {
if (isAIngleTypeOrPseudoType(type)) {
os << strings::typeToString[type];
} else {
os << static_cast<int>(type);
}
return os;
}
std::ostream &operator<<(std::ostream &os, const Null &) {
os << "(null value)";
return os;
}
} // namespace aingle
| 21.737705 | 90 | 0.619155 |
7cb2402039a6a28448524e88606e450eddb9e1a8 | 9,846 | cc | C++ | src/math/test_heightfield.cc | mnvl/scratch | 7717772e0b9a85c8feb73fdc3562425f48b4a727 | [
"BSD-3-Clause"
] | 1 | 2016-08-15T11:55:32.000Z | 2016-08-15T11:55:32.000Z | src/math/test_heightfield.cc | mnvl/scratch | 7717772e0b9a85c8feb73fdc3562425f48b4a727 | [
"BSD-3-Clause"
] | null | null | null | src/math/test_heightfield.cc | mnvl/scratch | 7717772e0b9a85c8feb73fdc3562425f48b4a727 | [
"BSD-3-Clause"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include "heightfield.h"
BOOST_AUTO_TEST_SUITE(test_triangle)
BOOST_AUTO_TEST_CASE(test_raytrace_simple_1)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 0, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_2)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0.5f, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0.5f, 0.5f, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_3)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(1, 10.0f, 0), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1, 1, 0)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_4)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f, 0.5f), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 1.5f, 0.5f)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_5)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(0, 10.0f,1), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(0, 3, 1)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_6)
{
math::matrix<4,4> tf;
tf.identity();
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t const heights[] = {
0, 1,
3, 7
};
hf.load_from_raw_buffer(heights);
math::contact_info<3> ci = hf.trace(math::ray<3>(math::vec<3>(1, 10.0f,1), math::vec<3>(0, -1.0f, 0)));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1, 7, 1)).length_sq() < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_1)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(6.6737876f, 0, 4.9803157f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_2)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(2.0899076f, 0, 5.1918087f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_3)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(4.0656757f, 0, 7.5460067f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_raytrace_complex_4)
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
for (int i = 0; i < 100; ++i)
{
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(math::scalar(rand()) / RAND_MAX * 10, 0, math::scalar(rand()) / RAND_MAX * 10);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE (abs(ci.position.y / ci.position.x - 1) < 0.01f);
BOOST_REQUIRE (ci.normal.y > 0);
}
}
BOOST_AUTO_TEST_CASE(test_raytrace_simple_save_load_1)
{
std::string dump;
{
math::matrix<4,4> tf;
tf.scaling(10, 10, 10);
math::heightfield<boost::uint8_t> hf(tf, 11, 11);
static boost::uint8_t const heights[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
hf.load_from_raw_buffer(heights);
std::stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa & hf;
dump = ss.str();
}
math::heightfield<boost::uint8_t> hf(math::matrix<4,4>(), 10, 10);
std::stringstream stream(dump);
boost::archive::binary_iarchive(stream) & hf;
math::vec<3> p1(0, 10, 0);
math::vec<3> p2(2.0899076f, 0, 5.1918087f);
math::contact_info<3> ci = hf.trace(math::ray<3>(p1, p2 - p1));
BOOST_REQUIRE (ci.happened == true);
BOOST_REQUIRE (ci.penetrated == false);
BOOST_REQUIRE ((ci.position - math::vec<3>(1.7286383f, 1.7286377f, 4.2943335f)).length_sq() < 1e-6f);
BOOST_REQUIRE (ci.normal.y > 0);
}
BOOST_AUTO_TEST_CASE(test_y_under)
{
math::matrix<4,4> tf;
tf.scaling(1, 1, 1);
math::heightfield<boost::uint8_t> hf(tf, 2, 2);
static boost::uint8_t heights[2 * 2] = {
0, 1,
4, 9,
};
hf.load_from_raw_buffer(heights);
for (size_t i = 0; i < 100; ++i)
{
math::scalar height = hf.y_under(math::vec<3>(i / 100.0f, 100, 0));
BOOST_REQUIRE (abs(height - i / 100.0) < 1e-3);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height = hf.y_under(math::vec<3>(0, 100, i / 100.0f));
BOOST_REQUIRE (abs(height - 4 * i / 100.0f) < 1e-3);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height1 = hf.y_under(math::vec<3>(i / 100.0f, 100, 1 - 1e-6f));
math::scalar height2 = 4 + (9 - 4) * i / 100.0f;
BOOST_REQUIRE (abs(height1 - height2) < 0.01f);
}
for (size_t i = 0; i < 100; ++i)
{
math::scalar height1 = hf.y_under(math::vec<3>(1 - 1e-6f, 100, i / 100.0f));
math::scalar height2 = 1 + (9 - 1) * i / 100.0f;
BOOST_REQUIRE (abs(height1 - height2) < 0.01f);
}
}
BOOST_AUTO_TEST_SUITE_END()
| 26.467742 | 108 | 0.582064 |
7cb2ddc579a2d08161f030133cc2d6295ec37fb1 | 89,722 | cpp | C++ | src/reader.cpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 5 | 2021-01-10T06:22:11.000Z | 2021-04-13T12:59:40.000Z | src/reader.cpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 1 | 2021-01-10T04:42:17.000Z | 2021-01-10T10:55:58.000Z | src/reader.cpp | david-cortes/readsparse | 1d816bdccd628788027041e92d83e8e20702de86 | [
"BSD-2-Clause"
] | 1 | 2021-04-13T12:59:41.000Z | 2021-04-13T12:59:41.000Z | /* Generated through 'instantiate_templates.py', do not edit manually. */
/* Read and write sparse matrices in text format:
* <labels(s)> <column>:<value> <column>:<value> ...
*
* BSD 2-Clause License
* Copyright (c) 2021, David Cortes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(_FOR_PYTHON) || defined(_FOR_R) || !defined(_WIN32)
#define EXPORTABLE
#else
#ifdef READSPARSE_COMPILE
#define EXPORTABLE __declspec(dllexport)
#else
#define EXPORTABLE __declspec(dllimport)
#endif
#endif
#include "reader.hpp"
#ifdef _FOR_R
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#elif defined(_FOR_PYTHON)
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#else
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
FILE *input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &indptr_lab,
std::vector<int> &indices_lab,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int> &indptr,
std::vector<int> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &indptr_lab,
std::vector<int64_t> &indices_lab,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<int64_t> &indptr,
std::vector<int64_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<int64_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<float> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_multi_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &indptr_lab,
std::vector<size_t> &indices_lab,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_multi_label_template(
input_file,
indptr,
indices,
values,
indptr_lab,
indices_lab,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<int64_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<size_t> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<float> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
EXPORTABLE bool read_single_label
(
std::istream &input_file,
std::vector<size_t> &indptr,
std::vector<size_t> &indices,
std::vector<double> &values,
std::vector<double> &labels,
std::vector<size_t> &qid,
size_large &nrows,
size_large &ncols,
size_large &nclasses,
const size_t limit_nrows = 0,
const bool ignore_zero_valued = true,
const bool sort_indices = true,
const bool text_is_base1 = true,
const bool assume_no_qid = true,
const bool assume_trailing_ws = true
)
{
return read_single_label_template(
input_file,
indptr,
indices,
values,
labels,
qid,
nrows,
ncols,
nclasses,
limit_nrows,
ignore_zero_valued,
sort_indices,
text_is_base1,
assume_no_qid,
assume_trailing_ws
);
}
#endif /* _FOR_R, _FOR_PYTHON */
| 23.058854 | 84 | 0.617441 |
7cb574e9ac5f67235a3ff3c89c8c918f75508ed3 | 1,546 | cpp | C++ | internalconnector/internalrastercoverageconnector.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | internalconnector/internalrastercoverageconnector.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | internalconnector/internalrastercoverageconnector.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | #include "kernel.h"
#include "raster.h"
#include "numericrange.h"
#include "numericdomain.h"
#include "columndefinition.h"
#include "table.h"
#include "connectorinterface.h"
#include "mastercatalog.h"
#include "ilwisobjectconnector.h"
#include "catalogexplorer.h"
#include "catalogconnector.h"
#include "internalrastercoverageconnector.h"
using namespace Ilwis;
using namespace Internal;
ConnectorInterface *Ilwis::Internal::InternalRasterCoverageConnector::create(const Ilwis::Resource &resource,bool load,const IOOptions& options)
{
return new InternalRasterCoverageConnector(resource, load, options);
}
InternalRasterCoverageConnector::InternalRasterCoverageConnector(const Resource &resource, bool load,const IOOptions& options) : IlwisObjectConnector(resource, load, options)
{
}
bool InternalRasterCoverageConnector::loadMetaData(IlwisObject *data, const IOOptions &options){
RasterCoverage *gcoverage = static_cast<RasterCoverage *>(data);
if(_dataType == gcoverage->datadef().range().isNull())
return false;
if ( !gcoverage->datadef().range().isNull())
_dataType = gcoverage->datadef().range()->valueType();
gcoverage->gridRef()->prepare(gcoverage,gcoverage->size());
return true;
}
bool InternalRasterCoverageConnector::loadData(IlwisObject *, const IOOptions &){
return true;
}
QString Ilwis::Internal::InternalRasterCoverageConnector::provider() const
{
return "internal";
}
IlwisObject *InternalRasterCoverageConnector::create() const
{
return new RasterCoverage();
}
| 27.607143 | 174 | 0.76326 |
7cbc334cb01636a1bcb59b8de0f8ff2fcf0c0a52 | 2,385 | cpp | C++ | src/D3D9Hook.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | 5 | 2021-06-09T23:53:28.000Z | 2022-02-21T06:09:41.000Z | src/D3D9Hook.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | 9 | 2021-06-09T23:52:43.000Z | 2021-09-17T14:05:47.000Z | src/D3D9Hook.cpp | muhopensores/dmc3-inputs-thing | 2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <spdlog/spdlog.h>
#include "D3D9Hook.hpp"
using namespace std;
static D3D9Hook* g_d3d9_hook = nullptr;
D3D9Hook::~D3D9Hook() {
unhook();
}
uintptr_t end_scene_jmp_ret = 0;
__declspec(naked) void end_scene_hook(void) {
__asm {
pushad
push eax
call D3D9Hook::end_scene
popad
pop eax
push eax
call dword ptr [ecx+0xA8]
jmp dword ptr [end_scene_jmp_ret]
}
}
uintptr_t reset_jmp_ret = 0;
__declspec(naked) void reset_hook(void) {
__asm {
pushad
push eax
call D3D9Hook::reset
popad
pop eax
push eax
call dword ptr [ecx+0x40]
mov esi, eax
jmp dword ptr [reset_jmp_ret]
}
}
bool D3D9Hook::hook() {
spdlog::info("Hooking D3D9");
g_d3d9_hook = this;
IDirect3DDevice9** game = (IDirect3DDevice9**)0x0252F374;
IDirect3DDevice9* d3d9_device = *game; // TODO: base + offset?
m_device = d3d9_device;
uintptr_t reset_fn = (*(uintptr_t**)d3d9_device)[16];
uintptr_t end_scene_fn = (*(uintptr_t**)d3d9_device)[42];
m_end_scene_hook = std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene);//std::make_unique<FunctionHook>(end_scene_fn, (uintptr_t)&end_scene_hook);
m_reset_hook = std::make_unique<FunctionHook>(reset_fn, (uintptr_t)&reset);
//end_scene_jmp_ret = 0x006DC48E + 0x6;
//reset_jmp_ret = reset_fn + 5;
m_hooked = m_end_scene_hook->create() && m_reset_hook->create();
return m_hooked;
}
bool D3D9Hook::unhook() {
return true;
}
#if 1
HRESULT WINAPI D3D9Hook::end_scene(LPDIRECT3DDEVICE9 pDevice) {
auto d3d9 = g_d3d9_hook;
//d3d9->m_device = pDevice;
if (d3d9->m_on_end_scene) {
d3d9->m_on_end_scene(*d3d9);
}
//return S_OK;
auto end_scene_fn =
d3d9->m_end_scene_hook->get_original<decltype(D3D9Hook::end_scene)>();
return end_scene_fn(pDevice);
}
#else
static void end_scene_our(LPDIRECT3DDEVICE9 pDevice) {
auto d3d9 = g_d3d9_hook;
d3d9->set_device(pDevice);
if (d3d9->m_on_end_scene) {
d3d9->m_on_end_scene(*d3d9);
}
}
#endif
HRESULT WINAPI D3D9Hook::reset(LPDIRECT3DDEVICE9 pDevice, D3DPRESENT_PARAMETERS *pPresentationParameters) {
auto d3d9 = g_d3d9_hook;
d3d9->m_presentation_params = pPresentationParameters;
if (d3d9->m_on_reset) {
d3d9->m_on_reset(*d3d9);
}
//return S_OK;
auto reset_fn =
d3d9->m_reset_hook->get_original<decltype(D3D9Hook::reset)>();
return reset_fn(pDevice, pPresentationParameters);
}
| 21.681818 | 166 | 0.72369 |
7cbc953df2964ce38192ac835e350fa99d16ce84 | 947 | cpp | C++ | Strings/LengthOfLastWord58.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 38 | 2021-10-14T09:36:53.000Z | 2022-01-27T02:36:19.000Z | Strings/LengthOfLastWord58.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | null | null | null | Strings/LengthOfLastWord58.cpp | devangi2000/Data-Structures-Algorithms-Handbook | ce0f00de89af5da7f986e65089402dc6908a09b5 | [
"MIT"
] | 4 | 2021-12-06T15:47:12.000Z | 2022-02-04T04:25:00.000Z | // Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
// A word is a maximal substring consisting of non-space characters only.
// Example 1:
// Input: s = "Hello World"
// Output: 5
// Explanation: The last word is "World" with length 5.
// Example 2:
// Input: s = " fly me to the moon "
// Output: 4
// Explanation: The last word is "moon" with length 4.
// Example 3:
// Input: s = "luffy is still joyboy"
// Output: 6
// Explanation: The last word is "joyboy" with length 6.
// Constraints:
// 1 <= s.length <= 104
// s consists of only English letters and spaces ' '.
// There will be at least one word in s.
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, n = s.size()-1;
while(n >= 0 and s[n] == ' ') n--;
while(n >= 0 and s[n--] != ' ') len++;
return len;
}
}; | 32.655172 | 131 | 0.600845 |
7cbdbb18250cf7d6bfd0461342c062690aebbb75 | 579 | cpp | C++ | threading.cpp | brandonbraun653/TeamSOAR | 472c7e900de20545476e76395ebe89ab5467ae11 | [
"MIT"
] | null | null | null | threading.cpp | brandonbraun653/TeamSOAR | 472c7e900de20545476e76395ebe89ab5467ae11 | [
"MIT"
] | null | null | null | threading.cpp | brandonbraun653/TeamSOAR | 472c7e900de20545476e76395ebe89ab5467ae11 | [
"MIT"
] | null | null | null | #include "threading.hpp"
QueueHandle_t qAHRS = xQueueCreate(1, sizeof(AHRSData_t));
SemaphoreHandle_t ahrsBufferMutex = xSemaphoreCreateMutex();
boost::container::vector<void*> TaskHandle(TOTAL_TASK_SIZE);
BaseType_t xTaskSendMessage(TaskIndex idx, uint32_t msg)
{
if (TaskHandle[idx])
return xTaskNotify(TaskHandle[idx], msg, eSetValueWithOverwrite);
else
return pdFAIL;
}
BaseType_t xTaskSendMessageFromISR(TaskIndex idx, uint32_t msg)
{
if (TaskHandle[idx])
return xTaskNotifyFromISR(TaskHandle[idx], msg, eSetValueWithOverwrite, NULL);
else
return pdFAIL;
}
| 24.125 | 80 | 0.787565 |
7cbf4c55beb83cc24a403f56b1a7342e27cc14d9 | 896 | cpp | C++ | projects/basic microcontroller/source/main.cpp | ankhbayar59/SJSU-Dev2 | 423e36298b7ef53762348299f0ffca50b31c2dfe | [
"Apache-2.0"
] | null | null | null | projects/basic microcontroller/source/main.cpp | ankhbayar59/SJSU-Dev2 | 423e36298b7ef53762348299f0ffca50b31c2dfe | [
"Apache-2.0"
] | null | null | null | projects/basic microcontroller/source/main.cpp | ankhbayar59/SJSU-Dev2 | 423e36298b7ef53762348299f0ffca50b31c2dfe | [
"Apache-2.0"
] | null | null | null | #include <cstdint>
#include "Bus.hpp"
Bus bus;
void irs()
{
LOG_INFO("Interrupt Detected\n");
uint8_t data5;
uint8_t address10;
uint8_t address11;
address10 = 0;
address11 = 1;
bus.polling(address10, address11);
data5 = 15;
bus.io_write(address10, data5);
}
int main()
{
sjsu::lpc40xx::Gpio interrupt = sjsu::lpc40xx::Gpio(0,11);
uint8_t address1;
uint8_t address2;
uint8_t address3;
uint8_t data1;
uint8_t data2;
int n = 0;
address1 = 3;
address2 = 0;
address3 = 1;
data1 = 134;
bus.Initialize();
bus.io_write(address1, data1);
data1 = 5; // Used to set INTE B which was 0b 0000 0101
bus.io_write(address1, data1);
data2 = 15;
bus.io_write(address2, data2);
interrupt.GetPin().SetPull(sjsu::Pin::Resistor::kPullUp);
interrupt.AttachInterrupt(irs, sjsu::Gpio::Edge::kEdgeRising);
while(n == 0)
{
}
return 0;
}
| 17.230769 | 66 | 0.654018 |
7cbf6b75bd6ea36ecdadc7160eb5608779872ea9 | 40,214 | cpp | C++ | lib/klc3/Core/Executor.cpp | liuzikai/klc3 | 0c7c1504158f1cce3e6bff32f69b4cb3067cffff | [
"NCSA"
] | null | null | null | lib/klc3/Core/Executor.cpp | liuzikai/klc3 | 0c7c1504158f1cce3e6bff32f69b4cb3067cffff | [
"NCSA"
] | null | null | null | lib/klc3/Core/Executor.cpp | liuzikai/klc3 | 0c7c1504158f1cce3e6bff32f69b4cb3067cffff | [
"NCSA"
] | null | null | null | //
// Created by liuzikai on 3/19/20.
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
#include "klc3/Core/Executor.h"
#include "klc3/Generation/ReportFormatter.h"
#define LOG_BR_FORK 0
#define LOG_SYM_ADDR_FORK 0
#define DISABLE_FORK_ON_SYM_ADDR 0
namespace klc3 {
extern llvm::cl::OptionCategory KLC3ExecutionCat;
llvm::cl::opt<int> ForkOnSymAddrThreshold(
"cache-sym-addr-threshold",
llvm::cl::desc("Cache a memory access of a symbolic address whose "
"number of possible concrete values is less than this limit "
"under the initial constraints. "
"Set to 0 to disable. Set to -1 for unlimited. (default=0)"),
llvm::cl::init(0),
llvm::cl::cat(KLC3ExecutionCat));
Executor::Executor(ExprBuilder *builder, Solver *solver, const map<uint16_t, ref<MemValue>> &mem)
: WithBuilder(builder),
symAddrCacheHits("SymAddrCacheHits", "SAHits"),
symAddrCacheMisses("SymAddrCacheMisses", "SAMiss"), solver(solver) {
// baseMem initialized to nullptr (by ref())
for (const auto &m: mem) {
baseMem[m.first] = m.second;
}
if (ForkOnSymAddrThreshold != 0) {
newProgWarn() << "using the symbolic address cache with threshold " << ForkOnSymAddrThreshold
<< ", which is only effective for well designed input spaces.\n";
}
}
State *Executor::createInitState(const vector<ref<Expr>> &constraints, uint16_t initPC, IssuePackage *issuePackage) {
auto *s = stateAllocator.createInitState(builder, baseMem, initPC, issuePackage);
// Load constraints into state and check compatibility
for (const auto &c : constraints) {
bool res;
bool success = solver->mustBeFalse(Query(s->constraints, c), res);
assert(success && "Unexpected solver failure");
s->solverCount++;
if (res) {
newProgErr() << "Initial constraints are provably unsatisfiable! Failed to create initial state!" << "\n"
<< " Triggering constraint: " << c << "\n";
progExit();
} else {
s->addConstraint(c);
}
}
// Save a copy of initial constraints for possibleValuesCache, for example
initConstraints = s->constraints;
return s;
}
bool Executor::step(State *s, StateVector &result, bool returnImmediatelyIfWillFork) {
result.clear();
/// Phase 1. Fetch Instruction
ref<InstValue> ir = nullptr;
fetchInst(s, ir);
if (s->status != State::NORMAL) {
result.push_back(s);
return true;
}
if (returnImmediatelyIfWillFork && !ir.isNull() && ir->instID() == InstValue::BR) {
ref<Expr> brCond;
Solver::Validity br = solveBRCond(s, ir, brCond);
if (br == klee::Solver::Unknown) {
return false;
}
}
// Update path info
for (unsigned i = 1; i < State::RECORD_FETCHED_INST_COUNT; i++) {
s->latestInst[i] = s->latestInst[i - 1];
}
s->latestInst[0] = ir.get();
if (!ir->belongsToOS) {
for (unsigned i = 1; i < State::RECORD_FETCHED_INST_COUNT; i++) {
s->latestNonOSInst[i] = s->latestNonOSInst[i - 1];
}
s->latestNonOSInst[0] = ir.get();
}
++s->stepCount; // include OS node
/// Phase 2. Update IR and PC
updateIRAndPC(s, ir);
if (s->status != State::NORMAL) {
result.push_back(s);
return true;
}
/// Phase 3. Execute Instruction
switch (ir->instID()) {
case InstValue::BR:
executeBR(s, ir, result);
return true; // result is already filled
case InstValue::LDR:
executeLDR(s, ir, result);
return true;
case InstValue::LDI:
executeLDI(s, ir, result);
return true;
case InstValue::STR:
executeSTR(s, ir, result);
return true;
case InstValue::STI:
executeSTI(s, ir, result);
return true;
case InstValue::ADD:
case InstValue::ADDi:
executeADD(s, ir);
break;
case InstValue::AND:
case InstValue::ANDi:
executeAND(s, ir);
break;
case InstValue::JMP:
executeJMP(s, ir);
break;
case InstValue::JSR:
executeJSR(s, ir);
break;
case InstValue::JSRR:
executeJSRR(s, ir);
break;
case InstValue::LD:
executeLD(s, ir);
break;
case InstValue::LEA:
executeLEA(s, ir);
break;
case InstValue::NOT:
executeNOT(s, ir);
break;
case InstValue::ST:
executeST(s, ir);
break;
case InstValue::TRAP:
executeTRAP(s, ir);
break;
case InstValue::RTI:
if (auto issueInfo = s->newStateIssue(Issue::ERR_INVALID_INST, ir)) {
issueInfo->setNote("RTI is not supported at " + reportFormatter->formattedContext(ir) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
break;
default:
assert(!"Instruction is not supported yet");
}
result.push_back(s);
return true;
}
void Executor::fetchInst(State *s, ref<InstValue> &ir) {
uint16_t pc = s->getPC();
ref<MemValue> val = s->mem.read(pc);
if (!val.isNull() && val->type == MemValue::MEM_INST) {
ir = dyn_cast<InstValue>(val);
} else {
// Use last executed inst as break point
if (val.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_EXECUTE_UNINITIALIZED_MEMORY, s->latestNonOSInst[0])) {
issueInfo->setNote("trying to execute addr " + toLC3Hex(pc) + ".\n");
}
} else if (val->type == MemValue::MEM_DATA) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_EXECUTE_DATA_AS_INST, s->latestNonOSInst[0])) {
issueInfo->setNote("trying to execute addr " + toLC3Hex(pc) + ".\n");
}
}
assert(s->status == State::BROKEN && "Non-continuable error");
}
}
void Executor::updateIRAndPC(State *s, const ref<InstValue> &ir) {
setReg(s, R_IR, ir->e, ir);
setReg(s, R_PC, (s->getPC() + 1) & 0xFFFF, ir);
}
void Executor::executeSTR(State *s, const ref<InstValue> &ir, StateVector &result) {
handleExprST(s,
builder->Add(getReg(s, ir->baseR(), ir), buildConstant(ir->imm6())),
getReg(s, ir->sr(), ir, true), // bypass uninitialized register null value
ir,
result);
}
void Executor::executeSTI(State *s, const ref<InstValue> &ir, StateVector &result) {
uint16_t addr = s->getPC() + ir->imm9(); // auto wrap 0xFFFF
ref<Expr> midAddr;
memReadData(s, addr, midAddr, ir, -1);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
handleExprST(s, midAddr, getReg(s, ir->sr(), ir, true), ir, result); // by pass null
}
void Executor::handleExprST(State *s, const ref<Expr> &addr, const ref<Expr> &value, const ref<InstValue> &ir,
StateVector &result) {
if (addr->getKind() == Expr::Constant) {
memWriteData(s, castConstant(addr), value, ir); // if value is null, still bypass it
result.push_back(s);
} else {
vector<pair<uint16_t, State *>> instances;
forkOnRange(s, addr, ir, instances);
assert(!instances.empty() && "Immediate address evaluate to no range, which means constraints have conflicts");
for (auto &it : instances) {
uint16_t realizedAddr = it.first;
State *t = it.second;
memWriteData(t, realizedAddr, value, ir); // if value is null, still bypass it
result.push_back(t);
}
}
}
void Executor::executeLDR(State *s, const ref<InstValue> &ir, StateVector &result) {
Reg DR = ir->dr();
ref<Expr> midAddr = builder->Add(getReg(s, ir->baseR(), ir), buildConstant(ir->imm6()));
handleExprLD(s, DR, midAddr, ir, result);
}
void Executor::executeLDI(State *s, const ref<InstValue> &ir, StateVector &result) {
Reg DR = ir->dr();
uint16_t addr = s->getPC() + ir->imm9();
ref<Expr> midAddr;
memReadData(s, addr, midAddr, ir, -1);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
handleExprLD(s, DR, midAddr, ir, result);
}
void
Executor::handleExprLD(State *s, Reg DR, const ref<Expr> &addr, const ref<InstValue> &ir, StateVector &result) {
if (addr->getKind() == Expr::Constant) {
ref<Expr> data;
memReadData(s, castConstant(addr), data, ir, DR);
if (s->status != State::NORMAL) {
result.push_back(s);
return;
}
setReg(s, DR, data, ir);
setCC(s, DR, ir);
result.push_back(s);
return;
} else {
vector<pair<uint16_t, State *>> instances;
forkOnRange(s, addr, ir, instances);
assert(!instances.empty() && "Immediate address evaluate to no range, which means constraints have conflicts");
for (auto &it : instances) {
uint16_t realizedAddr = it.first;
State *t = it.second;
ref<Expr> data;
memReadData(t, realizedAddr, data, ir, DR);
if (t->status != State::NORMAL) {
result.push_back(t);
continue;
}
setReg(t, DR, data, ir);
setCC(t, DR, ir);
result.push_back(t);
}
return;
}
}
/**
* Fork states by range of given expression
* @param s
* @param val
* @param instances [out] vector of pairs of {evaluated value, state}
*/
void Executor::forkOnRange(State *s, const ref<Expr> &val, const ref<InstValue> &ir,
vector<pair<uint16_t, State *>> &instances) {
vector<pair<uint16_t, ref<Expr>>> values;
evalPossibleValuesWithCache(val, s->constraints, values, s->solverCount);
if (values.empty()) return; // no valid range
if (values.size() > 1) { // need to fork
#if LOG_SYM_ADDR_FORK
progInfo() << "Fork " << values.size() - 1 << " states" << " At: " << ir->sourceContext() << "\n";
#endif
}
#if !DISABLE_FORK_ON_SYM_ADDR
for (unsigned i = 0; i < values.size(); i++) {
State *t = (i != values.size() - 1 ? stateAllocator.fork(s) : s); // realize s to the last value
// Notice that s must be the last, or changes on it will be forked into other states
// If there is only one values, no need to add the Eq constraint since it must be true
if (!values[i].second.isNull() && values.size() != 1) {
t->addConstraint(values[i].second);
}
instances.emplace_back(values[i].first, t);
}
#else
bool res;
bool success = solver->mustBeTrue(Query(s->constraints, values.back().second), res);
assert(success && "Unexpected solver failure");
s->solverCount++;
if (!res) s->addConstraint(values.back().second);
instances.emplace_back(values.back().first, s);
#endif
}
void Executor::evalPossibleValuesWithCache(const ref<Expr> &expr, const ConstraintSet &constraints,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount) {
assert(expr->getWidth() == Expr::Int16);
if (ForkOnSymAddrThreshold == 0) {
evalPossibleValues(expr, constraints, result, solverCount);
return;
}
auto it = possibleValuesCache.find(expr);
if (it == possibleValuesCache.end()) {
++symAddrCacheMisses;
vector<pair<uint16_t, ref<Expr>>> resultUnderInitConstraints; // pairs of value, expr == value
// Evaluate the possible values under initial constraints, with a upper limit on possible value count
if (evalPossibleValues(expr, initConstraints, resultUnderInitConstraints, solverCount,
ForkOnSymAddrThreshold)) {
assert(!resultUnderInitConstraints.empty() && "Expr under initial constraints evaluates to no value!");
it = possibleValuesCache.emplace(expr, resultUnderInitConstraints).first;
} else {
// Place an empty vector to indicate there are too many possible values under only initial constraints
it = possibleValuesCache.emplace(expr, vector<pair<uint16_t, ref<Expr>>>{}).first;
static bool alreadyWarned = false;
if (!alreadyWarned) {
newProgWarn() << "Possible values on an Expr under initial constraints result in too many values.\n";
alreadyWarned = true;
}
}
} else {
++symAddrCacheHits;
}
// Evaluate possible values on current constraints
if (it->second.empty()) {
/*
* Evaluation on initial constraints results in too many possible values, possibly due to poorly designed input
* space. Hope the currently evaluated program is well written, so that reasonable constraints are placed on
* the variables and the evaluation on complete current constraints won't result in too many values. Otherwise,
* it will get explode anyway...
*/
evalPossibleValues(expr, constraints, result, solverCount);
} else {
for (const auto &item : it->second) {
bool res, success;
success = solver->mayBeTrue(Query(constraints, item.second), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
result.emplace_back(item);
}
}
}
}
bool Executor::evalPossibleValues(const ref<Expr> &expr, const ConstraintSet &constraints,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount,
int maxPossibleValueCount) const {
assert(expr->getWidth() == Expr::Int16);
uint16_t minVal, maxVal;
bool res, success;
// Binary search for # of useful bits
uint64_t lo = 0, hi = 16, mid, bits = 0;
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mustBeTrue(Query(constraints,
builder->Eq(builder->LShr(expr, buildConstant(mid)),
buildConstant(0))),
res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
bits = lo;
// Binary search for min
lo = 0, hi = klee::bits64::maxValueOfNBits(bits);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mayBeTrue(Query(constraints, builder->Ule(expr, buildConstant(mid))),
res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
minVal = lo;
// Check for the common case that maxVal == minVal
ref<Expr> c = builder->Eq(expr, buildConstant(minVal));
success = solver->mustBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
result.emplace_back(minVal, c);
return (maxPossibleValueCount == -1 || (int) result.size() <= maxPossibleValueCount);
}
// Binary search for max
lo = minVal, hi = klee::bits64::maxValueOfNBits(bits);
while (lo < hi) {
mid = lo + (hi - lo) / 2;
success = solver->mustBeTrue(Query(constraints, builder->Ule(expr, buildConstant(mid))),
res);
solverCount++;
assert(success && "FIXME: Unhandled solver failure");
if (res) {
hi = mid;
} else {
lo = mid + 1;
}
}
maxVal = lo;
/*maxVal = klee::bits64::maxValueOfNBits(bits);*/
return evalPossibleValuesInRange(expr, constraints, minVal, maxVal, result, solverCount, maxPossibleValueCount);
}
bool Executor::evalPossibleValuesInRange(const ref<Expr> &expr, const ConstraintSet &constraints,
long minVal, long maxVal,
vector<pair<uint16_t, ref<Expr>>> &result, int &solverCount,
int maxPossibleValueCount) const {
// NOTE: as we do arithmetic, minVal, maxVal and midVal below must be larger than uint16_t (and better to be signed)
bool res, success;
ref<Expr> c;
if (minVal > maxVal) {
return true;
} else if (maxVal - minVal <= 3) {
/**
* [0, 3] for example
* Direct Eq: 4 queries
* Fall back to else below, worse case: 6 queries
* mid = 1
* 1) 0 <= expr <= 1? [0, 1]
* 2) expr == 0?
* 3) expr == 1?
* 4) 2 <= expr <= 3? [2, 3]
* 5) expr == 2?
* 6) expr == 3?
* Best case: 3 (half of the range is impossible, while the other must be possible or it will exit earlier)
* 1) 0 <= expr <= 1? No. Then 2 <= expr <= 3 must be true.
* 2) expr == 2?
* 3) expr == 3?
*/
// NOTE: must be larger than uint16_t or ++ may overflow
for (long val = minVal; val <= maxVal; val++) {
c = builder->Eq(expr, buildConstant(val));
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) result.emplace_back(val, c);
if (maxPossibleValueCount != -1 && (int) result.size() > maxPossibleValueCount) return false;
}
} else {
long midVal = (minVal + maxVal) / 2;
// [minVal, midVal]
if (minVal == midVal) {
// Just query Eq
if (!evalPossibleValuesInRange(expr, constraints, minVal, midVal, result, solverCount,
maxPossibleValueCount))
return false;
} else {
// Check whether this half is possible
c = builder->And(
builder->Ule(buildConstant(minVal), expr),
builder->Ule(expr, buildConstant(midVal))
);
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
if (res) {
if (!evalPossibleValuesInRange(expr, constraints, minVal, midVal, result, solverCount,
maxPossibleValueCount))
return false;
}
}
// [midVal + 1, maxVal]
if (midVal + 1 == maxVal) {
// Just query Eq
if (!evalPossibleValuesInRange(expr, constraints, midVal + 1, maxVal, result, solverCount,
maxPossibleValueCount))
return false;
} else {
if (!res) {
// The other half is not possible, then this half must be possible
res = true;
} else {
// Check whether this half is possible
c = builder->And(
builder->Ule(buildConstant(midVal + 1), expr),
builder->Ule(expr, buildConstant(maxVal))
);
success = solver->mayBeTrue(Query(constraints, c), res);
assert(success && "Unexpected solver failure");
solverCount++;
}
if (res) {
if (!evalPossibleValuesInRange(expr, constraints, midVal + 1, maxVal, result, solverCount,
maxPossibleValueCount))
return false;
}
}
}
return true;
}
void Executor::executeBR(State *s, const ref<InstValue> &ir, StateVector &result) {
ref<Expr> brCond;
Solver::Validity br = solveBRCond(s, ir, brCond);
State *continueState = nullptr;
State *branchState = nullptr;
if (br == Solver::True) { // always branch
branchState = s;
} else if (br == Solver::False) { // always continue
continueState = s;
} else {
// Fork state
branchState = s;
continueState = stateAllocator.fork(s);
// Add constraints
branchState->addConstraint(brCond);
ref<Expr> continueCond = Expr::createIsZero(brCond);
continueState->addConstraint(continueCond);
#if LOG_BR_FORK
progInfo() << "Fork 1 state" << " At: " << ir->sourceContext() << "\n";
#endif
}
if (branchState != nullptr) {
// Execute branch
setReg(branchState, R_PC, branchState->getPC() + ir->imm9(), ir); // auto wrap 0xFFFF
}
if (continueState != nullptr) result.push_back(continueState);
if (branchState != nullptr) result.push_back(branchState);
}
Solver::Validity Executor::solveBRCond(State *s, const ref<InstValue> &ir, ref<Expr> &brCond) {
// Generate branch condition
// Only using Eq, Slt and Sle in canonical mode
switch (ir->cc()) {
case InstValue::CC_NONE:
brCond = nullptr;
return klee::Solver::False; // never branch
case InstValue::CC_NZP:
brCond = nullptr;
return klee::Solver::True; // always branch
case InstValue::CC_N:
brCond = builder->Slt(getCCExpr(s, ir), buildConstant(0));
break;
case InstValue::CC_Z:
brCond = Expr::createIsZero(getCCExpr(s, ir));
break;
case InstValue::CC_P:
brCond = builder->Slt(buildConstant(0), getCCExpr(s, ir));
break;
case InstValue::CC_NP:
brCond = Expr::createIsZero(Expr::createIsZero(getCCExpr(s, ir)));
break;
case InstValue::CC_NZ:
brCond = builder->Sle(getCCExpr(s, ir), buildConstant(0));
break;
case InstValue::CC_ZP:
brCond = builder->Sle(buildConstant(0), getCCExpr(s, ir));
break;
}
// Constant folding builder
if (brCond->isTrue()) return klee::Solver::True;
else if (brCond->isFalse()) return klee::Solver::False;
#if 0
progInfo() << " brCond: " << brCond << "\n" << " Constraint:" << "\n";
for (auto it = s->constraints.begin(); it != s->constraints.end(); it++) {
progInfo() << " " << *it << "\n";
}
progInfo() << "At: " << ir->sourceContext() << "\n";
#endif
klee::Solver::Validity ret;
bool success = solver->evaluate(Query(s->constraints, brCond), ret);
assert(success && "Unhandled solver failure");
s->solverCount++;
#if 0
if (ret == klee::Solver::Validity::Unknown) {
progInfo() << " brCond: " << brCond << " => Unknown\n" << " Constraint:" << "\n";
for (auto it = s->constraints.begin(); it != s->constraints.end(); it++) {
progInfo() << " " << *it << "\n";
}
}
#endif
return ret;
}
void Executor::executeST(State *s, const ref<InstValue> &ir) {
memWriteData(s,
s->getPC() + ir->imm9(), // auto wrap 0xFFFF
getReg(s, ir->sr(), ir, true), ir); // bypass uninitialized register null value
}
void Executor::executeLD(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
uint16_t addr = s->getPC() + ir->imm9();
ref<Expr> result;
memReadData(s, addr, result, ir, DR);
if (s->status != State::NORMAL) return;
setReg(s, DR, result, ir);
setCC(s, DR, ir);
}
void Executor::executeJMP(State *s, const ref<InstValue> &ir) {
if (!ir->belongsToOS && ir->baseR() == R_R7) {
if (!s->stackHasMessedUp && !s->colorStack.empty() && s->colorStack.size() < 2) { // in main code
if (auto issueInfo = s->newStateIssue(Issue::ERR_RET_IN_MAIN_CODE, ir)) {
issueInfo->setNote("main code starts at: " + toLC3Hex(s->colorStack.top()) + ".\n");
}
// By default ERROR, but can allow WARNING or NONE
s->stackHasMessedUp = true;
} // otherwise, do nothing, execute it and let SubroutineTracker to handle it
}
if (s->status == State::NORMAL) {
ref<Expr> newPC = getReg(s, ir->baseR(), ir);
if (newPC->getKind() != Expr::Constant) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_SYMBOLIC_PC, ir)) {
issueInfo->setNote("last instruction that set PC: " +
(s->regChangeLocation[R_PC].isNull() ?
"(none)" : reportFormatter->formattedContext(s->regChangeLocation[R_PC])) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
return;
}
setReg(s, R_PC, newPC, ir);
}
}
void Executor::executeJSRR(State *s, const ref<InstValue> &ir) {
// Note: no special handle for JMP R7 for now
ref<Expr> newPC = getReg(s, ir->baseR(), ir);
if (newPC->getKind() != Expr::Constant) {
if (auto issueInfo = s->newStateIssue(Issue::ERR_SYMBOLIC_PC, ir)) {
issueInfo->setNote("last instruction that set PC: " +
(s->regChangeLocation[R_PC].isNull() ?
"(none)" : reportFormatter->formattedContext(s->regChangeLocation[R_PC])) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
return;
}
setReg(s, R_R7, s->getPC(), ir);
setReg(s, R_PC, newPC, ir);
}
void Executor::executeADD(State *s, const ref<InstValue> &ir) {
Reg dr = ir->dr();
ref<Expr> op1 = getReg(s, ir->sr1(), ir);
ref<Expr> op2 = (ir->instDef().format == InstValue::FMT_RRR ?
getReg(s, ir->sr2(), ir) :
static_cast<ref<Expr>>(buildConstant(ir->imm5())));
ref<Expr> result;
// If we encounter Mul expression, it must have been constructed here, so we can safely infer its structure.
// But the expression can be re-written by KLEE so left and right can swap. Use the convention:
// Left: constant. Right: Expr.
auto mul1 = op1->getKind() == klee::Expr::Mul ? dyn_cast<klee::BinaryExpr>(op1) : nullptr;
auto mul2 = op2->getKind() == klee::Expr::Mul ? dyn_cast<klee::BinaryExpr>(op2) : nullptr;
if (mul1) assert(mul1->left->getKind() == klee::Expr::Constant && "Unexpected mul1 structure");
if (mul2) assert(mul2->left->getKind() == klee::Expr::Constant && "Unexpected mul2 structure");
if (op1 == op2) {
// Replace adding itself by multiplying by 2
// Left shift by 1 also works, but multiplying can handle the more general cases in else if below
if (mul1) {
// Fold * 2 into the Mul expression
int mulVal = (castConstant(mul1->left) * 2) % 65536; // any number times 65536 overflows
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), mul1->right);
} else {
result = builder->Mul(buildConstant(2), op1);
}
} else if ((mul1 && mul1->right == op2) || (mul2 && mul2->right == op1)) {
// Fold OP2 into OP1 or vice versa
auto op = (mul1 && mul1->right == op2) ? mul1 : mul2; // the Mul expression
int mulVal = (castConstant(op->left) + 1) % 65536; // any number times 65536 overflows
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), op->right);
} else if (mul1 && mul2 && mul1->right == mul2->right) {
// Combine OP1 and OP2
int mulVal = (castConstant(mul1->left) + castConstant(mul2->left)) % 65536;
if (mulVal == 0) result = buildConstant(0);
else result = builder->Mul(buildConstant(mulVal), mul1->right);
} else {
result = builder->Add(op1, op2); // note: not masking 0xFFFF for now
}
setReg(s, dr, result, ir);
setCC(s, dr, ir);
}
void Executor::executeAND(State *s, const ref<InstValue> &ir) {
Reg dr = ir->dr();
// Here we don't use getReg(), since we don't want to give warning when AND an uninitialized reg with 0
ref<Expr> op1 = s->getReg(ir->sr1());
ref<Expr> op2 = (ir->instDef().format == InstValue::FMT_RRR ?
s->getReg(ir->sr2()) :
static_cast<ref<Expr>>(buildConstant(ir->imm5())));
if (op1.isNull()) {
// NOTE: without optimization like constant folding, it's still possible that op2 must be zero under some
// constraints, but this case is ignored since it is not obvious and should be avoided
if (op2.isNull() || !op2->isZero()) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) ir->sr1()) + ".\n");
}
setReg(s, ir->sr1(), 0, ir); // write back to warning only once
}
}
}
if (op2.isNull()) {
if (op1.isNull() || !op1->isZero()) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) ir->sr2()) + ".\n");
}
setReg(s, ir->sr2(), 0, ir); // write back to warning only once
}
}
}
if (op1.isNull()) op1 = buildConstant(0);
if (op2.isNull()) op2 = buildConstant(0);
ref<Expr> result = builder->And(op1, op2);
setReg(s, dr, result, ir);
setCC(s, dr, ir);
}
void Executor::executeNOT(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
setReg(s, DR, builder->Not(getReg(s, ir->sr1(), ir)), ir);
setCC(s, DR, ir);
}
void Executor::executeLEA(State *s, const ref<InstValue> &ir) {
Reg DR = ir->dr();
setReg(s, DR, s->getPC() + ir->imm9(), ir); // note: not masking 0xFFFF for now
setCC(s, DR, ir);
}
void Executor::executeJSR(State *s, const ref<InstValue> &ir) {
setReg(s, R_R7, s->getPC(), ir);
setReg(s, R_PC, s->getPC() + ir->imm11(), ir); // auto wrap 0xFFFF
}
void Executor::executeTRAP(State *s, const ref<InstValue> &ir) {
if (ir->sourceContent == "INSTANT_HALT") {
s->status = State::HALTED;
return;
}
setReg(s, R_R7, s->getPC(), ir);
ref<Expr> newPC;
memReadData(s, ir->vec8(), newPC, ir, -1); // the vector table given by LC3OS must be constant
if (s->status != State::NORMAL) return;
setReg(s, R_PC, castConstant(newPC), ir);
}
Issue::Type Executor::memReadData(State *s, uint16_t addr, ref<Expr> &result, const ref<InstValue> &ir, int dr) const {
Issue::Type ret = Issue::NO_ISSUE;
ref<MemValue> value = s->mem.read(addr);
if (value.isNull()) { // this is nullptr MemValue, which means the memory is never wrote
if (auto issueInfo = s->newStateIssue(Issue::WARN_POSSIBLE_WILD_READ, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_POSSIBLE_WILD_READ;
}
// State status is set by newStateIssue
result = buildConstant(0); // upper level no longer need to handle null value
} else {
if (value->type == MemValue::MEM_DATA && dyn_cast<DataValue>(value)->forWrite) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_READ_UNINITIALIZED_MEMORY, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_READ_UNINITIALIZED_MEMORY;
}
// State status is set by newStateIssue
} else if (value->type == MemValue::MEM_INST) {
// InstValue *inst = dyn_cast<InstValue>(value);
if (auto issueInfo = s->newStateIssue(Issue::WARN_READ_INST_AS_DATA, ir)) {
issueInfo->setNote("reading addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_READ_INST_AS_DATA;
}
// State status is set by newStateIssue
}
if (value->e.isNull()) { // this is the nullptr value, while the MemValue is not nullptr
if (s->memStoringUninitReg.find(addr) != s->memStoringUninitReg.end()) {
if (dr != -1 &&
dr == s->memStoringUninitReg[addr].first) { // loading data into original register
result = nullptr; // still store nullptr back
} else {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote(
"Using value of: R" + llvm::Twine(s->memStoringUninitReg[addr].first) + "\n" +
" Stored uninitialized reg value into memory at: " +
reportFormatter->formattedContext(s->memStoringUninitReg[addr].second) + ".\n");
ret = Issue::WARN_USE_UNINITIALIZED_REGISTER;
}
// State status is set by newStateIssue
s->memStoringUninitReg.erase(addr); // one warning is enough
result = buildConstant(0); // upper level no longer need to handle null value
}
} else { // otherwise, the warning may have been already generated
result = buildConstant(0); // upper level no longer need to handle null value
}
} else {
result = value->e;
}
}
return ret;
}
Issue::Type Executor::memWriteData(State *s, uint16_t addr, const ref<Expr> &value, const ref<InstValue> &ir) {
Issue::Type ret = Issue::NO_ISSUE;
ref<MemValue> oldVal = s->mem.read(addr);
if (oldVal.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_POSSIBLE_WILD_WRITE, ir)) {
issueInfo->setNote("writing to unspecified addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_POSSIBLE_WILD_WRITE;
}
// State status is set by newStateIssue
} else {
if (oldVal->type == MemValue::MEM_DATA && dyn_cast<DataValue>(oldVal)->forRead) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_WRITE_READ_ONLY_DATA, ir)) {
issueInfo->setNote("overwriting read-only data at addr " + toLC3Hex(addr) + ".\n");
ret = Issue::WARN_WRITE_READ_ONLY_DATA;
}
// State status is set by newStateIssue
} else if (oldVal->type == MemValue::MEM_INST) {
// We don't allow overwriting inst since it makes changes to the flow graph
ref<InstValue> oldInst = dyn_cast<InstValue>(oldVal);
if (auto issueInfo = s->newStateIssue(Issue::ERR_OVERWRITE_INST, ir)) {
issueInfo->setNote("writing to addr " + toLC3Hex(addr) + ", original: " +
reportFormatter->formattedContext(oldInst) + ".\n");
}
assert(s->status == State::BROKEN && "Non-continuable error");
ret = Issue::ERR_OVERWRITE_INST;
return ret;
}
}
/**
* @note About WARN_READ_UNINITIALIZED_REGISTER at ST/STI/STR
* ST/STI/STR can be used to store registers. In that case we don't want to give warning immediately. And if the
* value is simply loaded back to the original register, we would consider these as the storing-loading registers
* and give no warning. But if the value stored into memory now is loaded into another register or used by other
* instructions, we will report WARN_READ_UNINITIALIZED_REGISTER at that time.
*
* This function memWriteData() is called only by ST/STI/STR, and null value of register will get passed through to
* here.
*/
if (value.isNull()) { // is storing uninitialized register into memory
s->memStoringUninitReg[addr] = {ir->sr(), ir}; // All ST/STR/STI are using ir->sr() field
// Continue to write nullptr into memory
} else {
if (s->memStoringUninitReg.find(addr) != s->memStoringUninitReg.end()) {
s->memStoringUninitReg.erase(addr); // no longer storing an uninitialized value
}
}
MemoryManager::WriteResult result = s->mem.writeData(addr, value);
switch (result) {
case MemoryManager::WRITE_SUCCESS:
return ret;
case MemoryManager::WRITE_HALT:
s->status = State::HALTED;
if (s->latestNonOSInst[0]->instID() != InstValue::TRAP) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_MANUAL_HALT, s->latestNonOSInst[0])) {
issueInfo->setNote("last executed instruction: " +
reportFormatter->formattedContext(s->latestNonOSInst[0]) + ".\n");
}
}
return ret;
case MemoryManager::WRITE_DDR:
if (value.isNull()) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
// Here I just don't border to report which register
ret = Issue::WARN_USE_UNINITIALIZED_REGISTER;
}
s->lc3Out.emplace_back(buildConstant(0));
} else {
s->lc3Out.push_back(value);
}
return ret;
default:
assert(!"Unknown return value from mem->writeData()");
}
}
ref<Expr> Executor::getReg(State *s, Reg r, const ref<InstValue> &ir, bool bypassUninitialized) {
ref<Expr> ret = s->getReg(r);
if (ret.isNull()) {
if (!bypassUninitialized) {
if (!ir->belongsToOS) {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) r) + ".\n");
}
}
s->setReg(r, 0); // write back to warn only once, but do not change regChangeLocation
ret = buildConstant(0);
} // Otherwise, bypass the null value to upper level
}
return ret;
}
void Executor::setReg(State *s, Reg r, const ref<Expr> &value, const ref<InstValue> &ir) {
switch (r) {
case R_PC:
assert(value->getKind() == klee::Expr::Constant);
s->setPC(castConstant(value));
case R_IR:
s->setIR(value);
break;
default:
s->setReg(r, value);
break;
}
s->regChangeLocation[r] = ir;
}
void Executor::setReg(State *s, Reg r, uint16_t value, const ref<InstValue> &ir) {
switch (r) {
case R_PC:
s->setPC(value);
break;
case R_IR:
s->setIR(buildConstant(value));
break;
default:
s->setReg(r, value);
break;
}
s->regChangeLocation[r] = ir;
}
void Executor::setCC(State *s, Reg r, const ref<InstValue> &ir) {
s->setCC(r);
s->ccChangeLocation = ir;
}
ref<Expr> Executor::getCCExpr(State *s, const ref<InstValue> &ir) {
ref<Expr> ret = s->getCCExpr();
if (ret.isNull()) {
Reg r = s->getCCSrcReg();
if (r == NUM_REGS) {
s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_CC, ir);
} else {
if (auto issueInfo = s->newStateIssue(Issue::WARN_USE_UNINITIALIZED_REGISTER, ir)) {
issueInfo->setNote("using uninitialized R" + llvm::Twine((int) r) + " (through CC code).\n");
}
// Write back to warn only once, but do not change regChangeLocation and ccChangeLocation
s->setReg(r, 0);
s->setCC(r);
}
ret = buildConstant(0);
}
return ret;
}
} | 37.269694 | 120 | 0.560501 |
7cbfc7ce81026348266e9ae8ec20990e911e02ea | 13,300 | cpp | C++ | packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/utility/archive/test/tstHDF5ArchiveTupleTypes.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file tstHDF5ArchiveTupleTypes.cpp
//! \author Alex Robinson
//! \brief HDF5 archive tuple type unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <sstream>
// FRENSIE Includes
#include "Utility_HDF5IArchive.hpp"
#include "Utility_HDF5OArchive.hpp"
#include "Utility_Tuple.hpp"
#include "Utility_ArrayView.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Template Types
//---------------------------------------------------------------------------//
typedef std::tuple<bool,
char, unsigned char, signed char,
short, unsigned short,
int, unsigned int,
long, unsigned long,
long long, unsigned long long,
float, double, long double> BasicTestTypes;
template<typename... Types>
struct PairTypes;
template<typename T, typename... Types>
struct PairTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::pair<T,T> >(), typename PairTypes<Types...>::type())) type;
};
template<typename T>
struct PairTypes<T>
{
typedef std::pair<T,T> type;
};
template<typename... Types>
struct PairTypes<std::tuple<Types...> > : public PairTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct OneElementTupleTypes;
template<typename T, typename... Types>
struct OneElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T> >(), typename OneElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct OneElementTupleTypes<T>
{
typedef std::tuple<std::tuple<T> > type;
};
template<typename... Types>
struct OneElementTupleTypes<std::tuple<Types...> > : public OneElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct TwoElementTupleTypes;
template<typename T, typename... Types>
struct TwoElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T> >(), typename TwoElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct TwoElementTupleTypes<T>
{
typedef std::tuple<T,T> type;
};
template<typename... Types>
struct TwoElementTupleTypes<std::tuple<Types...> > : public TwoElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct ThreeElementTupleTypes;
template<typename T, typename... Types>
struct ThreeElementTupleTypes<T,Types...>
{
typedef decltype(std::tuple_cat( std::tuple<std::tuple<T,T,T> >(), typename ThreeElementTupleTypes<Types...>::type())) type;
};
template<typename T>
struct ThreeElementTupleTypes<T>
{
typedef std::tuple<std::tuple<T,T,T> > type;
};
template<typename... Types>
struct ThreeElementTupleTypes<std::tuple<Types...> > : public ThreeElementTupleTypes<Types...>
{ /* ... */ };
template<typename... Types>
struct MergeTypeLists;
template<typename T, typename... Types>
struct MergeTypeLists<T,Types...>
{
typedef decltype(std::tuple_cat( T(), typename MergeTypeLists<Types...>::type())) type;
};
template<typename T>
struct MergeTypeLists<T>
{
typedef T type;
};
typedef typename MergeTypeLists<typename PairTypes<BasicTestTypes>::type,typename OneElementTupleTypes<BasicTestTypes>::type,typename TwoElementTupleTypes<BasicTestTypes>::type,typename ThreeElementTupleTypes<BasicTestTypes>::type>::type BasicTupleTestTypes;
//---------------------------------------------------------------------------//
// Testing functions
//---------------------------------------------------------------------------//
template<typename T>
inline T zero( T )
{ return T(0); }
template<typename T1, typename T2>
inline std::pair<T1,T2> zero( std::pair<T1,T2> )
{
return std::make_pair( zero<T1>( T1() ), zero<T2>( T2() ) );
}
template<typename... Types>
inline std::tuple<Types...> zero( std::tuple<Types...> )
{
return std::make_tuple( zero<Types>( Types() )... );
}
template<typename T>
inline T one( T )
{ return T(1); }
template<typename T1, typename T2>
inline std::pair<T1,T2> one( std::pair<T1,T2> )
{
return std::make_pair( one<T1>( T1() ), one<T2>( T2() ) );
}
template<typename... Types>
inline std::tuple<Types...> one( std::tuple<Types...> )
{
return std::make_tuple( one<Types>( Types() )... );
}
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Check that tuple composed of basic types can be archived
FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive,
archive_tuple_basic_types,
BasicTupleTestTypes )
{
FETCH_TEMPLATE_PARAM( 0, T );
std::string archive_name( "test_tuple_basic_types.h5a" );
const T tuple_a = zero(T());
const T tuple_b = one(T());
const T array_a[8] = {one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T()), one(T())};
const T array_b[2][3] = {{one(T()), one(T()), one(T())},{one(T()), one(T()), one(T())}};
std::array<T,10> array_c;
array_c.fill( one(T()) );
{
Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) );
// Array optimization should be used with this type
FRENSIE_REQUIRE( Utility::HDF5OArchive::use_array_optimization::apply<T>::type::value );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_c", array_c ) );
}
{
Utility::HDF5IArchive archive( archive_name );
T extracted_tuple;
T extracted_array_a[8];
T extracted_array_b[2][3];
std::array<T,10> extracted_array_c;
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple ) );
FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple ) );
FRENSIE_CHECK_EQUAL( extracted_tuple, tuple_b );
// Array optimization should be used with this type
FRENSIE_REQUIRE( Utility::HDF5IArchive::use_array_optimization::apply<T>::type::value );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) );
FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( array_a, array_a+8 ),
Utility::ArrayView<const T>( extracted_array_a, extracted_array_a+8 ) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) );
FRENSIE_CHECK_EQUAL( Utility::ArrayView<const T>( &array_b[0][0], &array_b[0][0]+6 ),
Utility::ArrayView<const T>( &extracted_array_b[0][0], &extracted_array_b[0][0]+6 ) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_c", extracted_array_c ) );
FRENSIE_CHECK_EQUAL( array_c, extracted_array_c );
}
}
//---------------------------------------------------------------------------//
// Check that tuple composed of advanced types can be archived
FRENSIE_UNIT_TEST_TEMPLATE( HDF5Archive,
archive_tuple_advanced_types,
BasicTestTypes )
{
FETCH_TEMPLATE_PARAM( 0, T );
std::string archive_name( "test_tuple_advanced_types.h5a" );
const std::pair<T,std::string> pair_a =
std::make_pair( one(T()), std::string("Test message a") );
const std::pair<std::string,T> pair_b =
std::make_pair( std::string("Test message b"), one(T()) );
const std::pair<std::string,std::string> pair_c =
std::make_pair( std::string("Test message c-0"), std::string("Test message c-1") );
const std::tuple<T,std::string> tuple_a =
std::make_tuple( one(T()), std::string("Test message a") );
const std::tuple<std::string,T> tuple_b =
std::make_tuple( std::string("Test message b"), one(T()) );
const std::tuple<std::string,std::string> tuple_c =
std::make_tuple( std::string("Test message c-0"), std::string("Test message c-1") );
const std::pair<T,std::string> array_a[2][3] =
{{std::make_pair(one(T()), std::string("Test message a-00")),
std::make_pair(one(T()), std::string("Test message a-01")),
std::make_pair(one(T()), std::string("Test message a-02"))},
{std::make_pair(zero(T()), std::string("Test message a-10")),
std::make_pair(zero(T()), std::string("Test message a-11")),
std::make_pair(zero(T()), std::string("Test message a-12"))}};
const std::tuple<std::string,T> array_b[6] =
{std::make_tuple(std::string("Test message b-00"), zero(T())),
std::make_tuple(std::string("Test message b-01"), zero(T())),
std::make_tuple(std::string("Test message b-02"), zero(T())),
std::make_tuple(std::string("Test message b-10"), one(T())),
std::make_tuple(std::string("Test message b-11"), one(T())),
std::make_tuple(std::string("Test message b-12"), one(T()))};
{
Utility::HDF5OArchive archive( archive_name, Utility::HDF5OArchiveFlags::OVERWRITE_EXISTING_ARCHIVE );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_a", pair_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_b", pair_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "pair_c", pair_c ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_a", tuple_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_b", tuple_b ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "tuple_c", tuple_c ) );
// Array optimization should be used with these types
FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) );
FRENSIE_REQUIRE( (Utility::HDF5OArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_a", array_a ) );
FRENSIE_REQUIRE_NO_THROW( archive << boost::serialization::make_nvp( "array_b", array_b ) );
}
{
Utility::HDF5IArchive archive( archive_name );
std::pair<T,std::string> extracted_pair_a;
std::pair<std::string,T> extracted_pair_b;
std::pair<std::string,std::string> extracted_pair_c;
std::tuple<T,std::string> extracted_tuple_a;
std::tuple<std::string,T> extracted_tuple_b;
std::tuple<std::string,std::string> extracted_tuple_c;
std::pair<T,std::string> extracted_array_a[2][3];
std::tuple<std::string,T> extracted_array_b[6];
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_a", extracted_pair_a ) );
FRENSIE_CHECK_EQUAL( extracted_pair_a, pair_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_b", extracted_pair_b ) );
FRENSIE_CHECK_EQUAL( extracted_pair_b, pair_b );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "pair_c", extracted_pair_c ) );
FRENSIE_CHECK_EQUAL( extracted_pair_c, pair_c );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_a", extracted_tuple_a ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_a, tuple_a );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_b", extracted_tuple_b ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_b, tuple_b );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "tuple_c", extracted_tuple_c ) );
FRENSIE_CHECK_EQUAL( extracted_tuple_c, tuple_c );
// Array optimization should not be used with these types
FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::pair<T,std::string> >::type::value) );
FRENSIE_REQUIRE( (Utility::HDF5IArchive::use_array_optimization::apply<std::tuple<std::string,T> >::type::value) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_a", extracted_array_a ) );
FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::pair<T,std::string> >( &array_a[0][0], &array_a[0][0]+6 )),
(Utility::ArrayView<const std::pair<T,std::string> >( &extracted_array_a[0][0], &extracted_array_a[0][0]+6 )) );
FRENSIE_REQUIRE_NO_THROW( archive >> boost::serialization::make_nvp( "array_b", extracted_array_b ) );
FRENSIE_CHECK_EQUAL( (Utility::ArrayView<const std::tuple<std::string,T> >( array_b, array_b+6 )),
(Utility::ArrayView<const std::tuple<std::string,T> >( extracted_array_b, extracted_array_b+6 )) );
}
}
//---------------------------------------------------------------------------//
// end tstHDF5ArchiveTupleTypes.cpp
//---------------------------------------------------------------------------//
| 40.060241 | 258 | 0.635338 |
7cc25b5cc7f475ba8cd715a85093f9e839f362d0 | 15,286 | cpp | C++ | src/src/tests/suites/mutation_test_bad.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 5 | 2015-08-25T15:40:09.000Z | 2020-03-15T19:33:22.000Z | src/src/tests/suites/mutation_test_bad.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | null | null | null | src/src/tests/suites/mutation_test_bad.cpp | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 3 | 2019-01-24T13:14:51.000Z | 2022-01-03T07:30:20.000Z | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE operations/mutation
#include <boost/test/unit_test.hpp>
#include <geneial/algorithm/BaseGeneticAlgorithm.h>
#include <geneial/core/fitness/Fitness.h>
#include <geneial/core/fitness/FitnessEvaluator.h>
#include <geneial/core/population/PopulationSettings.h>
#include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h>
#include <geneial/core/population/builder/ContinousMultiValueChromosomeFactory.h>
#include <geneial/core/operations/mutation/MutationSettings.h>
#include <geneial/core/operations/mutation/NonUniformMutationOperation.h>
#include <geneial/core/operations/mutation/UniformMutationOperation.h>
#include <geneial/core/operations/choosing/ChooseRandom.h>
#include "mocks/MockFitnessEvaluator.h"
#include <memory>
using namespace geneial;
using namespace geneial::population::management;
using namespace geneial::operation::choosing;
using namespace geneial::operation::mutation;
using namespace test_mock;
BOOST_AUTO_TEST_SUITE( TESTSUITE_UniformMutationOperation )
//TODO (bewo): Separate Uniform and Nonuniform into separate testcases
//TODO (bewo): Use more mock objects / helper here to avoid tedious duplicate gluecode?
BOOST_AUTO_TEST_CASE( UNIFORM_TEST__basicMutation )
{
/*
* 100% Chance of mutation
* Tests if Chromosomes are actually mutated
*
* Test for Uniform and NonUniform Mutation
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 10, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
BOOST_TEST_MESSAGE("Checking Mutation at 100% probability");
for (double i = 0; i <= 1; i = i + 0.1)
{
MutationSettings mutationSettings(1, i, 0);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000,
0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i);
BOOST_CHECK(inputSet != resultSet_NonUniform);
BOOST_CHECK(inputSet != resultSet_Uniform);
}
// BOOST_TEST_MESSAGE ("");
// BOOST_TEST_MESSAGE ("Checking Mutation at 0% probability");
for (double i = 0; i <= 1; i = i + 0.1)
{
MutationSettings mutationSettings(0, i, 0);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform (mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
BOOST_TEST_MESSAGE("Checking at amount of Mutation = "<< i);
BOOST_CHECK(inputSet == resultSet_NonUniform);
BOOST_CHECK(inputSet == resultSet_Uniform);
}
}
BOOST_AUTO_TEST_CASE( UNIFORM_TEST__Mutation_probability )
{
/*
* Testing Mutation probability for 10000 Testcases
* Checking UNIFOM and NONUNIFORM mutation
*
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings(evaluator, 10, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory(builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
//TODO (bewo): Constantify magic numbers...
for (double probability = 0.0; probability <= 1.0; probability = probability + 0.1)
{
// BaseChromosome<double>::ptr _newChromosome = chromosomeFactory->createChromosome(true);
// BaseMutationOperation<double>::mutation_result_set inputSet;
// BaseMutationOperation<double>::mutation_result_set resultSet[10000];
MutationSettings mutationSettings(probability, 1, 5);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform(1000, 0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform[10000];
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform[10000];
inputSet.push_back(_newChromosome);
int mutationCounter_NonUniform = 0;
int mutationCounter_Uniform = 0;
for (int i = 0; i < 10000; i++)
{
resultSet_NonUniform[i].push_back(_newChromosome);
resultSet_NonUniform[i] = mutationOperation_NonUniform.doMutate(inputSet, manager);
if (inputSet != resultSet_NonUniform[i])
{
mutationCounter_NonUniform++;
}
resultSet_Uniform[i].push_back(_newChromosome);
resultSet_Uniform[i] = mutationOperation_Uniform.doMutate(inputSet, manager);
if (inputSet != resultSet_Uniform[i])
{
mutationCounter_Uniform++;
}
}
if (probability < 0)
{
//Checking for NON-UNIFORM Mutation
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
BOOST_CHECK(mutationCounter_NonUniform == 0);
//Checking for UNIFORM Mutation
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
BOOST_CHECK(mutationCounter_Uniform == 0);
}
else if (probability > 1)
{
//Checking for NON-UNIFORM Mutation
BOOST_CHECK(mutationCounter_NonUniform = 10000);
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
//Checking for UNIFORM Mutation
BOOST_CHECK(mutationCounter_Uniform = 10000);
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
}
else
{
//Checking for NON-UNIFORM Mutation
BOOST_CHECK(mutationCounter_NonUniform > (10000 * probability - 200));
BOOST_CHECK(mutationCounter_NonUniform < (10000 * probability + 200));
BOOST_TEST_MESSAGE("Non-Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_NonUniform);
//Checking for UNIFORM Mutation
BOOST_CHECK(mutationCounter_Uniform > (10000 * probability - 200));
BOOST_CHECK(mutationCounter_Uniform < (10000 * probability + 200));
BOOST_TEST_MESSAGE("Uniform-Mutation porpability: "<< probability);
BOOST_TEST_MESSAGE("Mutated chrmomosomes (Of 10000): "<< mutationCounter_Uniform);
}
}
}
BOOST_AUTO_TEST_CASE ( UNIFORM_TEST__points_of_mutation )
{
/*
* Checking if as many points are mutated as set in Mutation settings
*/
MockFitnessEvaluator<double>::ptr evaluator(new MockFitnessEvaluator<double>());
ContinousMultiValueBuilderSettings<int, double> builderSettings (evaluator, 100, 130, 0, true, 20, 5);
ContinousMultiValueChromosomeFactory<int, double> chromosomeFactory (builderSettings);
BaseManager<double> manager(std::make_shared<ContinousMultiValueChromosomeFactory<int, double>>(chromosomeFactory));
for (unsigned int pointsOfMutation = 0; pointsOfMutation <= 102; pointsOfMutation++)
{
MutationSettings mutationSettings(1, 1, pointsOfMutation);
ChooseRandom<int, double> mutationChoosingOperation(mutationSettings);
NonUniformMutationOperation<int, double> mutationOperation_NonUniform (1000,
0.2, mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
UniformMutationOperation<int, double> mutationOperation_Uniform(mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);
BaseChromosome<double>::ptr _newChromosome = chromosomeFactory.createChromosome(
BaseChromosomeFactory<double>::CREATE_VALUES);
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set inputSet;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_NonUniform;
geneial::operation::mutation::BaseMutationOperation<double>::mutation_result_set resultSet_Uniform;
inputSet.push_back(_newChromosome);
resultSet_NonUniform.push_back(_newChromosome);
resultSet_Uniform.push_back(_newChromosome);
resultSet_NonUniform = mutationOperation_NonUniform.doMutate(inputSet, manager);
resultSet_Uniform = mutationOperation_Uniform.doMutate(inputSet, manager);
//getting Chromosome from resultSet:
MultiValueChromosome<int, double>::ptr mvcMutant_NonUniform = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*resultSet_NonUniform.begin());
MultiValueChromosome<int, double>::ptr mvcMutant_Uniform = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*resultSet_Uniform.begin());
MultiValueChromosome<int, double>::ptr mvcOriginal = std::dynamic_pointer_cast<
MultiValueChromosome<int, double> >(*inputSet.begin());
//getting ValueContainer from Chromosome:
MultiValueChromosome<int, double>::value_container &mvcMutant_NonUniform_valueContainer =
mvcMutant_NonUniform->getContainer();
MultiValueChromosome<int, double>::value_container &mvcMutant_Uniform_valueContainer =
mvcMutant_Uniform->getContainer();
MultiValueChromosome<int, double>::value_container &mvcOriginal_valueContainer = mvcOriginal->getContainer();
//setting Iterators
MultiValueChromosome<int, double>::value_container::iterator original_it = mvcOriginal_valueContainer.begin();
unsigned int nunUniformdiffCounter = 0;
for (MultiValueChromosome<int, double>::value_container::iterator nonUniformMutant_it =
mvcMutant_NonUniform_valueContainer.begin();
nonUniformMutant_it != mvcMutant_NonUniform_valueContainer.end(); ++nonUniformMutant_it)
{
//BOOST_TEST_MESSAGE(original_it);
if (*original_it != *nonUniformMutant_it)
{
nunUniformdiffCounter++;
}
++original_it;
}
BOOST_TEST_MESSAGE("");
BOOST_TEST_MESSAGE(
"Check if as many points were Mutated as specified in MutationSettings: "<< pointsOfMutation);
BOOST_TEST_MESSAGE("NON-UNIFORM: "<< nunUniformdiffCounter);
if (pointsOfMutation != 0)
{
BOOST_CHECK(
(nunUniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100)
|| (nunUniformdiffCounter <= 100 && pointsOfMutation > 100));
}
else
{
BOOST_CHECK(nunUniformdiffCounter >= 90);
}
unsigned int uniformdiffCounter = 0;
original_it = mvcOriginal_valueContainer.begin();
for (MultiValueChromosome<int, double>::value_container::iterator uniformMutant_it =
mvcMutant_Uniform_valueContainer.begin(); uniformMutant_it != mvcMutant_Uniform_valueContainer.end();
++uniformMutant_it)
{
if (*original_it != *uniformMutant_it)
uniformdiffCounter++;
++original_it;
}
BOOST_TEST_MESSAGE("UNIFORM: "<< uniformdiffCounter);
if (pointsOfMutation != 0)
{
BOOST_CHECK(
(uniformdiffCounter <= pointsOfMutation + 5 && pointsOfMutation <= 100)
|| (uniformdiffCounter <= 100 && pointsOfMutation > 100));
}
else
{
BOOST_CHECK(uniformdiffCounter >= 90);
}
}
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE( TESTSUITE_SmoothingMutation )
//Checks whether the smoothing mutation destroys chromosome's smoothness
BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_nonviolated_smoothness )
{
}
//Test whether mutation generates values above/below minmax
BOOST_AUTO_TEST_CASE ( SMOOTHING_TEST__ensure_adherence_min_max )
{
}
//Test Peak at chromosome borders.
BOOST_AUTO_TEST_SUITE_END()
| 45.766467 | 171 | 0.715753 |
7cc4d6366a91a8a61ad3decd9b770103ff9db9c1 | 172 | cpp | C++ | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Font_Asap_Regular_13_4bpp.cpp | ramkumarkoppu/NUCLEO-F767ZI-ESW | 85e129d71ee8eccbd0b94b5e07e75b6b91679ee8 | [
"MIT"
] | null | null | null | #include <touchgfx/hal/Types.hpp>
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const uint8_t unicodes_Asap_Regular_13_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = {
0 // No glyphs
};
| 24.571429 | 91 | 0.819767 |
7cc6263b91af91347ca89106b29f0e127c9f61b6 | 2,524 | cpp | C++ | windows/cpp/samples/CameraToDVD/MuxedStream.cpp | dvdbuilder/dvdbuilder-samples | 8d2b472bd0af899fa342437bb41b33ef8603e0aa | [
"MIT"
] | null | null | null | windows/cpp/samples/CameraToDVD/MuxedStream.cpp | dvdbuilder/dvdbuilder-samples | 8d2b472bd0af899fa342437bb41b33ef8603e0aa | [
"MIT"
] | null | null | null | windows/cpp/samples/CameraToDVD/MuxedStream.cpp | dvdbuilder/dvdbuilder-samples | 8d2b472bd0af899fa342437bb41b33ef8603e0aa | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "MuxedStream.h"
using namespace primo::dvdbuilder::VR;
MuxedStreamCB::MuxedStreamCB()
{
filename[0] = L'\0';
file = NULL;
MainWindow = NULL;
Reset();
}
MuxedStreamCB::~MuxedStreamCB()
{
Reset();
}
void MuxedStreamCB::Reset()
{
if (file)
{
fclose(file);
file = NULL;
}
writeCounter = 0;
pVideoRecorder = NULL;
bProcess = true;
}
bool MuxedStreamCB::WriteData(uint8_t *pBuf, uint32_t bufSize)
{
if (!bProcess)
return false;
++writeCounter;
bool fileResult = true;
if (file)
{
size_t size = fwrite(pBuf,1,bufSize,file);
fileResult = (size == bufSize);
}
bool dvdResult = true;
int stopReason = -1;
if (pVideoRecorder && !pVideoRecorder->write(pBuf, bufSize))
{
ATLTRACE(L"VideoRecorder::Write() failed");
DumpErrorState(pVideoRecorder);
int activeCount, failedCount, noSpaceCount;
CheckRecorderDevices(pVideoRecorder, &activeCount, &failedCount, &noSpaceCount);
ATLASSERT((activeCount + failedCount + noSpaceCount) == pVideoRecorder->devices()->count());
if (0 == activeCount)
{
dvdResult = false;
if (0 == failedCount && noSpaceCount > 0)
stopReason = -2;
}
}
if (fileResult && dvdResult)
return true;
//STOP_CAPTURE
PostMessage(MainWindow, WM_STOP_CAPTURE, stopReason, 0);
bProcess = false;
return false;
}
bool MuxedStreamCB::SetOutputFile(PCWSTR filename)
{
if (file)
{
fclose(file);
file = NULL;
}
if (!filename)
{
this->filename[0] = L'\0';
return true;
}
wcscpy_s(this->filename,256, filename);
file = _wfopen(this->filename, L"wb");
return file != NULL;
}
// primo::Stream
bool_t MuxedStreamCB::open()
{
return TRUE;
}
void MuxedStreamCB::close()
{
}
bool_t MuxedStreamCB::isOpen() const
{
return TRUE;
}
bool_t MuxedStreamCB::canRead() const
{
return FALSE;
}
bool_t MuxedStreamCB::canWrite() const
{
return TRUE;
}
bool_t MuxedStreamCB::canSeek() const
{
return FALSE;
}
bool_t MuxedStreamCB::read(void* buffer, int32_t bufferSize, int32_t* totalRead)
{
return FALSE;
}
bool_t MuxedStreamCB::write(const void* buffer, int32_t dataSize)
{
return WriteData((uint8_t*)buffer, dataSize);
}
int64_t MuxedStreamCB::size() const
{
return -1;
}
int64_t MuxedStreamCB::position() const
{
return -1;
}
bool_t MuxedStreamCB::seek(int64_t position)
{
return FALSE;
}
| 16.496732 | 95 | 0.633914 |
7cc88522847226392bd3715ead508683b3047088 | 1,666 | cc | C++ | PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #include "PhysicsTools/CandAlgos/plugins/EventShapeVarsProducer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "PhysicsTools/CandUtils/interface/Thrust.h"
EventShapeVarsProducer::EventShapeVarsProducer(const edm::ParameterSet& cfg)
{
srcToken_ = consumes<edm::View<reco::Candidate> >(cfg.getParameter<edm::InputTag>("src"));
r_ = cfg.exists("r") ? cfg.getParameter<double>("r") : 2.;
produces<double>("thrust");
//produces<double>("oblateness");
produces<double>("isotropy");
produces<double>("circularity");
produces<double>("sphericity");
produces<double>("aplanarity");
produces<double>("C");
produces<double>("D");
}
void put(edm::Event& evt, double value, const char* instanceName)
{
evt.put(std::make_unique<double>(value), instanceName);
}
void EventShapeVarsProducer::produce(edm::Event& evt, const edm::EventSetup&)
{
//std::cout << "<EventShapeVarsProducer::produce>:" << std::endl;
edm::Handle<edm::View<reco::Candidate> > objects;
evt.getByToken(srcToken_, objects);
Thrust thrustAlgo(objects->begin(), objects->end());
put(evt, thrustAlgo.thrust(), "thrust");
//put(evt, thrustAlgo.oblateness(), "oblateness");
EventShapeVariables eventShapeVarsAlgo(*objects);
put(evt, eventShapeVarsAlgo.isotropy(), "isotropy");
put(evt, eventShapeVarsAlgo.circularity(), "circularity");
put(evt, eventShapeVarsAlgo.sphericity(r_), "sphericity");
put(evt, eventShapeVarsAlgo.aplanarity(r_), "aplanarity");
put(evt, eventShapeVarsAlgo.C(r_), "C");
put(evt, eventShapeVarsAlgo.D(r_), "D");
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(EventShapeVarsProducer);
| 32.666667 | 92 | 0.728091 |
7ccab8672dba2e6cc86748ba2213e2e6c7a12468 | 2,115 | hpp | C++ | src/mbgl/renderer/bucket.hpp | zxlee618/mapbox-gl-native | 04c70f55a534ca7cb4bb5358da3217329643a0f0 | [
"BSL-1.0",
"Apache-2.0"
] | 6 | 2019-06-17T05:41:03.000Z | 2022-01-20T13:16:14.000Z | src/mbgl/renderer/bucket.hpp | zxlee618/mapbox-gl-native | 04c70f55a534ca7cb4bb5358da3217329643a0f0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/renderer/bucket.hpp | zxlee618/mapbox-gl-native | 04c70f55a534ca7cb4bb5358da3217329643a0f0 | [
"BSL-1.0",
"Apache-2.0"
] | 4 | 2019-08-30T07:40:17.000Z | 2022-01-13T09:36:55.000Z | #pragma once
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/style/layer_type.hpp>
#include <mbgl/style/image_impl.hpp>
#include <mbgl/renderer/image_atlas.hpp>
#include <atomic>
namespace mbgl {
namespace gl {
class Context;
} // namespace gl
class RenderLayer;
class PatternDependency;
using PatternLayerMap = std::unordered_map<std::string, PatternDependency>;
class Bucket : private util::noncopyable {
public:
Bucket(style::LayerType layerType_)
: layerType(layerType_) {
}
virtual ~Bucket() = default;
// Check whether this bucket is of the given subtype.
template <class T>
bool is() const;
// Dynamically cast this bucket to the given subtype.
template <class T>
T* as() {
return is<T>() ? reinterpret_cast<T*>(this) : nullptr;
}
template <class T>
const T* as() const {
return is<T>() ? reinterpret_cast<const T*>(this) : nullptr;
}
// Feature geometries are also used to populate the feature index.
// Obtaining these is a costly operation, so we do it only once, and
// pass-by-const-ref the geometries as a second parameter.
virtual void addFeature(const GeometryTileFeature&,
const GeometryCollection&,
const ImagePositions&,
const PatternLayerMap&) {};
virtual void populateFeatureBuffers(const ImagePositions&) {};
virtual void addPatternDependencies(const std::vector<const RenderLayer*>&, ImageDependencies&) {};
// As long as this bucket has a Prepare render pass, this function is getting called. Typically,
// this only happens once when the bucket is being rendered for the first time.
virtual void upload(gl::Context&) = 0;
virtual bool hasData() const = 0;
virtual float getQueryRadius(const RenderLayer&) const {
return 0;
};
bool needsUpload() const {
return hasData() && !uploaded;
}
protected:
style::LayerType layerType;
std::atomic<bool> uploaded { false };
};
} // namespace mbgl
| 28.581081 | 103 | 0.665248 |
7ccf6d8cd7e5457a4ff6c7e03c2a5a56cf69237e | 809 | cpp | C++ | q206-Reverse-Linked-List-recursive-optimized.cpp | risyomei/leetcode | bd0eba2d31eca48c182fc328fab02aac61c15366 | [
"MIT"
] | null | null | null | q206-Reverse-Linked-List-recursive-optimized.cpp | risyomei/leetcode | bd0eba2d31eca48c182fc328fab02aac61c15366 | [
"MIT"
] | null | null | null | q206-Reverse-Linked-List-recursive-optimized.cpp | risyomei/leetcode | bd0eba2d31eca48c182fc328fab02aac61c15366 | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL){
return NULL;
}
if(head -> next == NULL) {
return head;
}
// Cache p in recursive stack
ListNode* p = head;
// Always return t, as that's the last node.
ListNode *t = reverseList(head->next);
// Reverse
p -> next -> next = p;
p -> next = NULL;
return t;
}
};
| 22.472222 | 62 | 0.454883 |
7cd2b544adf16108232c989a22345f250bc5d1f6 | 4,440 | cpp | C++ | src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp | erinloy/GraphEngine | 1a913c18043192c597d48e0b4e77b0a62cd6a10e | [
"MIT"
] | 370 | 2019-05-08T07:40:52.000Z | 2022-03-28T15:29:18.000Z | src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp | qingzhu521/GraphEngine | 56d98c09b8e9a55b4397823f20cf29263c8857b5 | [
"MIT"
] | 55 | 2019-05-20T09:01:48.000Z | 2022-03-31T23:05:23.000Z | src/Trinity.C/src/Storage/MTHash/MTHash.DiskIO.cpp | qingzhu521/GraphEngine | 56d98c09b8e9a55b4397823f20cf29263c8857b5 | [
"MIT"
] | 83 | 2019-05-15T14:16:23.000Z | 2022-03-06T07:04:10.000Z | // Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "Storage/MTHash/MTHash.h"
#include "Storage/MemoryTrunk/MemoryTrunk.h"
using namespace Trinity::IO;
namespace Storage
{
bool MTHash::Save(const String& output_file)
{
BinaryWriter bw(output_file);
bool success = true;
success = success && bw.Write((char)VERSION); // 1B
success = success && bw.Write(ExtendedInfo->NonEmptyEntryCount); // 4B
success = success && bw.Write(ExtendedInfo->FreeEntryCount); // 4B
success = success && bw.Write(ExtendedInfo->FreeEntryList); // 4B
success = success && bw.Write(BucketCount); // 4B
success = success && bw.Write(ExtendedInfo->EntryCount); // 4B
int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry();
int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry();
int32_t bucket_array_length = (int32_t)BucketCount * szBucket();
// Write buckets array
success = success && bw.Write((char*)Buckets, 0, bucket_array_length); // note here we write more
// Write entry array
char* buff = new char[cellentry_array_length];
memcpy(buff, CellEntries, cellentry_array_length);
#pragma region Modify the offset in the entries
char* p = buff;
if (memory_trunk->committed_tail < memory_trunk->head.committed_head ||
(memory_trunk->committed_tail == memory_trunk->head.committed_head && memory_trunk->committed_tail == 0)
)//one segment
{
CellEntry* entryPtr = (CellEntry*)p;
CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount;
for (; entryPtr != entryEndPtr; ++entryPtr)
{
if (entryPtr->offset > 0 && entryPtr->size > 0)
{
entryPtr->offset -= (int32_t)memory_trunk->committed_tail;
}
}
}
else//two segments
{
CellEntry* entryPtr = (CellEntry*)p;
CellEntry* entryEndPtr = entryPtr + ExtendedInfo->NonEmptyEntryCount;
for (; entryPtr != entryEndPtr; ++entryPtr)
{
if (entryPtr->offset >= (int32_t)memory_trunk->head.committed_head && entryPtr->size > 0)
{
entryPtr->offset -=
((int32_t)memory_trunk->committed_tail - (int32_t)memory_trunk->head.append_head);
}
}
}
#pragma endregion
success = success && bw.Write(buff, 0, cellentry_array_length);
delete[] buff;
success = success && bw.Write((char*)MTEntries, 0, mtentry_array_length);
return success;
}
bool MTHash::Reload(const String& input_file)
{
BinaryReader br(input_file);
if (!br.Good())
return false;
DeallocateMTHash();
/*********** Read meta data ************/
int32_t version = (int32_t)br.ReadChar();
if (version != VERSION)
{
Trinity::Diagnostics::FatalError("The Trinity disk image version does not match.");
}
ExtendedInfo->NonEmptyEntryCount = br.ReadInt32();
ExtendedInfo->FreeEntryCount = br.ReadInt32();
ExtendedInfo->FreeEntryList = br.ReadInt32();
if (BucketCount != br.ReadUInt32())
{
Trinity::Diagnostics::FatalError("The Trinity disk image is invalid.");
}
ExtendedInfo->EntryCount = br.ReadUInt32();
int32_t mtentry_array_length = (int32_t)ExtendedInfo->EntryCount * szMTEntry();
int32_t cellentry_array_length = (int32_t)ExtendedInfo->EntryCount * szCellEntry();
int32_t bucket_array_length = (int32_t)BucketCount * szBucket();
/////////////////////////////////////////////////////////
AllocateMTHash();
bool read_success = true;
read_success = read_success && br.Read((char*)Buckets, 0, bucket_array_length);
read_success = read_success && br.Read((char*)CellEntries, 0, cellentry_array_length);
read_success = read_success && br.Read((char*)MTEntries, 0, mtentry_array_length);
return read_success;
}
} | 38.608696 | 116 | 0.592568 |
7cd6712e6afe46868512b116b3c323f376e8e193 | 2,240 | cpp | C++ | code/engine.vc2008/xrGame/items/WeaponDispersion.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/engine.vc2008/xrGame/items/WeaponDispersion.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/engine.vc2008/xrGame/items/WeaponDispersion.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2019-10-20T19:35:34.000Z | 2022-02-28T01:42:10.000Z | // WeaponDispersion.cpp: разбос при стрельбе
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "items/Weapon.h"
#include "inventoryowner.h"
#include "actor.h"
#include "inventory_item_impl.h"
#include "actoreffector.h"
#include "effectorshot.h"
//возвращает 1, если оружие в отличном состоянии и >1 если повреждено
float CWeapon::GetConditionDispersionFactor() const
{
return (1.f + fireDispersionConditionFactor*(1.f-GetCondition()));
}
float CWeapon::GetFireDispersion (bool with_cartridge, bool for_crosshair)
{
if (!with_cartridge) return GetFireDispersion(1.0f, for_crosshair);
if (!m_magazine.empty()) m_fCurrentCartirdgeDisp = m_magazine.back().param_s.kDisp;
return GetFireDispersion (m_fCurrentCartirdgeDisp, for_crosshair);
}
float CWeapon::GetBaseDispersion(float cartridge_k)
{
return fireDispersionBase * cur_silencer_koef.fire_dispersion * cartridge_k * GetConditionDispersionFactor();
}
//текущая дисперсия (в радианах) оружия с учетом используемого патрона
float CWeapon::GetFireDispersion (float cartridge_k, bool for_crosshair)
{
//учет базовой дисперсии, состояние оружия и влияение патрона
float fire_disp = GetBaseDispersion(cartridge_k);
//вычислить дисперсию, вносимую самим стрелком
if(H_Parent())
{
const CInventoryOwner* pOwner = smart_cast<const CInventoryOwner*>(H_Parent());
float parent_disp = pOwner->GetWeaponAccuracy();
fire_disp += parent_disp;
}
return fire_disp;
}
//////////////////////////////////////////////////////////////////////////
// Для эффекта отдачи оружия
void CWeapon::AddShotEffector ()
{
inventory_owner().on_weapon_shot_start (this);
}
void CWeapon::RemoveShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_shot_remove (this);
}
void CWeapon::ClearShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_hide (this);
}
void CWeapon::StopShotEffector ()
{
CInventoryOwner* pInventoryOwner = smart_cast<CInventoryOwner*>(H_Parent());
if (pInventoryOwner)
pInventoryOwner->on_weapon_shot_stop();
}
| 28.35443 | 110 | 0.725446 |
7cd69f6f66570ee16e0dfc4a00208ac3e4fce49a | 1,924 | cpp | C++ | Algorithms/Implementation/The_Bomberman_Game/main.cpp | ugurcan-sonmez-95/HackerRank_Problems | 187d83422128228c241f279096386df5493d539d | [
"MIT"
] | null | null | null | Algorithms/Implementation/The_Bomberman_Game/main.cpp | ugurcan-sonmez-95/HackerRank_Problems | 187d83422128228c241f279096386df5493d539d | [
"MIT"
] | null | null | null | Algorithms/Implementation/The_Bomberman_Game/main.cpp | ugurcan-sonmez-95/HackerRank_Problems | 187d83422128228c241f279096386df5493d539d | [
"MIT"
] | null | null | null | // The Bomberman Game - Solution
#include <iostream>
#include <vector>
std::vector<std::string> bomberMan(const int r, const int c, const int n, const std::vector<std::string> &grid) {
std::vector<std::string> finalGrid1 = grid, finalGrid2, finalGrid3;
for (int i{}; i < r; i++)
for (int j{}; j < c; j++)
finalGrid1[i][j] = 'O';
finalGrid3 = finalGrid2 = finalGrid1;
for (int k{}; k < r; k++) {
for (int l{}; l < c; l++) {
if (grid[k][l] == 'O') {
finalGrid2[k][l] = '.';
if (k > 0)
finalGrid2[k-1][l] = '.';
if (l > 0)
finalGrid2[k][l-1] = '.';
if (l < c-1)
finalGrid2[k][l+1] = '.';
if (k < r-1)
finalGrid2[k+1][l] = '.';
}
}
}
for (int m{}; m < r; m++) {
for (int p{}; p < c; p++) {
if (finalGrid2[m][p] == 'O') {
finalGrid3[m][p] = '.';
if (m > 0)
finalGrid3[m-1][p] = '.';
if (p > 0)
finalGrid3[m][p-1] = '.';
if (p < c-1)
finalGrid3[m][p+1] = '.';
if (m < r-1)
finalGrid3[m+1][p] = '.';
}
}
}
if (n == 1 || n == 0)
return grid;
if (n % 2 == 0)
return finalGrid1;
if (n % 4 == 3)
return finalGrid2;
return finalGrid3;
}
int main() {
int r, c, n;
std::cin >> r >> c >> n;
std::vector<std::string> grid(r);
char ch;
for (int i{}; i < r; i++) {
for (int j{}; j < c; j++) {
std::cin >> ch;
grid[i].push_back(ch);
}
}
const std::vector<std::string> result = bomberMan(r, c, n, grid);
for (auto &el: result)
std::cout << el << '\n';
return 0;
} | 28.716418 | 113 | 0.37526 |
7cd798d6286c3458b708f1391f6a55e9c9d78390 | 27,815 | hpp | C++ | common/cmdline.hpp | Mainvooid/common | fd8f966ba283cb8df619166b41c76fb0cfc6a4c7 | [
"MIT"
] | null | null | null | common/cmdline.hpp | Mainvooid/common | fd8f966ba283cb8df619166b41c76fb0cfc6a4c7 | [
"MIT"
] | null | null | null | common/cmdline.hpp | Mainvooid/common | fd8f966ba283cb8df619166b41c76fb0cfc6a4c7 | [
"MIT"
] | null | null | null | /*
@brief a simple command line parser
@author guobao.v@gmail.com
*/
#ifndef _COMMON_CMDLINE_HPP_
#define _COMMON_CMDLINE_HPP_
#include <common/precomm.hpp>
#include <algorithm>
#ifdef __GNUC__
#include <cxxabi.h>
#endif
/**
@addtogroup common
@{
@defgroup cmdline cmdline - command line parser
@{
@defgroup detail detail
@}
@}
*/
namespace common {
/// @addtogroup common
/// @{
namespace cmdline {
/// @addtogroup cmdline
/// @{
static const std::string _TAG = "cmdline";
namespace detail {
/// @addtogroup detail
/// @{
/**
*@brief 获取类型
*/
static inline std::string demangle(const std::string &name) noexcept
{
#ifdef _MSC_VER
return name;
#elif defined(__GNUC__)
int status = 0;
char *p = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
std::string ret(p);
free(p);
return ret;
#else
#error unexpected c complier (msc/gcc), Need to implement this method for demangle
#endif
}
/**
*@brief 获取类型
*/
template <typename T>
std::string readable_typename() noexcept
{
return demangle(typeid(T).name());
}
template <>
inline std::string readable_typename<std::string>() noexcept { return "string"; }
template <>
inline std::string readable_typename<std::wstring>() noexcept { return "wstring"; }
/**
*@brief T -> string
*/
template <typename T>
std::string default_value(T def) noexcept
{
return convert_to_string<char>(def);
}
/// @}
} // detail --------------------------------------------------
/**
*@brief 模块异常类
*/
class[[deprecated("unnecessary")]]cmdline_error : public std::exception
{
public:
cmdline_error(const std::string msg) : m_msg(std::move(msg)) {}
~cmdline_error() {}
const char *what() const { return m_msg.c_str(); }
private:
std::string m_msg;
};
/**
*@brief string -> T
*/
template <typename T>
class default_reader
{
public:
T operator()(const std::string &str) noexcept(false)
{
return convert_from_string<T>(str);
}
};
/**
*@brief 参数范围检查器
*/
template <typename T>
class range_reader
{
public:
range_reader(const T &low, const T &high) : m_low(low), m_high(high) {}
T operator()(const std::string &s) const noexcept(false)
{
T ret = default_reader<T>()(s);
if (!(ret >= m_low && ret <= m_high)) {
std::ostringstream msg;
msg << _TAG << "..range error";
throw std::range_error(msg.str());
}
return ret;
}
private:
T m_low, m_high;
};
/**
*@brief 返回一个参数范围检查器
*/
template <typename T>
range_reader<T> range(const T &low, const T &high) noexcept
{
return range_reader<T>(low, high);
}
/**
*@brief 可选值检查器
*/
template <typename T>
class oneof_reader
{
public:
oneof_reader() {}
oneof_reader(const std::initializer_list<T> &list) noexcept
{
for (T item : list) {
m_values.push_back(item);
}
}
template <typename ...Values>
oneof_reader(const T& v, const Values&...vs) noexcept
{
add(v, vs...);
}
T operator=(const std::initializer_list<T> &list) noexcept
{
for (T item : list) {
m_values.push_back(item);
}
};
T operator()(const std::string &s) noexcept(false)
{
T ret = default_reader<T>()(s);
if (std::find(m_values.begin(), m_values.end(), ret) == m_values.end()) {
std::ostringstream msg;
msg << _TAG << "..oneof error";
throw std::invalid_argument(msg.str());
}
return ret;
}
template <typename ...Values>
void add(const T& v, const Values&...vs) noexcept
{
m_values.push_back(v);
add(vs...);
}
private:
void add(const T& v) noexcept
{
m_values.push_back(v);
}
private:
std::vector<T> m_values;
};
/**
*@brief 返回一个可选值检查器
*/
template <typename T, typename ...Values>
oneof_reader<T> oneof(const T& a1, const Values&... a2) noexcept
{
return oneof_reader<T>(a1, a2...);
}
/**
*@brief 返回一个可选值检查器
*/
template <typename T>
oneof_reader<T> oneof(const std::initializer_list<T> &list) noexcept
{
return oneof_reader<T>(list);
}
/**
*@brief 命令行解析类
*/
class parser
{
public:
parser() {}
~parser()
{
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
delete_s(p->second);
}
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*/
void add(const std::string &name, char short_name = 0, const std::string &desc = "") noexcept(false)
{
if (options.count(name)) {
std::ostringstream msg;
msg << _TAG << "..multiple definition:" << name;
throw std::invalid_argument(msg.str());
}
options[name] = new option_without_value(name, short_name, desc);
ordered.push_back(options[name]);
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*@param need 是否必需(可选)
*@param def 默认值(可选,当不必需时使用)
*/
template <typename T>
void add(const std::string &name, char short_name = 0, const std::string &desc = "",
bool need = true, const T def = T()) noexcept(false)
{
add(name, short_name, desc, need, def, default_reader<T>());
}
/**
*@brief 添加指定类型的参数
*@param name 长名称
*@param short_name 短名称(\0:表示没有短名称)
*@param desc 描述
*@param need 是否必需(可选)
*@param def 默认值(可选,当不必需时使用)
*@param reader 解析类型
*/
template <class T, class F>
void add(const std::string &name, char short_name = 0, const std::string &desc = "",
bool need = true, const T def = T(), F reader = F()) noexcept(false)
{
if (options.count(name)) {
std::ostringstream msg;
msg << _TAG << "..multiple definition:" << name;
throw std::invalid_argument(msg.str());
}
options[name] = new option_with_value_with_reader<T, F>(name, short_name, need, def, desc, reader);
ordered.push_back(options[name]);
}
/**
*@brief usage尾部添加说明(如果需要解析未指定参数)
*@param f 补充说明
*/
void footer(std::string f) noexcept { ftr = std::move(f); }
/**
*@brief 设置usage程序名,默认由argv[0]确定
*@param name usage程序名
*/
void set_program_name(std::string name) noexcept { prog_name = std::move(name); }
/**
*@brief 判断bool参数是否被指定
*@param name bool参数名
*/
bool exist(const std::string &name) const noexcept(false)
{
if (options.count(name) == 0) {
std::ostringstream msg;
msg << _TAG << "..there is no flag: --" << name;
throw std::invalid_argument(msg.str());
}
return options.find(name)->second->has_set();
}
/**
*@brief 获取参数的值
*@param name 参数名
*@return 返回相应类型参数值
*/
template <class T>
const T &get(const std::string &name) const noexcept(false)
{
if (options.count(name) == 0) {
std::ostringstream msg;
msg << _TAG << "..there is no flag: --" << name;
throw std::invalid_argument(msg.str());
}
const option_with_value<T> *p = dynamic_cast<const option_with_value<T>*>(options.find(name)->second);
if (p == nullptr) {
std::ostringstream msg;
msg << _TAG << "..type mismatch flag '" << name << "'";
throw std::invalid_argument(msg.str());
}
return p->get();
}
/**
*@brief 获取未指定的参数的值
*/
const std::vector<std::string> &rest() const noexcept { return others; }
/**
*@brief 解析一行命令
*@param arg 参数
*@return 是否解析成功
*/
bool parse(const std::string &arg) noexcept
{
std::vector<std::string> args;
std::string buf;
bool in_quote = false;//是否有""
for (std::string::size_type i = 0; i < arg.length(); i++) {
if (arg[i] == '\"') {
in_quote = !in_quote;
continue;
}
if (arg[i] == ' ' && !in_quote) {
args.push_back(buf);
buf = "";
continue;
}
if (arg[i] == '\\') { //跳过'\'
i++;
if (i >= arg.length()) {
errors.push_back("unexpected occurrence of '\\' at end of string");
return false;
}
}
buf += arg[i];
}
if (in_quote) {
errors.push_back("quote is not closed");
return false;
}
if (buf.length() > 0) {
args.push_back(buf);
}
for (size_t i = 0; i < args.size(); i++) {
std::cout << "\"" << args[i] << "\"" << std::endl;
}
return parse(args);
}
/**
*@brief 解析参数数组
*@param args 参数数组
*@return 是否解析成功
*/
bool parse(const std::vector<std::string> &args) noexcept
{
int argc = static_cast<int>(args.size());
std::vector<const char*> argv(argc);
for (int i = 0; i < argc; i++) {
argv[i] = args[i].c_str();
}
return parse(argc, &argv[0]);
}
/**
*@brief 解析参数数组
*@param argc 参数数量(+程序名)
*@param argv 参数值([0]为程序名)
*@return 是否解析成功
*/
bool parse(int argc, const char * const argv[]) noexcept
{
errors.clear();
others.clear();
if (argc < 1) {
errors.push_back("argument number must be bigger than 0");
return false;
}
if (prog_name == "") { prog_name = argv[0]; }
std::map<char, std::string> lookup;
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
if (p->first.length() == 0) {
continue;//key不存在
}
char initial = p->second->short_name();
if (initial) {
if (lookup.count(initial) > 0) {
lookup[initial] = "";
errors.push_back(std::string("short option '") + initial + "' is ambiguous");
return false;
}
else {
lookup[initial] = p->first;
}
}
}
for (int i = 1; i < argc; i++) {
if (strncmp(argv[i], "--", 2) == 0) {//长名称
const char *p = strchr(argv[i] + 2, '=');
if (p) {
std::string name(argv[i] + 2, p);
std::string val(p + 1);
set_option(name, val);
}
else {
std::string name(argv[i] + 2);
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
continue;
}
if (options[name]->has_value()) {
if (i + 1 >= argc) {
errors.push_back("option needs value: --" + name);
continue;
}
else {
i++;
set_option(name, argv[i]);
}
}
else {
set_option(name); //bool
}
}
}
else if (strncmp(argv[i], "-", 1) == 0) {//短名称
if (!argv[i][1]) {//若'-'后无值
continue;
}
char last = argv[i][1];
for (int j = 2; argv[i][j]; j++) {
last = argv[i][j];
if (lookup.count(argv[i][j - 1]) == 0) {
errors.push_back(std::string("undefined short option: -") + argv[i][j - 1]);
continue;
}
if (lookup[argv[i][j - 1]] == "") {
errors.push_back(std::string("ambiguous short option: -") + argv[i][j - 1]);
continue;
}
set_option(lookup[argv[i][j - 1]]);
}
if (lookup.count(last) == 0) {
errors.push_back(std::string("undefined short option: -") + last);
continue;
}
if (lookup[last] == "") {
errors.push_back(std::string("ambiguous short option: -") + last);
continue;
}
if (i + 1 < argc && options[lookup[last]]->has_value()) {
set_option(lookup[last], argv[i + 1]);
i++;
}
else {
set_option(lookup[last]);
}
}
else {
others.push_back(argv[i]);
}
}
for (std::map<std::string, option_base*>::iterator p = options.begin(); p != options.end(); p++) {
if (!p->second->valid()) {
errors.push_back("need option: --" + std::string(p->first));
}
}
return errors.size() == 0;
}
/**
*@brief 包装parse并做检查
*@param arg 一行命令
*/
void parse_check(const std::string &arg) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(0, parse(arg));
}
/**
*@brief 包装parse并做检查
*@param args 参数数组
*/
void parse_check(const std::vector<std::string> &args) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(args.size(), parse(args));
}
/**
*@brief 运行解析器(包装parse并做检查)
*@param argc 参数数量(+程序名)
*@param argv 参数值([0]为程序名)
*@note 仅当命令行参数有效时才返回
如果参数无效,解析器输出错误消息然后退出程序
如果指定了help flag('-help'或'-?')或空命令,则解析器输出用法消息然后退出程序
*/
void parse_check(int argc, char *argv[]) noexcept(false)
{
if (!options.count("help")) {
add("help", '?', "print this message");
}
check(argc, parse(argc, argv));
}
/**
*@brief 返回第一条错误消息
*/
std::string error() const { return errors.size() > 0 ? errors[0] : ""; }
/**
*@brief 返回所有错误消息
*/
std::string error_full() const noexcept
{
std::ostringstream oss;
for (size_t i = 0; i < errors.size(); i++) {
oss << errors[i] << std::endl;
}
return oss.str();
}
/**
*@brief 返回使用方法说明
*/
std::string usage() const noexcept
{
std::ostringstream oss;
oss << "usage: " << prog_name << " ";
for (size_t i = 0; i < ordered.size(); i++) {
if (ordered[i]->must()) {
oss << ordered[i]->short_description() << " ";
}
}
oss << "[options] ... " << ftr << std::endl;
oss << "options:" << std::endl;
size_t max_width = 0;
for (size_t i = 0; i < ordered.size(); i++) {
max_width = std::max(max_width, ordered[i]->name().length());
}
for (size_t i = 0; i < ordered.size(); i++) {
if (ordered[i]->short_name()) {
oss << " -" << ordered[i]->short_name() << ", ";
}
else {
oss << " ";
}
oss << "--" << ordered[i]->name();
for (size_t j = ordered[i]->name().length(); j < max_width + 4; j++) {
oss << ' ';
}
oss << ordered[i]->description() << std::endl;
}
return oss.str();
}
private:
/**
*@brief parse检查
*@param argc 参数数量
*@param ok 是否解析成功
*/
void check(size_t argc, bool ok) noexcept
{
if ((argc == 1 && !ok) || exist("help")) {
std::cerr << usage();
exit(0);
}
if (!ok) {
std::cerr << error() << std::endl << usage();
exit(1);
}
}
/**
*@brief 设置参数选项
*@param name 参数名
*/
void set_option(const std::string &name) noexcept
{
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
return;
}
if (!options[name]->set()) {
errors.push_back("option needs value: --" + name);
return;
}
}
/**
*@brief 设置参数选项
*@param name 参数名
*@param value 参数值
*/
void set_option(const std::string &name, const std::string &value) noexcept {
if (options.count(name) == 0) {
errors.push_back("undefined option: --" + name);
return;
}
if (!options[name]->set(value)) {
errors.push_back("option value is invalid: --" + name + "=" + value);
return;
}
}
/**
*@brief 参数选项基础接口类
*/
class option_base {
public:
virtual ~option_base() {}
virtual bool has_value() const = 0;
virtual bool set() = 0;
virtual bool set(const std::string &value) = 0;
virtual bool has_set() const = 0;
virtual bool valid() const = 0;
virtual bool must() const = 0;
virtual const std::string &name() const = 0;
virtual char short_name() const = 0;
virtual const std::string &description() const = 0;
virtual std::string short_description() const = 0;
};
/**
*@brief 参数选项派生类(无值参数:bool)
*/
class option_without_value : public option_base {
public:
option_without_value(const std::string &name, char short_name, const std::string &desc)
:m_name(name), m_short_name(short_name), m_desc(desc), m_has(false) {}
~option_without_value() {}
bool has_value() const noexcept { return false; }
bool set() noexcept { m_has = true; return true; }
bool set(const std::string &) noexcept { return false; }
bool has_set() const noexcept { return m_has; }
bool valid() const noexcept { return true; }
bool must() const noexcept { return false; }
const std::string &name() const noexcept { return m_name; }
char short_name() const noexcept { return m_short_name; }
const std::string &description() const noexcept { return m_desc; }
std::string short_description() const noexcept { return "--" + m_name; }
private:
std::string m_name;
char m_short_name;
std::string m_desc;
bool m_has;
};
/**
*@brief 参数选项派生类(有值参数)
*/
template <class T>
class option_with_value : public option_base {
public:
/**
*@brief 参数选项派生类(有值参数)
*@param name 长名称
*@param short_name 短名称
*@param need 是否必需
*@param def 默认值
*@param desc 描述
*/
option_with_value(const std::string &name, char short_name, bool need, const T &def, const std::string &desc)
: m_name(name), m_short_name(short_name), m_need(need), m_has(false), m_def(def), m_actual(def)
{
this->desc = full_description(desc);
}
~option_with_value() {}
const T &get() const { return m_actual; }
bool has_value() const { return true; }
bool set() { return false; }
bool set(const std::string &value) noexcept
{
try {
m_actual = read(value);
m_has = true;
}
catch (const std::exception &) {
return false;
}
return true;
}
bool has_set() const { return m_has; }
bool valid() const { return (m_need && !m_has) ? false : true; }
bool must() const { return m_need; }
const std::string &name() const { return m_name; }
char short_name() const { return m_short_name; }
const std::string &description() const { return desc; }
std::string short_description() const noexcept
{
return "--" + m_name + "=" + detail::readable_typename<T>();
}
protected:
std::string full_description(const std::string &desc) noexcept
{
return
desc + " (" + detail::readable_typename<T>() +
(m_need ? "" : " [=" + detail::default_value<T>(m_def) + "]")
+ ")";
}
virtual T read(const std::string &s) = 0;
protected:
std::string m_name;
char m_short_name;
bool m_need;
std::string desc;
bool m_has;
T m_def;///< 默认值
T m_actual;///< 实际值
};
/**
*@brief 有值参数选项派生类
*/
template <class T, class F>
class option_with_value_with_reader : public option_with_value<T>
{
public:
/**
*@brief 有值参数选项派生类
*@param name 长名称
*@param short_name 短名称
*@param need 是否必需
*@param def 默认值
*@param desc 描述
*@param reader 可读包装类型string->T
*/
option_with_value_with_reader(const std::string &name,
char short_name,
bool need,
const T def,
const std::string &desc,
F reader)
: option_with_value<T>(name, short_name, need, def, desc), reader(reader) {}
private:
//string -> T
T read(const std::string &s) noexcept { return reader(s); }
private:
F reader;
};
private:
std::map<std::string, option_base*> options;///< 参数选项map(长名称,一个选项)
std::vector<option_base*> ordered; ///< 有序的参数选项(add时push)
std::string ftr; ///< usage尾部添加说明
std::string prog_name; ///< 程序名
std::vector<std::string> others; ///< 其他为指定参数
std::vector<std::string> errors; ///< 错误消息
};
/// @}
} // cmdline
/// @}
} // common
#endif // _COMMON_CMDLINE_HPP_ | 34.595771 | 125 | 0.39112 |
7cd8af0d239035028cee9ef266413830d55c0fe1 | 969 | cpp | C++ | shell.cpp | s1023006/POSD | 5c12966e967607d9ea06b0a55e799afe8b1c242e | [
"MIT"
] | null | null | null | shell.cpp | s1023006/POSD | 5c12966e967607d9ea06b0a55e799afe8b1c242e | [
"MIT"
] | null | null | null | shell.cpp | s1023006/POSD | 5c12966e967607d9ea06b0a55e799afe8b1c242e | [
"MIT"
] | null | null | null | #include "parser.h"
#include "scanner.h"
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
string input, context = "";
Parser *parser;
while (true)
{
do
{
if (context == "")
cout << "?- ";
else
cout << "| ";
getline(cin, input);
if (input != "")
while (input[0] == ' ')
input = input.substr(1, input.size() - 1);
context += input;
} while (input == "" || context.back() != '.');
if (context == "halt.")
break;
parser = new Parser(Scanner(context));
try
{
parser->buildExpression();
cout << parser->getExpressionTree()->getEvaluateString() << '.' << endl;
}
catch (string &msg)
{
cout << msg << endl;
}
context = "";
}
}
| 24.846154 | 85 | 0.401445 |
7cd96b7b5d529d013f3d3766f874b5fdcbf4943c | 196 | cpp | C++ | samplers/src/simple_sampler.cpp | ton/lightbox | d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb | [
"MIT"
] | null | null | null | samplers/src/simple_sampler.cpp | ton/lightbox | d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb | [
"MIT"
] | null | null | null | samplers/src/simple_sampler.cpp | ton/lightbox | d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb | [
"MIT"
] | null | null | null | #include "samplers/itf/simple_sampler.h"
using namespace lb;
SimpleSampler::SimpleSampler(
const Point2d& upperLeft, const Point2d& bottomRight):
Sampler(upperLeft, bottomRight)
{
}
| 19.6 | 62 | 0.744898 |
7cd9cb30ae181e4ce06afb3e9ea850af4f1ed71d | 6,242 | cc | C++ | mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/storage/ndb/plugin/ndb_schema_result_table.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Implements the interface defined in
#include "storage/ndb/plugin/ndb_schema_result_table.h"
#include <sstream>
#include "storage/ndb/plugin/ndb_thd_ndb.h"
const std::string Ndb_schema_result_table::DB_NAME = "mysql";
const std::string Ndb_schema_result_table::TABLE_NAME = "ndb_schema_result";
const char *Ndb_schema_result_table::COL_NODEID = "nodeid";
const char *Ndb_schema_result_table::COL_SCHEMA_OP_ID = "schema_op_id";
const char *Ndb_schema_result_table::COL_PARTICIPANT_NODEID =
"participant_nodeid";
const char *Ndb_schema_result_table::COL_RESULT = "result";
const char *Ndb_schema_result_table::COL_MESSAGE = "message";
Ndb_schema_result_table::Ndb_schema_result_table(Thd_ndb *thd_ndb)
: Ndb_util_table(thd_ndb, DB_NAME, TABLE_NAME, true) {}
Ndb_schema_result_table::~Ndb_schema_result_table() {}
bool Ndb_schema_result_table::check_schema() const {
// nodeid
// unsigned int
if (!(check_column_exist(COL_NODEID) && check_column_unsigned(COL_NODEID))) {
return false;
}
// schema_op_id
// unsigned int
if (!(check_column_exist(COL_SCHEMA_OP_ID) &&
check_column_unsigned(COL_SCHEMA_OP_ID))) {
return false;
}
// participant_nodeid
// unsigned int
if (!(check_column_exist(COL_PARTICIPANT_NODEID) &&
check_column_unsigned(COL_PARTICIPANT_NODEID))) {
return false;
}
// Check that nodeid + schema_op_id + participant_nodeid is the primary key
if (!check_primary_key(
{COL_NODEID, COL_SCHEMA_OP_ID, COL_PARTICIPANT_NODEID})) {
return false;
}
// result
// unsigned int
if (!(check_column_exist(COL_RESULT) && check_column_unsigned(COL_RESULT))) {
return false;
}
// message
// varbinary, at least 255 bytes long
if (!(check_column_exist(COL_MESSAGE) &&
check_column_varbinary(COL_MESSAGE) &&
check_column_minlength(COL_MESSAGE, 255))) {
return false;
}
return true;
}
bool Ndb_schema_result_table::define_table_ndb(NdbDictionary::Table &new_table,
unsigned mysql_version) const {
// Allow later online add column
new_table.setForceVarPart(true);
// Allow table to be read+write also in single user mode
new_table.setSingleUserMode(NdbDictionary::Table::SingleUserModeReadWrite);
{
// nodeid UNSIGNED NOT NULL
NdbDictionary::Column col_nodeid(COL_NODEID);
col_nodeid.setType(NdbDictionary::Column::Unsigned);
col_nodeid.setNullable(false);
col_nodeid.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_nodeid)) return false;
}
{
// schema_op_id UNSIGNED NOT NULL
NdbDictionary::Column col_schema_op_id(COL_SCHEMA_OP_ID);
col_schema_op_id.setType(NdbDictionary::Column::Unsigned);
col_schema_op_id.setNullable(false);
col_schema_op_id.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_schema_op_id)) return false;
}
{
// participant_nodeid UNSIGNED NOT NULL
NdbDictionary::Column col_participant_nodeid(COL_PARTICIPANT_NODEID);
col_participant_nodeid.setType(NdbDictionary::Column::Unsigned);
col_participant_nodeid.setNullable(false);
col_participant_nodeid.setPrimaryKey(true);
if (!define_table_add_column(new_table, col_participant_nodeid))
return false;
}
{
// result UNSIGNED NOT NULL
NdbDictionary::Column col_result(COL_RESULT);
col_result.setType(NdbDictionary::Column::Unsigned);
col_result.setNullable(false);
if (!define_table_add_column(new_table, col_result)) return false;
}
{
// message VARBINARY(255) NOT NULL
NdbDictionary::Column col_message(COL_MESSAGE);
col_message.setType(NdbDictionary::Column::Varbinary);
col_message.setLength(255);
col_message.setNullable(false);
if (!define_table_add_column(new_table, col_message)) return false;
}
(void)mysql_version; // Only one version can be created
return true;
}
bool Ndb_schema_result_table::need_upgrade() const { return false; }
std::string Ndb_schema_result_table::define_table_dd() const {
std::stringstream ss;
ss << "CREATE TABLE " << db_name() << "." << table_name() << "(\n";
ss << "nodeid INT UNSIGNED NOT NULL,"
"schema_op_id INT UNSIGNED NOT NULL,"
"participant_nodeid INT UNSIGNED NOT NULL,"
"result INT UNSIGNED NOT NULL,"
"message VARBINARY(255) NOT NULL,"
"PRIMARY KEY(nodeid, schema_op_id, participant_nodeid)"
<< ") ENGINE=ndbcluster";
return ss.str();
}
bool Ndb_schema_result_table::drop_events_in_NDB() const {
// Drop the default event
if (!drop_event_in_NDB("REPL$mysql/ndb_schema_result")) return false;
return true;
}
void Ndb_schema_result_table::pack_message(const char *message, char *buf) {
pack_varbinary(Ndb_schema_result_table::COL_MESSAGE, message, buf);
}
std::string Ndb_schema_result_table::unpack_message(
const std::string &packed_message) {
if (!open()) {
return std::string("");
}
return unpack_varbinary(Ndb_schema_result_table::COL_MESSAGE,
packed_message.c_str());
}
| 34.10929 | 79 | 0.73422 |
7cdad3ebcc2bf57b9787e69f1a92a256c4646439 | 990 | cpp | C++ | engine/src/engine/core/layers_stack.cpp | DmitryK579/Tank-Assault | f20cee73fdaa1e1d34f24cc681d781a26a7311a1 | [
"MIT"
] | null | null | null | engine/src/engine/core/layers_stack.cpp | DmitryK579/Tank-Assault | f20cee73fdaa1e1d34f24cc681d781a26a7311a1 | [
"MIT"
] | null | null | null | engine/src/engine/core/layers_stack.cpp | DmitryK579/Tank-Assault | f20cee73fdaa1e1d34f24cc681d781a26a7311a1 | [
"MIT"
] | 2 | 2021-12-16T13:04:18.000Z | 2022-01-07T14:06:06.000Z | #include "pch.h"
#include "layers_stack.h"
engine::layers_stack::~layers_stack()
{
for(auto* layer : m_layers)
{
layer->on_detach();
delete layer;
}
}
void engine::layers_stack::push_layer(layer* layer)
{
m_layers.emplace(m_layers.begin() + m_layers_insert_index, layer);
m_layers_insert_index++;
layer->on_attach();
}
void engine::layers_stack::push_overlay(layer* overlay)
{
m_layers.emplace_back(overlay);
overlay->on_attach();
}
void engine::layers_stack::pop_layer(layer* layer)
{
auto it = std::find(m_layers.begin(), m_layers.end(), layer);
if(it != m_layers.begin() + m_layers_insert_index)
{
layer->on_detach();
m_layers.erase(it);
--m_layers_insert_index;
}
}
void engine::layers_stack::pop_overlay(layer* overlay)
{
auto it = std::find(m_layers.begin(), m_layers.end(), overlay);
if(it != m_layers.end())
{
overlay->on_detach();
m_layers.erase(it);
}
}
| 21.521739 | 70 | 0.638384 |
7cdf425a0f02d64151bfcb78567242dbbd288976 | 431 | hpp | C++ | splayer_ios/splayer_ios/native/Person.hpp | biezhihua/splayer | 82f5b160b30c2d99ba400f5b676dd23795e081c7 | [
"Apache-2.0"
] | 4 | 2019-08-14T08:57:05.000Z | 2019-11-16T18:22:23.000Z | splayer_ios/splayer_ios/native/Person.hpp | biezhihua/SPlayer | 82f5b160b30c2d99ba400f5b676dd23795e081c7 | [
"Apache-2.0"
] | null | null | null | splayer_ios/splayer_ios/native/Person.hpp | biezhihua/SPlayer | 82f5b160b30c2d99ba400f5b676dd23795e081c7 | [
"Apache-2.0"
] | 1 | 2019-11-16T18:22:24.000Z | 2019-11-16T18:22:24.000Z | #ifndef Person_hpp
#define Person_hpp
#include <stdio.h>
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
bool sex;
public:
//默认构造函数,相当于init
Person();
//带参数的构造函数,相当于带参数的init
Person(const char* name , const int age , const bool sex);
//析构函数,用来释放资源,相当于deinit
~Person();
//自我介绍
void introduceMySelf();
};
#endif /* Person_hpp */
| 13.903226 | 62 | 0.617169 |
7ce02368bf5c246ef5364a904b9f1feac6faefc4 | 1,855 | cpp | C++ | flashlight/dataset/ResampleDataset.cpp | josephmisiti/flashlight | a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273 | [
"MIT"
] | 2 | 2020-12-27T18:38:44.000Z | 2021-09-10T20:55:25.000Z | flashlight/dataset/ResampleDataset.cpp | josephmisiti/flashlight | a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273 | [
"MIT"
] | null | null | null | flashlight/dataset/ResampleDataset.cpp | josephmisiti/flashlight | a1349e84c9be19ecbbdc28d2d5a8eeeaaaa06273 | [
"MIT"
] | null | null | null | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ResampleDataset.h"
#include <algorithm>
#include <numeric>
namespace {
std::vector<int64_t> makeIdentityPermutation(int64_t size) {
std::vector<int64_t> perm(size);
std::iota(perm.begin(), perm.end(), 0);
return perm;
}
std::vector<int64_t> makePermutationFromFn(
int64_t size,
const fl::Dataset::PermutationFunction& fn) {
FL_ASSERT(fn, "Permutation function shouldn't be a nullptr");
auto perm = makeIdentityPermutation(size);
std::transform(perm.begin(), perm.end(), perm.begin(), fn);
return perm;
}
} // namespace
namespace fl {
ResampleDataset::ResampleDataset(std::shared_ptr<const Dataset> dataset)
: ResampleDataset(dataset, makeIdentityPermutation(dataset->size())) {}
ResampleDataset::ResampleDataset(
std::shared_ptr<const Dataset> dataset,
std::vector<int64_t> resamplevec)
: dataset_(dataset) {
FL_ASSERT(dataset_, "Dataset shouldn't be a nullptr");
resample(std::move(resamplevec));
}
ResampleDataset::ResampleDataset(
std::shared_ptr<const Dataset> dataset,
const PermutationFunction& fn)
: ResampleDataset(dataset, makePermutationFromFn(dataset->size(), fn)) {}
void ResampleDataset::resample(std::vector<int64_t> resamplevec) {
FL_ASSERT(
size() == resamplevec.size(), "Incorrect vector size for `resample`");
resampleVec_ = std::move(resamplevec);
}
std::vector<af::array> ResampleDataset::get(const int64_t idx) const {
FL_ASSERT(
idx >= 0 && idx < size(),
"Invalid value of idx. idx should be in [0, size())");
return dataset_->get(resampleVec_[idx]);
}
int64_t ResampleDataset::size() const {
return dataset_->size();
}
} // namespace fl
| 27.279412 | 77 | 0.709434 |
7ce095b7f6667f84a76d62e0e9023d433e372d20 | 7,051 | cpp | C++ | src/RSL/UnitTest/RslMigration/TestHarness/main.cpp | nkindberg/RSL | f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a | [
"MIT"
] | 58 | 2018-03-21T09:55:08.000Z | 2022-03-25T07:21:42.000Z | src/RSL/UnitTest/RslMigration/TestHarness/main.cpp | nkindberg/RSL | f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a | [
"MIT"
] | 2 | 2019-01-29T05:56:48.000Z | 2019-05-23T04:44:28.000Z | src/RSL/UnitTest/RslMigration/TestHarness/main.cpp | nkindberg/RSL | f5907fb694c00ebcc6d6ad54e72e9f8a9b66ff0a | [
"MIT"
] | 17 | 2018-03-21T12:10:47.000Z | 2022-03-20T03:24:37.000Z | #define _WINSOCKAPI_
#include <windows.h>
#include <stdio.h>
#include <list>
#include "libfuncs.h"
#include "logging.h"
using namespace std;
using namespace RSLibImpl;
#define NUM_REPLICAS 5
#define MAX_CMD_LEN 256
char procTitles[NUM_REPLICAS][256];
volatile bool endTest;
volatile bool endTestCompleted;
bool StartProcess(char * programName, int replicaId, HANDLE *processHandlePtr)
{
_snprintf_s(procTitles[replicaId-1], MAX_CMD_LEN, "%s %d", programName, replicaId);
printf("%s\n", procTitles[replicaId-1]);
STARTUPINFOA startupInfo;
GetStartupInfoA(&startupInfo);
startupInfo.lpTitle = procTitles[replicaId-1];
PROCESS_INFORMATION processInfo;
if (!CreateProcessA(NULL,
procTitles[replicaId-1],
NULL, // no process security attributes
NULL, // no thread security attributes
FALSE, // inherit handles? no
CREATE_NEW_CONSOLE,
NULL, // no special environment
NULL, //directoryPath,
&startupInfo,
&processInfo)) {
return false;
}
*processHandlePtr = processInfo.hProcess;
CloseHandle(processInfo.hThread);
return true;
}
BOOL CtrlHandler(DWORD ctrlType)
{
if (ctrlType == CTRL_C_EVENT ||
ctrlType == CTRL_BREAK_EVENT)
{
endTest = true;
while (endTestCompleted == false)
{
Sleep(100);
}
}
return FALSE;
}
void ReadNextCommand(int *timeToWaitPtr, list<int> *membersPtr)
{
*timeToWaitPtr = 0;
membersPtr->clear();
char line[1024];
if (fgets(line, 1024, stdin) == NULL) {
return;
}
char *curPos = line, *nextPos;
long timeToWait = strtol(curPos, &nextPos, 10);
if (nextPos == curPos) {
return;
}
curPos = nextPos;
*timeToWaitPtr = (int) timeToWait;
for (;;) {
long memberId = strtol(curPos, &nextPos, 10);
if (nextPos == curPos) {
break;
}
curPos = nextPos;
membersPtr->push_back((int) memberId);
}
}
bool SetConfiguration(int configurationNumber, const list<int>& membersInNextConfiguration)
{
list<int>::const_iterator it;
printf("Setting configuration to:\n");
for (it = membersInNextConfiguration.begin();
it != membersInNextConfiguration.end();
++it) {
printf(" %d", *it);
}
printf("\n");
FILE *fp;
if (fopen_s(&fp, "members.txt", "w")) {
fprintf(stderr, "Could not open members.txt for writing.\n");
return false;
}
fprintf(fp, "%d\n%d\n", configurationNumber, (int)membersInNextConfiguration.size());
for (it = membersInNextConfiguration.begin();
it != membersInNextConfiguration.end();
++it) {
fprintf(fp, "%d\n", *it);
}
fclose(fp);
return true;
}
int GetLastReportedConfigurationNumber ()
{
FILE *fp;
if (fopen_s(&fp, "CurrentConfig.txt", "r")) {
return 0;
}
int lastReportedConfigurationNumber = 0;
fscanf_s(fp, "%d", &lastReportedConfigurationNumber);
fclose(fp);
return lastReportedConfigurationNumber;
}
int __cdecl main(int argc, char **argv)
{
char * programName = "RSLNetTest.exe";
if (argc == 2)
{
programName = argv[1];
}
if (GetFileAttributesA(programName) == INVALID_FILE_ATTRIBUTES)
{
printf("Program '%s' not found!\n", programName);
::ExitProcess(1);
}
if (Logger::Init(".\\") == FALSE)
{
printf("Logger::Init failed\n");
::ExitProcess(1);
}
system("cmd /c rmdir /s /q .\\data");
DeleteFileA("members.txt");
DeleteFileA("CurrentConfig.txt");
Sleep(1000);
int currentConfigurationNumber = 0;
int timeToWaitForConfigurationChange = 0;
list<int> membersInNextConfiguration;
printf("Type timeout and replica set:\n");
ReadNextCommand(&timeToWaitForConfigurationChange, &membersInNextConfiguration);
currentConfigurationNumber++;
SetConfiguration(currentConfigurationNumber, membersInNextConfiguration);
HANDLE processHandle[NUM_REPLICAS];
for (int processNumber = 0; processNumber < NUM_REPLICAS; ++processNumber) {
if (!StartProcess(programName, processNumber+1, &processHandle[processNumber])) {
fprintf(stderr, "ERROR - Could not start process #%d\n", processNumber+1);
return -1;
}
}
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
endTest = false;
endTestCompleted = false;
for (; endTest == false; ) {
DWORD waitResult = WaitForMultipleObjects(NUM_REPLICAS,
processHandle,
FALSE, // don't wait for all of them
1000); // time out after 1000 ms
if (waitResult < WAIT_OBJECT_0 + NUM_REPLICAS) {
int processNumber = waitResult - WAIT_OBJECT_0;
printf("Restarting server %d\n", processNumber+1);
CloseHandle(processHandle[processNumber]);
if (!StartProcess(programName, processNumber+1, &processHandle[processNumber])) {
fprintf(stderr, "ERROR - Could not start process #%d\n", processNumber+1);
break;
}
}
else if (waitResult == WAIT_TIMEOUT) {
--timeToWaitForConfigurationChange;
if (timeToWaitForConfigurationChange < 1) {
int lastReportedConfig = GetLastReportedConfigurationNumber();
if (currentConfigurationNumber != lastReportedConfig) {
fprintf(stderr, "ERROR - Configuration change failed (%d!=%d)!\n",
currentConfigurationNumber, lastReportedConfig);
break;
}
else {
printf("Configuration number check successful.\n");
}
if (membersInNextConfiguration.size() == 0) {
break;
}
ReadNextCommand(&timeToWaitForConfigurationChange, &membersInNextConfiguration);
if (membersInNextConfiguration.size() == 0)
{
break;
}
currentConfigurationNumber++;
if (!SetConfiguration(currentConfigurationNumber, membersInNextConfiguration)) {
break;
}
}
}
else {
printf("WARNING - Unexpected return value %d from WaitForMultipleObjects.\n", waitResult);
}
}
printf("Terminating all processes.\n");
for (int processNumber = 0; processNumber < NUM_REPLICAS; ++processNumber) {
TerminateProcess(processHandle[processNumber], 0);
CloseHandle(processHandle[processNumber]);
}
endTestCompleted = true;
printf("Test complete.\n");
return 0;
}
| 30.392241 | 102 | 0.584598 |
7ceae8a4f83a95e9ee841983fd42e6251bcedc57 | 8,606 | hpp | C++ | include/Mahi/Com/SocketSelector.hpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 1 | 2021-09-22T08:37:01.000Z | 2021-09-22T08:37:01.000Z | include/Mahi/Com/SocketSelector.hpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 1 | 2020-11-16T04:05:47.000Z | 2020-11-16T04:05:47.000Z | include/Mahi/Com/SocketSelector.hpp | chip5441/mahi-com | fc7efcc5d7e9ff995303bbc162e694f25f47d6dd | [
"MIT"
] | 2 | 2020-12-21T09:28:26.000Z | 2021-09-17T03:08:19.000Z | // MIT License
//
// MEL - Mechatronics Engine & Library
// Copyright (c) 2019 Mechatronics and Haptic Interfaces Lab - Rice University
//
// 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.
//
// This particular source file includes code which has been adapted from the
// following open-source projects (all external licenses attached at bottom):
// SFML - Simple and Fast Multimedia Library
//
// Author(s): Evan Pezent (epezent@rice.edu)
#pragma once
#include <Mahi/Util/Timing/Time.hpp>
// #include <Mahi/Util.hpp>
namespace mahi {
namespace com {
class Socket;
/// Multiplexer that allows to read from multiple sockets
class SocketSelector {
public:
/// \brief Default constructor
SocketSelector();
/// \brief Copy constructor
///
/// \param copy Instance to copy
SocketSelector(const SocketSelector& copy);
/// \brief Destructor
~SocketSelector();
/// \brief Add a new socket to the selector
///
/// This function keeps a weak reference to the socket,
/// so you have to make sure that the socket is not destroyed
/// while it is stored in the selector.
/// This function does nothing if the socket is not valid.
///
/// \param socket Reference to the socket to add
///
/// \see remove, clear
void add(Socket& socket);
/// \brief Remove a socket from the selector
///
/// This function doesn't destroy the socket, it simply
/// removes the reference that the selector has to it.
///
/// \param socket Reference to the socket to remove
///
/// \see add, clear
void remove(Socket& socket);
/// \brief Remove all the sockets stored in the selector
///
/// This function doesn't destroy any instance, it simply
/// removes all the references that the selector has to
/// external sockets.
///
/// \see add, remove
void clear();
/// \brief Wait until one or more sockets are ready to receive
///
/// This function returns as soon as at least one socket has
/// some data available to be received. To know which sockets are
/// ready, use the is_ready function.
/// If you use a timeout and no socket is ready before the timeout
/// is over, the function returns false.
///
/// \param timeout Maximum time to wait, (use Time::Zero for infinity)
///
/// \return True if there are sockets ready, false otherwise
///
/// \see is_ready
bool wait(util::Time timeout = util::Time::Zero);
/// \brief Test a socket to know if it is ready to receive data
///
/// This function must be used after a call to Wait, to know
/// which sockets are ready to receive data. If a socket is
/// ready, a call to receive will never block because we know
/// that there is data available to read.
/// Note that if this function returns true for a TcpListener,
/// this means that it is ready to accept a new connection.
///
/// \param socket Socket to test
///
/// \return True if the socket is ready to read, false otherwise
///
/// \see is_ready
bool is_ready(Socket& socket) const;
/// \brief Overload of assignment operator
///
/// \param right Instance to assign
///
/// \return Reference to self
SocketSelector& operator=(const SocketSelector& right);
private:
struct SocketSelectorImpl;
// Member data
SocketSelectorImpl* impl_; ///< Opaque pointer to the implementation (which
///< requires OS-specific types)
};
} // namespace mahi
} // namespace com
/// \class mel::SocketSelector
/// \ingroup communications
///
/// Socket selectors provide a way to wait until some data is
/// available on a set of sockets, instead of just one. This
/// is convenient when you have multiple sockets that may
/// possibly receive data, but you don't know which one will
/// be ready first. In particular, it avoids to use a thread
/// for each socket; with selectors, a single thread can handle
/// all the sockets.
///
/// All types of sockets can be used in a selector:
/// \li mel::TcpListener
/// \li mel::TcpSocket
/// \li mel::UdpSocket
///
/// A selector doesn't store its own copies of the sockets
/// (socket classes are not copyable anyway), it simply keeps
/// a reference to the original sockets that you pass to the
/// "add" function. Therefore, you can't use the selector as a
/// socket container, you must store them outside and make sure
/// that they are alive as long as they are used in the selector.
///
/// Using a selector is simple:
/// \li populate the selector with all the sockets that you want to observe
/// \li make it wait until there is data available on any of the sockets
/// \li test each socket to find out which ones are ready
///
/// Usage example:
/// \code
/// // Create a socket to listen to new connections
/// mel::TcpListener listener;
/// listener.listen(55001);
///
/// // Create a list to store the future clients
/// std::list<mel::TcpSocket*> clients;
///
/// // Create a selector
/// mel::SocketSelector selector;
///
/// // Add the listener to the selector
/// selector.add(listener);
///
/// // Endless loop that waits for new connections
/// while (running)
/// {
/// // Make the selector wait for data on any socket
/// if (selector.wait())
/// {
/// // Test the listener
/// if (selector.is_ready(listener))
/// {
/// // The listener is ready: there is a pending connection
/// mel::TcpSocket* client = new mel::TcpSocket;
/// if (listener.accept(*client) == mel::Socket::Done)
/// {
/// // Add the new client to the clients list
/// clients.push_back(client);
///
/// // Add the new client to the selector so that we will
/// // be notified when he sends something
/// selector.add(*client);
/// }
/// else
/// {
/// // Error, we won't get a new connection, delete the socket
/// delete client;
/// }
/// }
/// else
/// {
/// // The listener socket is not ready, test all other sockets (the
/// clients) for (std::list<mel::TcpSocket*>::iterator it =
/// clients.begin(); it != clients.end(); ++it)
/// {
/// mel::TcpSocket& client = **it;
/// if (selector.is_ready(client))
/// {
/// // The client has sent some data, we can receive it
/// mel::Packet packet;
/// if (client.receive(packet) == mel::Socket::Done)
/// {
/// ...
/// }
/// }
/// }
/// }
/// }
/// }
/// \endcode
///
/// \see mel::Socket
///
//==============================================================================
// LICENSES
//==============================================================================
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2017 Laurent Gomila (laurent@melml-dev.org)
//
// 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.
| 35.415638 | 80 | 0.617128 |
7cee48ebae861eb413998922865af85c7c97f2c7 | 1,119 | cpp | C++ | uva/10855.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 3 | 2020-06-25T21:04:02.000Z | 2021-05-12T03:33:19.000Z | uva/10855.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | null | null | null | uva/10855.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 1 | 2020-06-25T21:04:06.000Z | 2020-06-25T21:04:06.000Z | // Author: btjanaka (Bryon Tjanaka)
// Problem: (UVa) 10855
#include <bits/stdc++.h>
#define GET(x) scanf("%d", &x)
#define GED(x) scanf("%lf", &x)
typedef long long ll;
using namespace std;
#define SZ 5000
int b, s;
char big[SZ][SZ];
char small[SZ][SZ];
char small2[SZ][SZ];
void rotate() {
for (int i = 0; i < s; ++i)
for (int j = 0; j < s; ++j) small2[j][s - i - 1] = small[i][j];
for (int i = 0; i < s; ++i)
for (int j = 0; j < s; ++j) small[i][j] = small2[i][j];
}
int count_match() {
int matched = 0;
for (int i = 0; i <= b - s; ++i) {
for (int j = 0; j <= b - s; ++j) {
bool ok = true;
for (int r = 0; r < s; ++r) {
for (int c = 0; c < s; ++c) {
ok &= small[r][c] == big[r + i][c + j];
}
}
if (ok) ++matched;
}
}
return matched;
}
int main() {
while (GET(b) && GET(s) && !(!b && !s)) {
for (int i = 0; i < b; ++i) scanf("%s", big[i]);
for (int i = 0; i < s; ++i) scanf("%s", small[i]);
for (int i = 0; i < 4; ++i) {
printf("%d%c", count_match(), i == 3 ? '\n' : ' ');
rotate();
}
}
return 0;
}
| 21.941176 | 67 | 0.446828 |
7cf0c63a6872c694335811d2bd24174c58e5614b | 415 | hpp | C++ | tests/thread/tests.hpp | cppfw/nitki | c567c1b60755491bc0c9c53321d175c4df00fc89 | [
"MIT"
] | null | null | null | tests/thread/tests.hpp | cppfw/nitki | c567c1b60755491bc0c9c53321d175c4df00fc89 | [
"MIT"
] | 1 | 2021-04-09T07:35:37.000Z | 2021-04-09T07:35:37.000Z | tests/thread/tests.hpp | cppfw/nitki | c567c1b60755491bc0c9c53321d175c4df00fc89 | [
"MIT"
] | 1 | 2020-12-15T01:38:09.000Z | 2020-12-15T01:38:09.000Z | #pragma once
namespace TestJoinBeforeAndAfterThreadHasFinished{
void Run();
}//~namespace
//====================
//Test many threads
//====================
namespace TestManyThreads{
void Run();
}//~namespace
//==========================
//Test immediate thread exit
//==========================
namespace TestImmediateExitThread{
void Run();
}//~namespace
namespace TestNestedJoin{
void Run();
}//~namespace
| 15.961538 | 50 | 0.575904 |
7cf0e8b4995c34dca1085b51efd5757a1d8b27f2 | 165 | cpp | C++ | src/Task.cpp | amrtechguy/My-Tasks | 9ae9cc08dc78e7852ccd287d75d8bea14e2fb69b | [
"MIT"
] | null | null | null | src/Task.cpp | amrtechguy/My-Tasks | 9ae9cc08dc78e7852ccd287d75d8bea14e2fb69b | [
"MIT"
] | null | null | null | src/Task.cpp | amrtechguy/My-Tasks | 9ae9cc08dc78e7852ccd287d75d8bea14e2fb69b | [
"MIT"
] | null | null | null | #include <iostream>
#include "../include/Task.h"
Task::Task(std::string content_val)
: content {content_val}
{}
std::string Task::get()
{
return content;
} | 15 | 35 | 0.660606 |
7cf265d3489293daa331751f47b69f65516d8386 | 698 | cpp | C++ | Big Number/Division.cpp | MrinmoiHossain/Algorithms | d29a10316219f320b0116ef3b412457a1c1aea26 | [
"MIT"
] | 2 | 2017-06-29T14:04:14.000Z | 2020-03-21T12:48:21.000Z | Big Number/Division.cpp | MrinmoiHossain/Algorithms | d29a10316219f320b0116ef3b412457a1c1aea26 | [
"MIT"
] | null | null | null | Big Number/Division.cpp | MrinmoiHossain/Algorithms | d29a10316219f320b0116ef3b412457a1c1aea26 | [
"MIT"
] | 2 | 2020-03-31T15:45:19.000Z | 2021-09-15T15:51:06.000Z | #include <bits/stdc++.h>
#define LL long long int
using namespace std;
string division(string a, LL b);
int main(void)
{
int T;
cin >> T;
for(int i = 1; i <= T; i++){
string a;
LL b;
cin >> a >> b;
cout << division(a, b) << endl;
}
return 0;
}
string division(string a, LL b)
{
string s;
LL sum = 0, d;
bool flag = 0;
for(int i = 0; i < a.length(); i++){
sum = sum * 10 + (a[i] - '0');
d = sum / b;
if(d == 0 && !flag)
continue;
else{
s += (d + '0');
flag = 1;
sum = (sum % b);
}
}
if(!flag)
s = "0";
return s;
}
| 15.173913 | 40 | 0.395415 |
7cf4fc1fa673ecf24f4cfb082943b0eb8ec5af76 | 520 | cpp | C++ | src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/ApplicationUsageProxy.pypp.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "applicationusageproxy.pypp.hpp"
namespace bp = boost::python;
void register_ApplicationUsageProxy_class(){
bp::class_< osg::ApplicationUsageProxy >( "ApplicationUsageProxy", bp::init< osg::ApplicationUsage::Type, std::string const &, std::string const & >(( bp::arg("type"), bp::arg("option"), bp::arg("explanation") ), " register an explanation of commandline/environmentvariable/keyboard mouse usage.") );
}
| 37.142857 | 304 | 0.728846 |
7cf7478851f0f1e06af485d309aab570636be6a8 | 1,842 | cpp | C++ | da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp | Heliot7/open-set-da | cd3c8c9a2491dd7165259e8fde769046f735a5b8 | [
"BSD-3-Clause"
] | 83 | 2017-11-21T00:50:05.000Z | 2022-03-18T00:54:25.000Z | da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp | Heliot7/open-set-da | cd3c8c9a2491dd7165259e8fde769046f735a5b8 | [
"BSD-3-Clause"
] | 6 | 2017-11-21T00:50:44.000Z | 2021-09-07T13:43:14.000Z | da/min/OPTI/Solvers/Source/scip/scipeventmex.cpp | Heliot7/open-set-da | cd3c8c9a2491dd7165259e8fde769046f735a5b8 | [
"BSD-3-Clause"
] | 15 | 2018-03-06T00:01:29.000Z | 2021-07-28T05:18:16.000Z | /* SCIPMEX - A MATLAB MEX Interface to SCIP
* Released Under the BSD 3-Clause License:
* http://www.i2c2.aut.ac.nz/Wiki/OPTI/index.php/DL/License
*
* Copyright (C) Jonathan Currie 2013
* www.i2c2.aut.ac.nz
*/
#include "scipmex.h"
#include "mex.h"
#include <signal.h>
//Ctrl-C Detection
#ifdef __cplusplus
extern "C" bool utIsInterruptPending();
extern "C" void utSetInterruptPending(bool);
#else
extern bool utIsInterruptPending();
extern void utSetInterruptPending(bool);
#endif
//Executed when adding the event
static SCIP_DECL_EVENTINIT(eventInitCtrlC)
{
//Notify SCIP to add event
SCIP_CALL( SCIPcatchEvent(scip, SCIP_EVENTTYPE_NODESOLVED, eventhdlr, NULL, NULL) );
//Return
return SCIP_OKAY;
}
//Executed when removing the event
static SCIP_DECL_EVENTEXIT(eventExitCtrlC)
{
//Notify SCIP to drop event
SCIP_CALL( SCIPdropEvent(scip, SCIP_EVENTTYPE_NODESOLVED, eventhdlr, NULL, -1) );
//Return
return SCIP_OKAY;
}
//Executed when event occurs
static SCIP_DECL_EVENTEXEC(eventExecCtrlC)
{
//Check for Ctrl-C
if (utIsInterruptPending()) {
utSetInterruptPending(false); /* clear Ctrl-C status */
mexPrintf("\nCtrl-C Detected. Exiting SCIP...\n\n");
raise(SIGINT);
}
return SCIP_OKAY; //always OK - otherwise we don't get intermediate answer
}
//Called from scipmex to include our event
SCIP_RETCODE SCIPincludeCtrlCEventHdlr(SCIP* scip)
{
SCIP_EVENTHDLR* eventhdlr = NULL;
//Create Event Handler
SCIP_CALL( SCIPincludeEventhdlrBasic(scip, &eventhdlr, "CtrlCMatlab", "Catching Ctrl-C From Matlab", eventExecCtrlC, NULL) );
//Setup callbacks
SCIP_CALL( SCIPsetEventhdlrInit(scip, eventhdlr, eventInitCtrlC) );
SCIP_CALL( SCIPsetEventhdlrExit(scip, eventhdlr, eventExitCtrlC) );
return SCIP_OKAY;
} | 28.338462 | 129 | 0.716069 |
7cfb7c135873789f76c032b27d40dd046117f774 | 1,163 | hpp | C++ | src/has_cycle.hpp | deepgrace/giant | 4070c79892957c8e9244eb7a3d7690a25970f769 | [
"BSL-1.0"
] | 6 | 2019-04-02T07:47:37.000Z | 2021-05-31T08:01:04.000Z | src/has_cycle.hpp | deepgrace/giant | 4070c79892957c8e9244eb7a3d7690a25970f769 | [
"BSL-1.0"
] | null | null | null | src/has_cycle.hpp | deepgrace/giant | 4070c79892957c8e9244eb7a3d7690a25970f769 | [
"BSL-1.0"
] | 4 | 2019-04-15T08:52:17.000Z | 2022-03-25T10:29:57.000Z | //
// Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/deepgrace/giant
//
#include <memory>
using namespace std;
template <typename T>
struct node
{
T data;
shared_ptr<node<T>> next;
};
template <typename T>
shared_ptr<node<T>> has_cycle(const shared_ptr<node<T>>& head)
{
auto fast = head;
auto slow = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
int len = 0;
do
{
++len;
fast = fast->next;
}
while (slow != fast);
auto pos = head;
while (len--)
pos = pos->next;
auto start = head;
while (start != pos)
{
pos = pos->next;
start = start->next;
}
return start;
}
}
return nullptr;
}
| 22.365385 | 90 | 0.505589 |
cfab33d4012660362d58479297385300f35539d5 | 2,657 | cpp | C++ | src/todo.cpp | adityasoni01/todo_project | 48f94eeba87f25f4b466d6913c36fd169ec0aba1 | [
"Apache-2.0"
] | null | null | null | src/todo.cpp | adityasoni01/todo_project | 48f94eeba87f25f4b466d6913c36fd169ec0aba1 | [
"Apache-2.0"
] | null | null | null | src/todo.cpp | adityasoni01/todo_project | 48f94eeba87f25f4b466d6913c36fd169ec0aba1 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<string>
#include<cstring>
#include<fstream>
#include<conio.h>
#include<cstdlib>
using namespace std;
string tasks[100];
int total=0,ch;
char yes;
void display()
{
cout<<"Your todo List :-"<<endl;
for(int i = 0;i<total;i++)
{
cout<<i+1<<". "<<tasks[i]<<endl;
}
cout<<endl;
};
void input()
{
do
{
cout<<"Enter Task "<<total+1<<" - ";
getline(cin,tasks[total]);
total++;
cout<<"Would you like to Add more (Y/N) ";
cin>>yes;
cin.ignore();
} while(yes=='y' || yes=='Y');
system("pause");
system("cls");
};
void del()
{
int remove,swap;
display();
cout<<"Enter the task number you want to delete - ";
cin>>remove;
swap =total-remove;
for(int z=0;z<swap;z++)
{
tasks[remove-1]=tasks[remove];
remove=remove+1;
};
tasks[total].erase();
total=total-1;
system("pause");
system("cls");
};
void mscreen()
{
cout<<endl<<"1. Add New Task"<<endl;
cout<<"2. Delete The Completed Tasks"<<endl;
cout<<"3. Exit"<<endl<<"Enter Your Choice :- ";
cin>>ch;
cin.ignore();
system("cls");
};
int storetasks()
{
ofstream fout;
fout.open("list.dat",ios::out|ios::binary);
for(int y=0;y<total;y++)
fout.write((char*)&tasks[y],sizeof(tasks[y]));
fout.close();
return 0;
};
void viewtasks()
{
int x=0,cr;
ifstream fin;
fin.open("list.dat",ios::in|ios::binary);
if(!fin)
{
cout<<"Your todo List :-"<<endl<<"No Todo List Found"<<endl;
cout<<"Press 1 to create New Todo list :- ";
cin>>cr;
cin.ignore();
system("cls");
if(cr==1)
{
input();
storetasks();
}
else
{
exit(1);
}
}
else
{
fin.read((char*)&tasks[x],sizeof(tasks[x]));
while(!fin.eof())
{
total=total+1;
x=x+1;
fin.read((char*)&tasks[x],sizeof(tasks[x]));
}
}
};
int main()
{
viewtasks();
abcdef:
display();
mscreen();
switch (ch)
{
case 1:
input();
storetasks();
goto abcdef;
case 2:
del();
storetasks();
goto abcdef;
case 3:
exit(2);
default:
cout<<"Invalid Response"<<endl;
system("pause");
system("cls");
goto abcdef;
}
return 0;
} | 19.115108 | 68 | 0.451637 |
cfb052a4599f1d20f940cc7b246840a20022dac9 | 3,922 | cpp | C++ | source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp | imallett/MOSS | 5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38 | [
"MIT"
] | 2 | 2020-04-02T14:00:33.000Z | 2021-06-29T05:50:30.000Z | source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp | imallett/MOSS | 5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38 | [
"MIT"
] | null | null | null | source/x86/source_moss/kernel/input/devices/interface_mouse_ps2.cpp | imallett/MOSS | 5ab7bc9c6b1669e2c99aa797d7091c6b52a0ea38 | [
"MIT"
] | null | null | null | #include "interface_mouse_ps2.hpp"
#include "../../../mossc/_misc.hpp"
#include "../../graphics/vesa/controller.hpp"
#include "../../io/io.hpp"
#include "../../kernel.hpp"
#include "../mouse.hpp"
#include "controller_ps2.hpp"
namespace MOSS { namespace Input { namespace Devices {
//TODO: timeouts for all this!
InterfaceDevicePS2Mouse::InterfaceDevicePS2Mouse(ControllerPS2* controller, int device_index, const DeviceType& device_type) : InterfaceDevicePS2Base(controller,device_index,device_type) {
mouse_cycle = 0;
x = last_x = 0;
y = last_y = 0;
for (int i=0;i<5;++i) buttons[i]=false;
}
InterfaceDevicePS2Mouse::~InterfaceDevicePS2Mouse(void) {
}
bool InterfaceDevicePS2Mouse::handle_irq(void) /*override*/ {
if (!InterfaceDevicePS2Base::handle_irq()) return false;
//http://forum.osdev.org/viewtopic.php?t=10247
//http://www.computer-engineering.org/ps2mouse/
uint8_t byte;
controller->recv_data(&byte);
switch (mouse_cycle) {
case 0:
received_data.byte1 = byte;
++mouse_cycle;
//if ((received_data.byte1&0x08)!=0) {
// ++mouse_cycle; //Only accept this as the first byte if the "must be 1" bit is set
//}
break;
case 1:
received_data.byte2 = byte;
++mouse_cycle;
break;
case 2:
received_data.byte3 = byte;
_handle_current_packet();
mouse_cycle = 0;
break;
}
return true;
}
void InterfaceDevicePS2Mouse::set_position(int x, int y) {
assert_term(kernel->graphics!=nullptr&&kernel->graphics->current_mode!=nullptr,"Mouse pointer can only be operated in a graphics mode!"); //But only because we need to check where to not move it.
if (x < 0) x= 0;
else if (x>=kernel->graphics-> width) x=kernel->graphics-> width-1;
if (y < 0) y= 0;
else if (y>=kernel->graphics->height) y=kernel->graphics->height-1;
int dx = x - this->x;
int dy = y - this->y;
if (dx!=0 || dy!=0) {
last_x = this->x;
last_y = this->y;
this->x += dx;
this->y += dy;
kernel->handle_mouse_move(Mouse::EventMouseMove(this->x,this->y,dx,dy));
}
}
void InterfaceDevicePS2Mouse:: click(int button_index) {
kernel->handle_mouse_click(Mouse::EventMouseClick(button_index));
}
void InterfaceDevicePS2Mouse::unclick(int button_index) {
kernel->handle_mouse_unclick(Mouse::EventMouseUnclick(button_index));
}
void InterfaceDevicePS2Mouse::set_sample_rate(int hz) {
#ifdef MOSS_DEBUG
switch (hz) {
case 10: case 20: case 40: case 60: case 80: case 100: case 200: break;
default:
assert_term(false,"Invalid samping rate %d (must be one of 10, 20, 40, 60, 80, 100, 200)!",hz);
}
#endif
//kernel->write(">>Sending 0xF3\n");
send_command_device(0xF3);
//kernel->write(">>Waiting\n");
wait_response();
//kernel->write(">>Sending Hz\n");
//controller->send_data(hz);
send_command_device(hz); //works for some reason? See http://forum.osdev.org/viewtopic.php?f=1&t=26899
//controller->send_data(hz);
//kernel->write(">>Waiting\n");
wait_response();
//kernel->write(">>Done!\n");
}
void InterfaceDevicePS2Mouse::_handle_current_packet(void) {
//http://wiki.osdev.org/PS/2_Mouse
if (received_data.dx_overflowed || received_data.dy_overflowed) return; //Just give up.
int dx = (int)(received_data.dx) - (int)((received_data.byte1<<4)&0x100);
int dy = (int)(received_data.dy) - (int)((received_data.byte1<<3)&0x100);
set_position(x+dx,y+dy);
#define HANDLE_BUTTON(NAME,INDEX)\
if (received_data.NAME && !buttons[INDEX]) {\
buttons[INDEX] = true;\
click(INDEX);\
} else if (!received_data.NAME && buttons[INDEX]) {\
buttons[INDEX] = false;\
unclick(INDEX);\
}
HANDLE_BUTTON( button_left,0)
HANDLE_BUTTON(button_middle,1)
HANDLE_BUTTON( button_right,2)
#undef HANDLE_BUTTON
}
}}}
| 29.051852 | 197 | 0.652728 |
cfb4195ba65d18271a75430f886d6ef75e33811c | 728 | cpp | C++ | 1248/1248/1248/1248.cpp | Shubhankar-Nath/LeetcodeExcercise | 040d413968138c60555c8754fd317a19cd29a601 | [
"MIT"
] | null | null | null | 1248/1248/1248/1248.cpp | Shubhankar-Nath/LeetcodeExcercise | 040d413968138c60555c8754fd317a19cd29a601 | [
"MIT"
] | null | null | null | 1248/1248/1248/1248.cpp | Shubhankar-Nath/LeetcodeExcercise | 040d413968138c60555c8754fd317a19cd29a601 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
int numberOfSubarrays(vector<int>& nums, int k) {
vector<int> oddIndex;
int sum = 0, index=0;
oddIndex.push_back(-1);
for (auto itterator = 0; itterator < nums.size(); itterator++)
{
if (nums[itterator] % 2 != 0) {
oddIndex.push_back(itterator);
}
}
oddIndex.push_back(nums.size());
while ((index+k+1)<oddIndex.size())
{
sum += (oddIndex[index + 1] - oddIndex[index]) * (oddIndex[k + index + 1] - oddIndex[k + index]);
index++;
}
return sum;
}
int main()
{
vector<int> array = { 2,2,2,1,2,2,1,2,2,2,1 };
std::cout << numberOfSubarrays(array, 4);
}
| 22.060606 | 105 | 0.571429 |
cfb50579394ad6701286872b4d235d1ee5af1a68 | 1,306 | cpp | C++ | LLVMpy.cpp | bmansfieldRIT/python2llvm | 8f48661316f753861e4e7623bff4eda29300ddbf | [
"MIT"
] | null | null | null | LLVMpy.cpp | bmansfieldRIT/python2llvm | 8f48661316f753861e4e7623bff4eda29300ddbf | [
"MIT"
] | null | null | null | LLVMpy.cpp | bmansfieldRIT/python2llvm | 8f48661316f753861e4e7623bff4eda29300ddbf | [
"MIT"
] | null | null | null | #include "graminit.h"
#include "CharStream.hpp"
#include <iostream>
#include "llvm/ADT/STLExtras.h"
std::unique_ptr<CharStream> cs;
static int gettok(){
static int lastChar = ' ';
while (isspace(lastChar)) {
cs->next();
lastChar = cs->getCurrent();
}
if (lastChar == '#'){
cout << "read a comment\n";
do {
cs->next();
lastChar = cs->getCurrent();
} while (lastChar != EOF && lastChar != '\n' && lastChar != '\r');
}
if (lastChar == EOF) {
return eof_tok;
}
int thisChar = lastChar;
cs->next();
lastChar = cs->getCurrent();
return thisChar;
}
static int CurTok;
static int getNextToken() {
return CurTok = gettok();
}
int main(int argc, char **argv){
bool help = false;
string helpMsg = "Options: --help\n";
string helpFlag("--help");
// checking for flags
for (int i = 0; i < argc; i++){
char* arg = argv[i];
if (arg == helpFlag){
help = true;
}
}
if (help){
std::cout << helpMsg;
exit(1);
}
char* filename = argv[argc - 1];
// Create character stream
cs = llvm::make_unique<CharStream>(filename);
cout << "Created character stream\n";
getNextToken();
return 0;
}
| 19.492537 | 74 | 0.532159 |
cfb74c5f61e72e167965cd3b6a4877121efebe2c | 2,131 | cpp | C++ | KEditor/Entity/KEEntityNamePool.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 13 | 2019-10-19T17:41:19.000Z | 2021-11-04T18:50:03.000Z | KEditor/Entity/KEEntityNamePool.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | 3 | 2019-12-09T06:22:43.000Z | 2020-05-28T09:33:44.000Z | KEditor/Entity/KEEntityNamePool.cpp | King19931229/KApp | f7f855b209348f835de9e5f57844d4fb6491b0a1 | [
"MIT"
] | null | null | null | #include "KEEntityNamePool.h"
#include "KEditorGlobal.h"
KEEntityNamePool::KEEntityNamePool()
{
}
KEEntityNamePool::~KEEntityNamePool()
{
ASSERT_RESULT(m_Pool.empty());
}
bool KEEntityNamePool::Init()
{
UnInit();
return true;
}
bool KEEntityNamePool::UnInit()
{
m_Pool.clear();
return true;
}
std::string KEEntityNamePool::NamePoolElement::AllocName()
{
assert(m_FreedName.size() == m_ReservedNameStack.size());
if (!m_ReservedNameStack.empty())
{
std::string oldName = m_ReservedNameStack.top();
m_ReservedNameStack.pop();
ASSERT_RESULT(m_FreedName.erase(oldName));
ASSERT_RESULT(m_AllocatedName.insert(oldName).second);
return oldName;
}
else
{
std::string newName = prefix + "_" + std::to_string(m_NameCounter++);
ASSERT_RESULT(m_AllocatedName.insert(newName).second);
return newName;
}
}
bool KEEntityNamePool::NamePoolElement::FreeName(const std::string& name)
{
auto it = m_AllocatedName.find(name);
if (it != m_AllocatedName.end())
{
bool notInFreeName = m_FreedName.find(name) == m_FreedName.end();
ASSERT_RESULT(notInFreeName);
if (notInFreeName)
{
ASSERT_RESULT(m_FreedName.insert(name).second);
m_ReservedNameStack.push(name);
assert(m_FreedName.size() == m_ReservedNameStack.size());
}
m_AllocatedName.erase(it);
return true;
}
return false;
}
bool KEEntityNamePool::GetBaseName(const std::string& name, std::string& baseName)
{
auto pos = name.find_last_of('_');
if (pos == std::string::npos || pos == name.length() - 1)
{
return false;
}
baseName = name.substr(0, pos);
return true;
}
void KEEntityNamePool::FreeName(const std::string& name)
{
std::string baseName;
if (GetBaseName(name, baseName))
{
auto poolIt = m_Pool.find(baseName);
if (poolIt != m_Pool.end())
{
NamePoolElement& element = poolIt->second;
element.FreeName(name);
}
}
}
std::string KEEntityNamePool::AllocName(const std::string& prefix)
{
auto poolIt = m_Pool.find(prefix);
if (poolIt == m_Pool.end())
{
poolIt = m_Pool.insert({ prefix, NamePoolElement(prefix) }).first;
}
NamePoolElement& element = poolIt->second;
return element.AllocName();
} | 21.525253 | 82 | 0.712342 |
cfb7c3be207d4d876b2478472d249000d3e74726 | 9,931 | cpp | C++ | jigtest/src/framework/sdlapplicationbase.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 10 | 2016-06-01T12:54:45.000Z | 2021-09-07T17:34:37.000Z | jigtest/src/framework/sdlapplicationbase.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | null | null | null | jigtest/src/framework/sdlapplicationbase.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 4 | 2017-05-03T14:03:03.000Z | 2021-01-04T04:31:15.000Z | //==============================================================
// Copyright (C) 2004 Danny Chapman
// danny@rowlhouse.freeserve.co.uk
//--------------------------------------------------------------
//
/// @file SDLApplicationbase.cpp
//
//==============================================================
#include "sdlapplicationbase.hpp"
#include "graphics.hpp"
#include <stdio.h>
using namespace std;
using namespace JigLib;
void tSDLApplicationBase::LoadConfig(int & argc, char * argv[],
string configFileName)
{
// setup config/tracing
bool configFileOk;
if (argc > 1)
configFileName = string(argv[1]);
mConfigFile = new tConfigFile(configFileName, configFileOk);
if (!configFileOk)
TRACE("Warning: Unable to open main config file: %s\n", configFileName.c_str());
// initialise trace
// set up tracing properly
bool traceEnabled = true;
int traceLevel = 3;
bool traceAllStrings = true;
vector<string> traceStrings;
mConfigFile->GetValue("trace_enabled", traceEnabled);
mConfigFile->GetValue("trace_level", traceLevel);
mConfigFile->GetValue("trace_all_strings", traceAllStrings);
mConfigFile->GetValues("trace_strings", traceStrings);
EnableTrace(traceEnabled);
SetTraceLevel(traceLevel);
EnableTraceAllStrings(traceAllStrings);
AddTraceStrings(traceStrings);
TRACE_FILE_IF(ONCE_1)
TRACE("Logging set up\n");
}
//==============================================================
// tSDLApplicationBase
//==============================================================
tSDLApplicationBase::tSDLApplicationBase(int & argc, char * argv[],
string configFileName,
void (* licenseFn)(void))
{
TRACE_METHOD_ONLY(ONCE_1);
LoadConfig(argc, argv, configFileName);
if (licenseFn)
(*licenseFn)();
else
DisplayLicense();
}
//==============================================================
// ~tSDLApplicationBase
//==============================================================
tSDLApplicationBase::~tSDLApplicationBase()
{
TRACE_METHOD_ONLY(ONCE_1);
}
//==============================================================
// Initialise
//==============================================================
bool tSDLApplicationBase::Initialise(const std::string app_name)
{
TRACE_METHOD_ONLY(ONCE_1);
// intialise some vars
mStartOfFrameTime = tTime(0.0f);
mOldStartOfFrameTime = tTime(0.0f);
mFPSInterval = tTime(1.0f);
mLastStoredTime = tTime(0.0f);
mFPSCounter = 0;
mFPS = 1.0f;
mNewFPS = true;
TRACE_FILE_IF(ONCE_2)
TRACE("Initializing SDL.\n");
if((SDL_Init(SDL_INIT_VIDEO)==-1)) {
TRACE("Could not initialize SDL: %s.\n", SDL_GetError());
return false;
}
/* Clean up on exit */
atexit(SDL_Quit);
TRACE_FILE_IF(ONCE_2)
TRACE("SDL initialized.\n");
// Information about the current video settings.
const SDL_VideoInfo* info = NULL;
// get some video information.
info = SDL_GetVideoInfo( );
if( !info ) {
TRACE("Video query failed: %s\n",
SDL_GetError( ) );
return false;
}
mWindowWidth = 800;
mWindowHeight = 600;
mConfigFile->GetValue("window_width", mWindowWidth);
mConfigFile->GetValue("window_height", mWindowHeight);
int bpp = info->vfmt->BitsPerPixel;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
bool fullscreen = false;
mConfigFile->GetValue("fullscreen", fullscreen);
// don't allow resizing for now - textures etc get zapped
int flags = SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);
SDL_Surface *screen = SDL_SetVideoMode( mWindowWidth,
mWindowHeight,
bpp,
flags );
if( screen == 0 )
{
TRACE("Video mode set failed: %s\n", SDL_GetError( ) );
return false;
}
return true;
}
//==============================================================
// GetTimeNow
//==============================================================
tTime tSDLApplicationBase::GetTimeNow() const
{
Uint32 millisec = SDL_GetTicks();
return millisec * 0.001f;
}
//==============================================================
// InternalHandleStartOfLoop
//==============================================================
void tSDLApplicationBase::InternalHandleStartOfLoop()
{
mOldStartOfFrameTime = mStartOfFrameTime;
mStartOfFrameTime = GetTimeNow();
if ( (mStartOfFrameTime > 0.0f) &&
(mStartOfFrameTime < mFPSInterval) )
{
mFPS = mFPSCounter / mStartOfFrameTime;
}
if (mStartOfFrameTime - mLastStoredTime >= mFPSInterval)
{
mFPS = (tScalar) mFPSCounter;
mLastStoredTime = mStartOfFrameTime;
mFPSCounter = 0;
mNewFPS = true;
}
else
{
++mFPSCounter;
mNewFPS = false;
}
}
//==============================================================
// StartMainLoop
//==============================================================
void tSDLApplicationBase::StartMainLoop()
{
mExitMainLoop = false;
while( false == mExitMainLoop )
{
InternalHandleStartOfLoop();
// do all the basic stuff like keyboard, mouse etc, callint the
// app.
ProcessEvents();
// get the app to do it's own stuff - e.g. physics, rendering
ProcessMainEvent();
}
}
//==============================================================
// InternalHandleResize
//==============================================================
void tSDLApplicationBase::InternalHandleResize(const SDL_ResizeEvent & event)
{
bool fullscreen = false;
mConfigFile->GetValue("fullscreen", fullscreen);
mWindowWidth = event.w;
mWindowHeight = event.h;
const SDL_VideoInfo* info = SDL_GetVideoInfo( );
if( !info ) {
TRACE("Video query failed: %s\n",
SDL_GetError( ) );
return;
}
int bpp = info->vfmt->BitsPerPixel;
int flags = SDL_RESIZABLE | SDL_OPENGL | (fullscreen ? SDL_FULLSCREEN : 0);
SDL_Surface *screen = SDL_SetVideoMode( mWindowWidth,
mWindowHeight,
bpp,
flags );
if( screen == 0 )
{
TRACE("Video mode set failed: %s\n", SDL_GetError( ) );
}
}
//==============================================================
// ProcessEvents
//==============================================================
void tSDLApplicationBase::ProcessEvents()
{
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
switch( event.type ) {
case SDL_KEYDOWN:
HandleKeyDown( event.key.keysym );
break;
case SDL_KEYUP:
HandleKeyUp( event.key.keysym );
break;
case SDL_MOUSEMOTION:
HandleMouseMotion( event.motion );
break;
case SDL_MOUSEBUTTONDOWN:
HandleMouseButtonDown( event.button );
break;
case SDL_MOUSEBUTTONUP:
HandleMouseButtonUp( event.button );
break;
case SDL_VIDEORESIZE:
InternalHandleResize( event.resize );
break;
case SDL_QUIT:
/* Handle quit requests (like Ctrl-c). */
exit(0);
break;
}
}
}
//==============================================================
// HandleReShape
//==============================================================
void tSDLApplicationBase::HandleReShape(int newWidth, int newHeight)
{
}
//==============================================================
// DisplayLicense
//==============================================================
void tSDLApplicationBase::DisplayLicense()
{
TRACE("Application Copyright 2004 Danny Chapman: danny@rowlhouse.freeserve.co.uk\n");
TRACE("Application comes with ABSOLUTELY NO WARRANTY;\n");
TRACE("This is free software, and you are welcome to redistribute it\n");
TRACE("under certain conditions; see the GNU General Public License\n");
}
//===========================================================
// Code to write out screen shots
//==========================================================
static void FlipVertical(unsigned char *data, int w, int h)
{
int x, y, i1, i2;
unsigned char temp;
for (x=0;x<w;x++){
for (y=0;y<h/2;y++){
i1 = (y*w + x)*3; // this pixel
i2 = ((h - y - 1)*w + x)*3; // its opposite (across x-axis)
// swap pixels
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
i1++; i2++;
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
i1++; i2++;
temp = data[i1];
data[i1] = data[i2];
data[i2] = temp;
}
}
}
//==============================================================
// writeFrameBuffer
//==============================================================
static void WriteFrameBuffer(char *filename)
{
FILE *fp = fopen(filename, "wb");
int width, height;
GetWindowSize(width, height);
int data_size = width * height * 3;
unsigned char *framebuffer =
(unsigned char *) malloc(data_size * sizeof(unsigned char));
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);
FlipVertical(framebuffer, width, height);
fprintf(fp, "P6\n%d %d\n%d\n", width, height, 255);
fwrite(framebuffer, data_size, 1, fp);
fclose(fp);
free(framebuffer);
}
//==============================================================
// DoScreenshot
//==============================================================
void tSDLApplicationBase::DoScreenshot()
{
static int count = 0;
static char screen_file[] = "screenshot-00000.ppm";
sprintf(screen_file, "screenshot-%05d.ppm", count++);
// printf("%s\n", movie_file);
WriteFrameBuffer(screen_file);
}
| 28.133144 | 87 | 0.518578 |
cfb7f0230a3dad9f838546d1c0b8a0a0989955ba | 17,656 | cpp | C++ | Source/System/[Platforms]/Windows/Interface.Windows.cpp | jbatonnet/System | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | 3 | 2020-04-24T20:23:24.000Z | 2022-01-06T22:27:01.000Z | Source/System/[Platforms]/Windows/Interface.Windows.cpp | jbatonnet/system | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | null | null | null | Source/System/[Platforms]/Windows/Interface.Windows.cpp | jbatonnet/system | 227cf491ab5d0660a6bcf654f6cad09d1f82ba8e | [
"MIT"
] | 1 | 2021-06-25T17:35:08.000Z | 2021-06-25T17:35:08.000Z | #ifdef WINDOWS
#include <System/System.h>
using namespace System;
using namespace System::Runtime;
using namespace System::Objects;
using namespace System::Devices;
using namespace System::IO;
using namespace System::Interface;
using namespace System::Graphics;
#undef using
#define _INITIALIZER_LIST_
#include <Windows.h>
#include <Dwmapi.h>
#include <cstdlib>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX_WINDOWS_COUNT 32
using namespace std;
struct WindowInfo
{
Window* Window;
Surface* Surface;
HWND Hwnd;
};
struct PendingWindowInfo
{
Window* Window;
};
vector<WindowInfo> windowInfos;
queue<PendingWindowInfo> pendingWindowInfos;
Buttons virtualKeyMapping[0x100] = {
(Buttons)0x00, (Buttons)0x01, (Buttons)0x02, (Buttons)0x03, (Buttons)0x04, (Buttons)0x05, (Buttons)0x06, (Buttons)0x07, Buttons::Backspace, Buttons::Tab, (Buttons)0x0A, (Buttons)0x0B, (Buttons)0x0C, Buttons::Enter, (Buttons)0x0E, (Buttons)0x0F,
Buttons::Shift, Buttons::Control, Buttons::Alt, (Buttons)0x13, Buttons::CapsLock, (Buttons)0x15, (Buttons)0x16, (Buttons)0x17, (Buttons)0x18, (Buttons)0x19, (Buttons)0x1A, Buttons::Escape, (Buttons)0x1C, (Buttons)0x1D, (Buttons)0x1E, (Buttons)0x1F,
Buttons::Space, Buttons::PageUp, Buttons::PageDown, Buttons::End, Buttons::Origin, Buttons::Left, Buttons::Up, Buttons::Right, Buttons::Down, (Buttons)0x29, (Buttons)0x2A, (Buttons)0x2B, (Buttons)0x2C, Buttons::Insert, Buttons::Delete, (Buttons)0x2F,
Buttons::Digit0, Buttons::Digit1, Buttons::Digit2, Buttons::Digit3, Buttons::Digit4, Buttons::Digit5, Buttons::Digit6, Buttons::Digit7, Buttons::Digit8, Buttons::Digit9, (Buttons)0x3A, (Buttons)0x3B, (Buttons)0x3C, (Buttons)0x3D, (Buttons)0x3E, (Buttons)0x3F,
(Buttons)0x40, Buttons::A, Buttons::B, Buttons::C, Buttons::D, Buttons::E, Buttons::F, Buttons::G, Buttons::H, Buttons::I, Buttons::J, Buttons::K, Buttons::L, Buttons::M, Buttons::N, Buttons::O,
Buttons::P, Buttons::Q, Buttons::R, Buttons::S, Buttons::T, Buttons::U, Buttons::V, Buttons::W, Buttons::X, Buttons::Y, Buttons::Z, (Buttons)0x5B, (Buttons)0x5C, (Buttons)0x5D, (Buttons)0x5E, (Buttons)0x5F,
(Buttons)0x60, (Buttons)0x61, (Buttons)0x62, (Buttons)0x63, (Buttons)0x64, (Buttons)0x65, (Buttons)0x66, (Buttons)0x67, (Buttons)0x68, (Buttons)0x69, (Buttons)0x6A, (Buttons)0x6B, (Buttons)0x6C, (Buttons)0x6D, (Buttons)0x6E, (Buttons)0x6F,
Buttons::F1, Buttons::F2, Buttons::F3, Buttons::F4, Buttons::F5, Buttons::F6, Buttons::F7, Buttons::F8, Buttons::F9, Buttons::F10, Buttons::F11, Buttons::F12, (Buttons)0x7C, (Buttons)0x7D, (Buttons)0x7E, (Buttons)0x7F,
(Buttons)0x80, (Buttons)0x81, (Buttons)0x82, (Buttons)0x83, (Buttons)0x84, (Buttons)0x85, (Buttons)0x86, (Buttons)0x87, (Buttons)0x88, (Buttons)0x89, (Buttons)0x8A, (Buttons)0x8B, (Buttons)0x8C, (Buttons)0x8D, (Buttons)0x8E, (Buttons)0x8F,
Buttons::NumLock, (Buttons)0x91, (Buttons)0x92, (Buttons)0x93, (Buttons)0x94, (Buttons)0x95, (Buttons)0x96, (Buttons)0x97, (Buttons)0x98, (Buttons)0x99, (Buttons)0x9A, (Buttons)0x9B, (Buttons)0x9C, (Buttons)0x9D, (Buttons)0x9E, (Buttons)0x9F,
Buttons::LeftShift, Buttons::RightShift, Buttons::LeftControl, Buttons::RightControl, (Buttons)0xA4, (Buttons)0xA5, (Buttons)0xA6, (Buttons)0xA7, (Buttons)0xA8, (Buttons)0xA9, (Buttons)0xAA, (Buttons)0xAB, (Buttons)0xAC, (Buttons)0xAD, (Buttons)0xAE, (Buttons)0xAF,
(Buttons)0xB0, (Buttons)0xB1, (Buttons)0xB2, (Buttons)0xB3, (Buttons)0xB4, (Buttons)0xB5, (Buttons)0xB6, (Buttons)0xB7, (Buttons)0xB8, (Buttons)0xB9, (Buttons)0xBA, (Buttons)0xBB, (Buttons)0xBC, (Buttons)0xBD, (Buttons)0xBE, (Buttons)0xBF,
(Buttons)0xC0, (Buttons)0xC1, (Buttons)0xC2, (Buttons)0xC3, (Buttons)0xC4, (Buttons)0xC5, (Buttons)0xC6, (Buttons)0xC7, (Buttons)0xC8, (Buttons)0xC9, (Buttons)0xCA, (Buttons)0xCB, (Buttons)0xCC, (Buttons)0xCD, (Buttons)0xCE, (Buttons)0xCF,
(Buttons)0xD0, (Buttons)0xD1, (Buttons)0xD2, (Buttons)0xD3, (Buttons)0xD4, (Buttons)0xD5, (Buttons)0xD6, (Buttons)0xD7, (Buttons)0xD8, (Buttons)0xD9, (Buttons)0xDA, (Buttons)0xDB, (Buttons)0xDC, (Buttons)0xDD, (Buttons)0xDE, (Buttons)0xDF,
(Buttons)0xE0, (Buttons)0xE1, (Buttons)0xE2, (Buttons)0xE3, (Buttons)0xE4, (Buttons)0xE5, (Buttons)0xE6, (Buttons)0xE7, (Buttons)0xE8, (Buttons)0xE9, (Buttons)0xEA, (Buttons)0xEB, (Buttons)0xEC, (Buttons)0xED, (Buttons)0xEE, (Buttons)0xEF,
(Buttons)0xF0, (Buttons)0xF1, (Buttons)0xF2, (Buttons)0xF3, (Buttons)0xF4, (Buttons)0xF5, (Buttons)0xF6, (Buttons)0xF7, (Buttons)0xF8, (Buttons)0xF9, (Buttons)0xFA, (Buttons)0xFB, (Buttons)0xFC, (Buttons)0xFD, (Buttons)0xFE, (Buttons)0xFF
};
WNDCLASSEX windowClass;
POINT clientOffset, nonClientSize;
#define DOUBLE_BUFFER 0
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Hwnd == hwnd; });
if (result == windowInfos.end())
return DefWindowProc(hwnd, msg, wParam, lParam);
WindowInfo& windowInfo = *result;
Window* window = windowInfo.Window;
Surface* surface = windowInfo.Surface;
int captionHeight = 23;
switch (msg)
{
#pragma region Mouse
case WM_MOUSEMOVE:
{
PointerPositionEvent pointerPositionEvent;
pointerPositionEvent.Index = 0;
pointerPositionEvent.X = LOWORD(lParam);
pointerPositionEvent.Y = HIWORD(lParam);
window->OnPointerMove(window, pointerPositionEvent);
break;
}
case WM_RBUTTONDOWN:
{
SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, NULL);
break;
}
case WM_LBUTTONDOWN:
{
PointerEvent pointerEvent;
pointerEvent.Index = 0;
window->OnPointerDown(window, pointerEvent);
break;
}
case WM_RBUTTONUP:
{
break;
}
case WM_LBUTTONUP:
{
PointerEvent pointerEvent;
pointerEvent.Index = 0;
window->OnPointerUp(window, pointerEvent);
break;
}
case WM_MOUSELEAVE:
{
break;
}
case WM_MOUSEWHEEL:
{
PointerScrollEvent pointerScrollEvent;
pointerScrollEvent.Index = 0;
pointerScrollEvent.Delta = -GET_WHEEL_DELTA_WPARAM(wParam) / 120;
window->OnPointerScroll(window, pointerScrollEvent);
break;
}
#pragma endregion
#pragma region Keyboard
case WM_CHAR:
{
if (wParam < 32)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = Buttons::Unknown;
buttonEvent.Character = (char)wParam;
bool pressed = !(lParam >> 31);
if (pressed)
window->OnButtonDown(window, buttonEvent);
else
window->OnButtonUp(window, buttonEvent);
return 0;
}
case WM_KEYDOWN:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
u32 character = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
if (!character || character < 32)
{
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonDown(window, buttonEvent);
}
return 0;
}
case WM_KEYUP:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 'a';
window->OnButtonUp(window, buttonEvent);
return 0;
}
case WM_SYSKEYDOWN:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonDown(window, buttonEvent);
return 0;
}
case WM_SYSKEYUP:
{
Buttons button = virtualKeyMapping[wParam];
if ((WPARAM)button == wParam)
break;
ButtonEvent buttonEvent;
buttonEvent.Button = button;
buttonEvent.Character = 0;
window->OnButtonUp(window, buttonEvent);
return 0;
}
#pragma endregion
#pragma region Window
case WM_CREATE:
{
RECT rect;
rect.left = window->Position.X;
rect.top = window->Position.Y;
rect.right = window->Position.X + window->Size.X;
rect.bottom = window->Position.Y + window->Size.Y;
AdjustWindowRect(&rect, WS_POPUP, false);
SetWindowPos(hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOREPOSITION | SWP_NOMOVE);
BufferedPaintInit();
break;
}
case WM_CLOSE:
{
DestroyWindow(hwnd);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
exit(0); // FIXME
break;
}
case WM_SIZE:
{
s16 width = LOWORD(lParam);
s16 height = HIWORD(lParam);
window->Size = Point2(width, height);
delete surface;
windowInfo.Surface = new Surface(window->Size.X, window->Size.Y);
InvalidateRect(hwnd, NULL, false);
UpdateWindow(hwnd);
break;
}
#pragma endregion
#pragma region Non-client
case WM_NCPAINT:
{
//DWMNCRENDERINGPOLICY policy = DWMNCRP_ENABLED;
//DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, (void*)&policy, sizeof(DWMNCRENDERINGPOLICY));
MARGINS margins = { 1, 1, 1, 1 };
DwmExtendFrameIntoClientArea(hwnd, &margins);
return DefWindowProc(hwnd, msg, wParam, lParam);
}
case WM_NCCALCSIZE:
break;
#pragma endregion
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc, hdcBuffer;
HGDIOBJ oldBitmap;
BITMAP bitmap;
HBITMAP hBitmap;
HPAINTBUFFER hPaintBuffer;
window->Redraw(surface, System::Graphics::Rectangle(Point2::Zero, window->Size));
#if DOUBLE_BUFFER
hdc = GetWindowDC(hwnd);
#else
hdc = BeginPaint(hwnd, &ps);
hdcBuffer = CreateCompatibleDC(hdc);
#endif
RECT rect;
GetClientRect(hwnd, &rect);
#if DOUBLE_BUFFER
hPaintBuffer = BeginBufferedPaint(hdc, &rect, BPBF_COMPATIBLEBITMAP, NULL, &hdcBuffer);
BufferedPaintMakeOpaque(hPaintBuffer, NULL);
#endif
hBitmap = CreateBitmap(window->Size.X, window->Size.Y, 1, 32, surface->Data);
oldBitmap = SelectObject(hdcBuffer, hBitmap);
GetObject(hBitmap, sizeof(bitmap), &bitmap);
BitBlt(hdc, 0, 0, bitmap.bmWidth, bitmap.bmHeight, hdcBuffer, 0, 0, SRCCOPY);
SelectObject(hdcBuffer, oldBitmap);
DeleteObject(hBitmap);
#if DOUBLE_BUFFER
BufferedPaintMakeOpaque(hPaintBuffer, NULL);
EndBufferedPaint(hPaintBuffer, TRUE);
ReleaseDC(hwnd, hdc);
#else
EndPaint(hwnd, &ps);
#endif
break;
}
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
HWND GetHwndByWindow(Window* window)
{
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; });
if (result == windowInfos.end())
return NULL;
return result->Hwnd;
}
void Window_PositionChanged(void* origin, ChangeEventParameter<Point> args)
{
HWND hwnd = GetHwndByWindow((Window*)origin);
SetWindowPos(hwnd, NULL, args.NewValue.X, args.NewValue.Y, 0, 0, SWP_NOREPOSITION | SWP_NOSIZE);
}
void Window_SizeChanged(void* origin, ChangeEventParameter<Point> args)
{
HWND hwnd = GetHwndByWindow((Window*)origin);
SetWindowPos(hwnd, NULL, 0, 0, args.NewValue.X, args.NewValue.Y, SWP_NOREPOSITION | SWP_NOMOVE);
}
void Window_Refreshed(void* origin, System::Graphics::Rectangle rectangle)
{
Window* window = (Window*)origin;
HWND hwnd = GetHwndByWindow(window);
RECT rect = { 0 };
/*rect.left = rectangle.Position.X;
rect.top = rectangle.Position.Y;
rect.right = rectangle.Position.X + rectangle.Size.X;
rect.bottom = rectangle.Position.Y + rectangle.Size.Y;*/
rect.left = 0;
rect.top = 0;
rect.right = window->Size.X;
rect.bottom = window->Size.Y;
InvalidateRect(hwnd, &rect, true);
}
DWORD WINAPI WindowsManager_Loop(LPVOID parameter)
{
MSG msg;
for (;;)
{
// Handle window creation requests
while (!pendingWindowInfos.empty())
{
PendingWindowInfo pendingWindow = pendingWindowInfos.front();
pendingWindowInfos.pop();
// Create the Window
Window* window = pendingWindow.Window;
HWND hwnd = CreateWindow("myWindowClass", "", WS_OVERLAPPEDWINDOW, window->Position.X, window->Position.Y, window->Size.X, window->Size.Y, NULL, NULL, NULL, NULL);
Surface* surface = new Surface(window->Size.X, window->Size.Y);
// Register to window events
window->PositionChanged += Window_PositionChanged;
window->SizeChanged += Window_SizeChanged;
window->Refreshed += Window_Refreshed;
//window->Initialize();
// Adjust the newly created window
/*RECT rect;
rect.left = window->Position.X;
rect.top = window->Position.Y;
rect.right = window->Position.X + window->Size.X;
rect.bottom = window->Position.Y + window->Size.Y;
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, false);*/
// Register the new window
WindowInfo windowInfo;
windowInfo.Window = window;
windowInfo.Surface = surface;
windowInfo.Hwnd = hwnd;
windowInfos.push_back(windowInfo);
// Show window
SetWindowPos(hwnd, NULL, 0, 0, window->Size.X + nonClientSize.x, window->Size.Y + nonClientSize.y, SWP_NOREPOSITION | SWP_NOMOVE);
ShowWindow(hwnd, SW_SHOW);
// Force first draw
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
}
// Handle messages
if (!windowInfos.empty())
{
for (int i = 0; i < 1024; i++)
{
if (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
}
return 0;
}
void WindowsManager::Initialize()
{
// Compute non client sizes
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = 0;
rect.bottom = 0;
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, false);
clientOffset.x = -rect.left;
clientOffset.y = -rect.top;
nonClientSize.x = rect.right - rect.left;
nonClientSize.y = rect.bottom - rect.top;
// Register a new window class
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = 0;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.hbrBackground = NULL; // (HBRUSH)(COLOR_WINDOW + 1);
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = "myWindowClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&windowClass))
Exception::Assert("Could not register window class");
// Start the window loop thread
DWORD threadId;
HANDLE threadHandle = CreateThread(NULL, 0, WindowsManager_Loop, NULL, 0, &threadId);
}
void WindowsManager::Add(Window* window)
{
int index = 0;
// Check for existing window
if (find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; }) != windowInfos.end())
return;
// Push a new window creation request
PendingWindowInfo pendingWindow;
pendingWindow.Window = window;
pendingWindowInfos.push(pendingWindow);
// Wait for window creation
for (;;)
{
Sleep(20);
auto result = find_if(windowInfos.begin(), windowInfos.end(), [=](WindowInfo w) { return w.Window == window; });
if (result != windowInfos.end())
return;
}
}
void WindowsManager::Remove(Window* window)
{
HWND hwnd = GetHwndByWindow(window);
DestroyWindow(hwnd);
window->Closed(window, null);
}
void Mover::OnPointerMove(void* origin, PointerPositionEvent pointerPositionEvent)
{
}
void Mover::OnPointerIn(void* origin, PointerEvent pointerEvent)
{
}
void Mover::OnPointerOut(void* origin, PointerEvent pointerEvent)
{
}
void Mover::OnPointerDown(void* origin, PointerEvent pointerEvent)
{
HWND hwnd = GetHwndByWindow(window);
SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, NULL);
}
void Mover::OnPointerUp(void* origin, PointerEvent pointerEvent)
{
}
#endif | 33.06367 | 269 | 0.617864 |
cfbaa3403fe6083a83b359001d88539239ef0d88 | 769 | cpp | C++ | WumbukDraw/line.cpp | YangPeihao1203/WumbukDraw | e0854e62cc050c99deda04a849d46824f458cbbc | [
"MIT"
] | null | null | null | WumbukDraw/line.cpp | YangPeihao1203/WumbukDraw | e0854e62cc050c99deda04a849d46824f458cbbc | [
"MIT"
] | null | null | null | WumbukDraw/line.cpp | YangPeihao1203/WumbukDraw | e0854e62cc050c99deda04a849d46824f458cbbc | [
"MIT"
] | null | null | null | #include "line.h"
Line::Line()
{
setAdjustFlag(false);
}
void Line::startDraw(QGraphicsSceneMouseEvent * event)
{
QPen pen = this->pen();
pen.setWidth(this->width);
pen.setColor(this->color);
setPen(pen);
startPos=event->scenePos();
}
void Line::drawing(QGraphicsSceneMouseEvent * event)
{
EndPos=event->scenePos();
QLineF newLine(startPos,EndPos);
setLine(newLine);
}
void Line::endDraw(QGraphicsSceneMouseEvent *event)
{
}
bool Line::CheckIsContainsPoint(QPointF p)
{
return shape().contains(p);
}
void Line::setAdjustFlag(bool val)
{
setFlag(QGraphicsItem::ItemIsMovable, val);
setFlag(QGraphicsItem::ItemIsSelectable, val);
setFlag(QGraphicsItem::ItemIsFocusable, val);
}
| 18.756098 | 55 | 0.6671 |
cfbc414efa03b4d00846bddacc360efa3e6b71df | 16,075 | cpp | C++ | diffsim_torch3d/arcsim/src/simulation.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/simulation.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/simulation.cpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "simulation.hpp"
#include "collision.hpp"
#include "dynamicremesh.hpp"
#include "geometry.hpp"
#include "magic.hpp"
#include "nearobs.hpp"
#include "physics.hpp"
#include "plasticity.hpp"
#include "popfilter.hpp"
#include "proximity.hpp"
#include "separate.hpp"
#include "obstacle.hpp"
#include <iostream>
#include <fstream>
using namespace std;
using torch::Tensor;
static const bool verbose = false;
static const int proximity = Simulation::Proximity,
physics = Simulation::Physics,
strainlimiting = Simulation::StrainLimiting,
collision = Simulation::Collision,
remeshing = Simulation::Remeshing,
separation = Simulation::Separation,
popfilter = Simulation::PopFilter,
plasticity = Simulation::Plasticity;
void physics_step (Simulation &sim, const vector<Constraint*> &cons);
void plasticity_step (Simulation &sim);
void strainlimiting_step (Simulation &sim, const vector<Constraint*> &cons);
void strainzeroing_step (Simulation &sim);
void equilibration_step (Simulation &sim);
void collision_step (Simulation &sim);
void remeshing_step (Simulation &sim, bool initializing=false);
void validate_handles (const Simulation &sim);
void prepare (Simulation &sim) {
sim.step = 0;
sim.frame = 0;
sim.cloth_meshes.resize(sim.cloths.size());
for (int c = 0; c < sim.cloths.size(); c++) {
compute_masses(sim.cloths[c]);
sim.cloth_meshes[c] = &sim.cloths[c].mesh;
update_x0(*sim.cloth_meshes[c]);
}
sim.obstacle_meshes.resize(sim.obstacles.size());
for (int o = 0; o < sim.obstacles.size(); o++) {
obs_compute_masses(sim.obstacles[o]);
sim.obstacle_meshes[o] = &sim.obstacles[o].get_mesh();
update_x0(*sim.obstacle_meshes[o]);
}
}
void relax_initial_state (Simulation &sim) {
validate_handles(sim);
return;
if (::magic.preserve_creases)
for (int c = 0; c < sim.cloths.size(); c++)
reset_plasticity(sim.cloths[c]);
bool equilibrate = true;
if (equilibrate) {
equilibration_step(sim);
remeshing_step(sim, true);
equilibration_step(sim);
} else {
remeshing_step(sim, true);
strainzeroing_step(sim);
remeshing_step(sim, true);
strainzeroing_step(sim);
}
if (::magic.preserve_creases)
for (int c = 0; c < sim.cloths.size(); c++)
reset_plasticity(sim.cloths[c]);
::magic.preserve_creases = false;
if (::magic.fixed_high_res_mesh)
sim.enabled[remeshing] = false;
}
void validate_handles (const Simulation &sim) {
for (int h = 0; h < sim.handles.size(); h++) {
vector<Node*> nodes = sim.handles[h]->get_nodes();
for (int n = 0; n < nodes.size(); n++) {
if (!nodes[n]->preserve) {
cout << "Constrained node " << nodes[n]->index << " will not be preserved by remeshing" << endl;
abort();
}
}
}
}
vector<Constraint*> get_constraints (Simulation &sim, bool include_proximity);
void delete_constraints (const vector<Constraint*> &cons);
void update_obstacles (Simulation &sim, bool update_positions=true);
void advance_step (Simulation &sim);
void advance_frame (Simulation &sim) {
for (int s = 0; s < sim.frame_steps; s++)
advance_step(sim);
}
void advance_step (Simulation &sim) {
Timer ti;
ti.tick();
sim.time = sim.time + sim.step_time;
sim.step++;
// cout << "\t\tstep=" << sim.step << endl;
update_obstacles(sim, false);
vector<Constraint*> cons = get_constraints(sim, true);
physics_step(sim, cons);
//plasticity_step(sim);
//strainlimiting_step(sim, cons);
collision_step(sim);
if (sim.step % sim.frame_steps == 0) {
remeshing_step(sim);
sim.frame++;
// cout << "\t\t\tframe="<<sim.frame<<endl;
}
delete_constraints(cons);
ti.tock();
// cout << "\t\ttime= "<< ti.last << endl;
}
vector<Constraint*> get_constraints (Simulation &sim, bool include_proximity) {
// cout << "get_constraints" << endl;
vector<Constraint*> cons;
for (int h = 0; h < sim.handles.size(); h++)
append(cons, sim.handles[h]->get_constraints(sim.time));
// PRIYA
if (include_proximity && sim.enabled[proximity]) {
sim.timers[proximity].tick();
append(cons, proximity_constraints(sim.cloth_meshes,
sim.obstacle_meshes,
sim.friction, sim.obs_friction));
sim.timers[proximity].tock();
}
return cons;
}
void delete_constraints (const vector<Constraint*> &cons) {
for (int c = 0; c < cons.size(); c++)
delete cons[c];
}
// Steps
void update_velocities (vector<Mesh*> &meshes, vector<Tensor> &xold, Tensor dt);
void step_mesh (Mesh &mesh, Tensor dt);
void step_obstacle (Obstacle &obstacle, Tensor dt);
void physics_step (Simulation &sim, const vector<Constraint*> &cons) {
// cout << "physics_step" << endl;
if (!sim.enabled[physics])
return;
sim.timers[physics].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
int nn = sim.cloths[c].mesh.nodes.size();
Tensor fext = torch::zeros({nn,3}, TNOPT)*0;
Tensor Jext = torch::zeros({nn,3,3}, TNOPT);
add_external_forces(sim.cloths[c], sim.gravity, sim.wind, fext, Jext);
for (int m = 0; m < sim.morphs.size(); m++)
if (sim.morphs[m].mesh == &sim.cloths[c].mesh)
add_morph_forces(sim.cloths[c], sim.morphs[m], sim.time,
sim.step_time, fext, Jext);
implicit_update(sim.cloths[c], fext, Jext, cons, sim.step_time, false);
}
for (int o = 0; o < sim.obstacles.size(); o++) {
int nn = 2;
Tensor fext = torch::zeros({nn,3}, TNOPT);
Tensor Jext = torch::zeros({nn,3,3}, TNOPT);
// just for test
obs_add_external_forces(sim.obstacles[o], sim.gravity, sim.wind, fext, Jext);
//fext = fext;
//cout << "obs fext = " << fext << endl;
obs_implicit_update(sim.obstacles[o], sim.obstacle_meshes, fext, Jext, cons, sim.step_time, false);
}
for (int c = 0; c < sim.cloth_meshes.size(); c++)
step_mesh(*sim.cloth_meshes[c], sim.step_time);
//for (int o = 0; o < sim.obstacle_meshes.size(); o++)
// step_mesh(*sim.obstacle_meshes[o], sim.step_time);
for (int o = 0; o < sim.obstacles.size(); o++)
step_obstacle(sim.obstacles[o], sim.step_time);
sim.timers[physics].tock();
}
void step_mesh (Mesh &mesh, Tensor dt) {
for (int n = 0; n < mesh.nodes.size(); n++) {
mesh.nodes[n]->x = mesh.nodes[n]->x + mesh.nodes[n]->v*dt;
mesh.nodes[n]->xold = mesh.nodes[n]->x;
}
}
// void apply_transformation (Mesh& mesh, const Transformation& tr) {
// apply_transformation_onto(mesh, mesh, tr);
//}
void step_obstacle (Obstacle &obstacle, Tensor dt) {
Node *dummy_node = obstacle.curr_state_mesh.dummy_node;
//cout << "velocity -------------" << endl;
////cout << dummy_node->x0 ;
//cout << dummy_node->x ;
if (dummy_node->movable)
dummy_node->x = dummy_node->v * dt + dummy_node->x;
dummy_node->xold = dummy_node->x;
//cout << dummy_node->x0 ;
Tensor euler = dummy_node->x.slice(0, 0, 3);
Tensor trans = dummy_node->x.slice(0, 3, 6);
Transformation tr;
tr.rotation = Quaternion::from_euler(euler);
tr.translation = trans;
tr.scale = dummy_node->scale;
//cout << tr.rotation << endl;
//cout << tr.translation << endl;
//cout << tr.scale << endl;
//cout << "step_obstacle" << endl;
apply_transformation_onto(obstacle.base_mesh, obstacle.curr_state_mesh, tr);
Mesh &mesh = obstacle.curr_state_mesh;
for (int n = 0; n < mesh.nodes.size(); n++) {
mesh.nodes[n]->xold = mesh.nodes[n]->x;
}
}
void plasticity_step (Simulation &sim) {
if (!sim.enabled[plasticity])
return;
// cout << "plasticity_step" << endl;
sim.timers[plasticity].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
plastic_update(sim.cloths[c]);
optimize_plastic_embedding(sim.cloths[c]);
}
sim.timers[plasticity].tock();
}
void strainlimiting_step (Simulation &sim, const vector<Constraint*> &cons) {
// cout << "strainlimiting_step" << endl;
}
void equilibration_step (Simulation &sim) {
sim.timers[remeshing].tick();
vector<Constraint*> cons;// = get_constraints(sim, true);
// double stiff = 1;
// swap(stiff, ::magic.handle_stiffness);
for (int c = 0; c < sim.cloths.size(); c++) {
Mesh &mesh = sim.cloths[c].mesh;
for (int n = 0; n < mesh.nodes.size(); n++)
mesh.nodes[n]->acceleration = ZERO3;
apply_pop_filter(sim.cloths[c], cons, 1);
}
// swap(stiff, ::magic.handle_stiffness);
sim.timers[remeshing].tock();
delete_constraints(cons);
cons = get_constraints(sim, false);
if (sim.enabled[collision]) {
sim.timers[collision].tick();
collision_response(sim, sim.cloth_meshes, cons, sim.obstacle_meshes);
sim.timers[collision].tock();
}
delete_constraints(cons);
}
void strainzeroing_step (Simulation &sim) {
}
void collision_step (Simulation &sim) {
if (!sim.enabled[collision])
return;
// cout << "collision_step" << endl;
sim.timers[collision].tick();
vector<Tensor> xold = node_positions(sim.cloth_meshes);
vector<Constraint*> cons = get_constraints(sim, false);
collision_response(sim, sim.cloth_meshes, cons, sim.obstacle_meshes);
delete_constraints(cons);
update_velocities(sim.cloth_meshes, xold, sim.step_time);
sim.timers[collision].tock();
}
void remeshing_step (Simulation &sim, bool initializing) {
if (!sim.enabled[remeshing])
return;
// copy old meshes
vector<Mesh> old_meshes(sim.cloths.size());
vector<Mesh*> old_meshes_p(sim.cloths.size()); // for symmetry in separate()
for (int c = 0; c < sim.cloths.size(); c++) {
old_meshes[c] = deep_copy(sim.cloths[c].mesh);
old_meshes_p[c] = &old_meshes[c];
}
// back up residuals
typedef vector<Residual> MeshResidual;
vector<MeshResidual> res;
if (sim.enabled[plasticity] && !initializing) {
sim.timers[plasticity].tick();
res.resize(sim.cloths.size());
for (int c = 0; c < sim.cloths.size(); c++)
res[c] = back_up_residuals(sim.cloths[c].mesh);
sim.timers[plasticity].tock();
}
// remesh
sim.timers[remeshing].tick();
for (int c = 0; c < sim.cloths.size(); c++) {
if (::magic.fixed_high_res_mesh)
static_remesh(sim.cloths[c]);
else {
vector<Plane> planes = nearest_obstacle_planes(sim.cloths[c].mesh,
sim.obstacle_meshes);
dynamic_remesh(sim.cloths[c], planes, sim.enabled[plasticity]);
}
}
sim.timers[remeshing].tock();
// restore residuals
if (sim.enabled[plasticity] && !initializing) {
sim.timers[plasticity].tick();
for (int c = 0; c < sim.cloths.size(); c++)
restore_residuals(sim.cloths[c].mesh, old_meshes[c], res[c]);
sim.timers[plasticity].tock();
}
// separate
if (sim.enabled[separation]) {
sim.timers[separation].tick();
separate(sim.cloth_meshes, old_meshes_p, sim.obstacle_meshes);
sim.timers[separation].tock();
}
// apply pop filter
if (sim.enabled[popfilter] && !initializing) {
sim.timers[popfilter].tick();
vector<Constraint*> cons = get_constraints(sim, true);
for (int c = 0; c < sim.cloths.size(); c++)
apply_pop_filter(sim.cloths[c], cons);
delete_constraints(cons);
sim.timers[popfilter].tock();
}
// delete old meshes
for (int c = 0; c < sim.cloths.size(); c++)
delete_mesh(old_meshes[c]);
}
void update_velocities (vector<Mesh*> &meshes, vector<Tensor> &xold, Tensor dt) {
Tensor inv_dt = 1/dt;
#pragma omp parallel for
for (int n = 0; n < xold.size(); n++) {
Node *node = get<Node>(n, meshes);
node->v = node->v + (node->x - xold[n])*inv_dt;
}
}
void update_obstacles (Simulation &sim, bool update_positions) {
// cout << "update_obstacles" << endl;
for (int o = 0; o < sim.obstacles.size(); o++) {
sim.obstacles[o].get_mesh(sim.time);
// sim.obstacles[o].blend_with_previous(sim.time, sim.step_time, blend);
if (!update_positions) {
// put positions back where they were
Mesh &mesh = sim.obstacles[o].get_mesh();
for (int n = 0; n < mesh.nodes.size(); n++) {
Node *node = mesh.nodes[n];
node->v = (node->x - node->x0)/sim.step_time;
node->x = node->x0;
}
}
}
}
// Helper functions
template <typename Prim> int size (const vector<Mesh*> &meshes) {
int np = 0;
for (int m = 0; m < meshes.size(); m++) np += get<Prim>(*meshes[m]).size();
return np;
}
template int size<Vert> (const vector<Mesh*>&);
template int size<Node> (const vector<Mesh*>&);
template int size<Edge> (const vector<Mesh*>&);
template int size<Face> (const vector<Mesh*>&);
template <typename Prim> int get_index (const Prim *p,
const vector<Mesh*> &meshes) {
int i = 0;
for (int m = 0; m < meshes.size(); m++) {
const vector<Prim*> &ps = get<Prim>(*meshes[m]);
if (p->index < ps.size() && p == ps[p->index])
return i + p->index;
else i += ps.size();
}
return -1;
}
template int get_index (const Vert*, const vector<Mesh*>&);
template int get_index (const Node*, const vector<Mesh*>&);
template int get_index (const Edge*, const vector<Mesh*>&);
template int get_index (const Face*, const vector<Mesh*>&);
template <typename Prim> Prim *get (int i, const vector<Mesh*> &meshes) {
for (int m = 0; m < meshes.size(); m++) {
const vector<Prim*> &ps = get<Prim>(*meshes[m]);
if (i < ps.size())
return ps[i];
else
i -= ps.size();
}
return NULL;
}
template Vert *get (int, const vector<Mesh*>&);
template Node *get (int, const vector<Mesh*>&);
template Edge *get (int, const vector<Mesh*>&);
template Face *get (int, const vector<Mesh*>&);
vector<Tensor> node_positions (const vector<Mesh*> &meshes) {
vector<Tensor> xs(size<Node>(meshes));
for (int n = 0; n < xs.size(); n++)
xs[n] = get<Node>(n, meshes)->x;
return xs;
}
| 34.869848 | 112 | 0.612877 |
cfbc9166cf99ff55eb9d15aacb24a713551f7d21 | 2,707 | hpp | C++ | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | RubetekIOS-CPP.framework/Versions/A/Headers/libnet/dawn/queue_blocks.hpp | yklishevich/RubetekIOS-CPP-releases | 7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb | [
"MIT"
] | null | null | null | #pragma once
#include <queue>
#include <msw/buffer.hpp>
namespace dawn
{
struct queue_blocks
{
typedef msw::range<msw::byte> block ;
typedef msw::range<msw::byte const> const_block ;
queue_blocks () ;
queue_blocks (queue_blocks&&) ;
bool empty () const ;
bool has_blocks () const ;
std::size_t count () const ;
msw::size<msw::byte> size () const ;
block front () ;
const_block front () const ;
block back () ;
const_block back () const ;
void push (const_block) ;
void pop () ;
msw::buffer<msw::byte> pull () ;
private:
std::queue<msw::buffer<msw::byte>> blocks_ ;
msw::size<msw::byte> size_ ;
};
}
namespace dawn
{
inline queue_blocks::queue_blocks()
{}
inline queue_blocks::queue_blocks(queue_blocks&& other)
: blocks_ (std::move(other.blocks_))
, size_ (std::move(other.size_ ))
{}
inline bool queue_blocks::empty() const
{
return blocks_.empty();
}
inline bool queue_blocks::has_blocks() const
{
return !empty();
}
inline std::size_t queue_blocks::count() const
{
return blocks_.size();
}
inline msw::size<msw::byte> queue_blocks::size() const
{
return size_;
}
inline queue_blocks::block queue_blocks::front()
{
return blocks_.front().all();
}
inline queue_blocks::const_block queue_blocks::front() const
{
return blocks_.front().all();
}
inline queue_blocks::block queue_blocks::back()
{
return blocks_.back().all();
}
inline queue_blocks::const_block queue_blocks::back() const
{
return blocks_.back().all();
}
inline void queue_blocks::push(const_block blk)
{
blocks_.emplace(blk);
size_ += blk.size();
}
inline void queue_blocks::pop()
{
size_ -= front().size();
blocks_.pop();
}
inline msw::buffer<msw::byte> queue_blocks::pull()
{
size_ -= front().size();
msw::buffer<msw::byte> blk = std::move(blocks_.front());
blocks_.pop();
return std::move(blk);
}
}
| 27.07 | 67 | 0.461396 |
cfbe411ee255d884970fca91398de8142dd8ec8c | 7,250 | hpp | C++ | math/rotation.hpp | melowntech/libmath | 7a473801a93ba5e244d96e773b412a3abed4a400 | [
"BSD-2-Clause"
] | 1 | 2021-09-02T08:42:59.000Z | 2021-09-02T08:42:59.000Z | externals/browser/externals/browser/externals/libmath/math/rotation.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 2 | 2020-06-09T12:06:16.000Z | 2021-10-06T08:15:04.000Z | externals/browser/externals/browser/externals/libmath/math/rotation.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2019-09-25T05:20:17.000Z | 2019-09-25T05:20:17.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file rotation.hpp
* @author Jakub Cerveny <jakub.cerveny@ext.citationtech.net>
*
* Math related to rotations.
*/
#ifndef MATH_ROTATION_HPP
#define MATH_ROTATION_HPP
#include "geometry_core.hpp"
namespace math {
/** Converts a rotation vector (see below) to a rotation matrix.
*/
inline Matrix4 rotationMatrix(const Point3 & rvec)
{
Matrix4 m( ublas::identity_matrix<double>(4) );
double angle = ublas::norm_2(rvec);
if (std::abs(angle) < 1e-10) { return m; }
Point3 vec(rvec * (1.0 / angle));
double s = sin(angle),
c = cos(angle);
double xx = vec(0) * vec(0),
yy = vec(1) * vec(1),
zz = vec(2) * vec(2),
xy = vec(0) * vec(1),
yz = vec(1) * vec(2),
zx = vec(2) * vec(0);
double xs = vec(0) * s,
ys = vec(1) * s,
zs = vec(2) * s;
double one_c = 1.0 - c;
m(0, 0) = (one_c * xx) + c;
m(0, 1) = (one_c * xy) - zs;
m(0, 2) = (one_c * zx) + ys;
m(1, 0) = (one_c * xy) + zs;
m(1, 1) = (one_c * yy) + c;
m(1, 2) = (one_c * yz) - xs;
m(2, 0) = (one_c * zx) - ys;
m(2, 1) = (one_c * yz) + xs;
m(2, 2) = (one_c * zz) + c;
return m;
}
/** Converts a rotation matrix to a rotation vector, whose direction represents
* the axis of rotation and its magnitude represents the angle of rotation
* in radians.
*/
inline Point3 rotationVector(const Matrix4 & mat)
{
double angle = acos(0.5 * (mat(0,0) + mat(1,1) + mat(2,2) - 1.0));
Point3 axis(mat(2,1) - mat(1,2),
mat(0,2) - mat(2,0),
mat(1,0) - mat(0,1));
return angle / (2*sin(angle)) * axis;
}
/** Quaternion -- represents a rotation.
*/
class Quaternion
{
public:
Quaternion()
: x(0.0), y(0.0), z(0.0), w(1.0) {}
Quaternion(double x, double y, double z, double w)
: x(x), y(y), z(z), w(w) {}
Quaternion(const Quaternion& q)
{ x = q.x; y = q.y; z = q.z; w = q.w; }
Quaternion& operator=(const Quaternion& q)
{ x = q.x; y = q.y; z = q.z; w = q.w; return *this; }
Quaternion(const Matrix4& mat)
{ fromMatrix(mat); }
/// Converts a matrix to a quaternion.
void fromMatrix(const Matrix4& m);
/// Converts this quaternion to a matrix.
Matrix4 toMatrix() const;
Quaternion& normalize();
Quaternion operator+(const Quaternion& other) const;
Quaternion operator*(const Quaternion& other) const;
Quaternion operator*(double scalar) const;
Quaternion& operator*=(double scalar);
Quaternion& operator*=(const Quaternion& other);
double x, y, z; // imaginary part
double w; // real part
};
inline Quaternion Quaternion::operator*(double s) const
{
return Quaternion(s*x, s*y, s*z, s*w);
}
inline Quaternion& Quaternion::operator*=(double s)
{
x*=s; y*=s; z*=s; w*=s;
return *this;
}
inline Quaternion& Quaternion::operator*=(const Quaternion& other)
{
return (*this = other * (*this));
}
inline Quaternion Quaternion::operator+(const Quaternion& b) const
{
return Quaternion(x+b.x, y+b.y, z+b.z, w+b.w);
}
inline Quaternion Quaternion::operator*(const Quaternion& other) const
{
Quaternion tmp;
tmp.w = (other.w * w) - (other.x * x) - (other.y * y) - (other.z * z);
tmp.x = (other.w * x) + (other.x * w) + (other.y * z) - (other.z * y);
tmp.y = (other.w * y) + (other.y * w) + (other.z * x) - (other.x * z);
tmp.z = (other.w * z) + (other.z * w) + (other.x * y) - (other.y * x);
return tmp;
}
inline void Quaternion::fromMatrix(const Matrix4& m)
{
const double diag = m(0,0) + m(1,1) + m(2,2) + 1;
if (diag > 0.0)
{
const double scale = sqrt(diag) * 2.0; // get scale from diagonal
x = (m(2,1) - m(1,2)) / scale;
y = (m(0,2) - m(2,0)) / scale;
z = (m(1,0) - m(0,1)) / scale;
w = 0.25 * scale;
}
else
{
if (m(0,0) > m(1,1) && m(0,0) > m(2,2))
{
// 1st element of diag is greatest value
// find scale according to 1st element, and double it
const double scale = sqrt( 1.0 + m(0,0) - m(1,1) - m(2,2)) * 2.0;
x = 0.25 * scale;
y = (m(0,1) + m(1,0)) / scale;
z = (m(2,0) + m(0,2)) / scale;
w = (m(2,1) - m(1,2)) / scale;
}
else if (m(1,1) > m(2,2))
{
// 2nd element of diag is greatest value
// find scale according to 2nd element, and double it
const double scale = sqrt( 1.0 + m(1,1) - m(0,0) - m(2,2)) * 2.0;
x = (m(0,1) + m(1,0) ) / scale;
y = 0.25 * scale;
z = (m(1,2) + m(2,1) ) / scale;
w = (m(0,2) - m(2,0) ) / scale;
}
else
{
// 3rd element of diag is greatest value
// find scale according to 3rd element, and double it
const double scale = sqrt( 1.0 + m(2,2) - m(0,0) - m(1,1)) * 2.0;
x = (m(0,2) + m(2,0)) / scale;
y = (m(1,2) + m(2,1)) / scale;
z = 0.25 * scale;
w = (m(1,0) - m(0,1)) / scale;
}
}
normalize();
}
inline Quaternion& Quaternion::normalize()
{
double n = x*x + y*y + z*z + w*w;
*this *= 1.0 / sqrt(n);
return *this;
}
inline Matrix4 Quaternion::toMatrix() const
{
Matrix4 m = ublas::identity_matrix<double>(4);
m(0,0) = 1.0 - 2.0*y*y - 2.0*z*z;
m(1,0) = 2.0*x*y + 2.0*z*w;
m(2,0) = 2.0*x*z - 2.0*y*w;
m(3,0) = 0.0;
m(0,1) = 2.0*x*y - 2.0*z*w;
m(1,1) = 1.0 - 2.0*x*x - 2.0*z*z;
m(2,1) = 2.0*z*y + 2.0*x*w;
m(3,1) = 0.0;
m(0,2) = 2.0*x*z + 2.0*y*w;
m(1,2) = 2.0*z*y - 2.0*x*w;
m(2,2) = 1.0 - 2.0*x*x - 2.0*y*y;
m(3,2) = 0.0;
m(0,3) = 0.0;
m(1,3) = 0.0;
m(2,3) = 0.0;
m(3,3) = 1.0;
return m;
}
} // namespace math
#endif
| 27.358491 | 79 | 0.549379 |
cfbf77748654b7c729a4e77abbb95f491baf1e66 | 1,934 | cpp | C++ | Scratch Pencil Photo/Main.cpp | bayudwiyansatria/computer-vision | 1cfe27441b0c92ac23195ed3c574daef1677d18a | [
"MIT"
] | 1 | 2019-05-27T17:54:32.000Z | 2019-05-27T17:54:32.000Z | Scratch Pencil Photo/Main.cpp | bayudwiyansatria/computer-vision | 1cfe27441b0c92ac23195ed3c574daef1677d18a | [
"MIT"
] | null | null | null | Scratch Pencil Photo/Main.cpp | bayudwiyansatria/computer-vision | 1cfe27441b0c92ac23195ed3c574daef1677d18a | [
"MIT"
] | 1 | 2018-11-02T02:29:03.000Z | 2018-11-02T02:29:03.000Z | #include <opencv/cv.h>
#include <opencv/highgui.h>
int main(int argc, char** argv)
{
int col_1, row_1;
uchar b_1, g_1, r_1, b_2, g_2, r_2, b_d, g_d, r_d;
IplImage* img = cvLoadImage("Theory/Scratch Pencil Photo/Input/lena.jpg");
IplImage* img1 = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* img2 = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* dst = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels);
IplImage* gray = cvCreateImage(cvGetSize(img), img->depth, 1);
cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);
cvNamedWindow("Output", CV_WINDOW_AUTOSIZE);
cvShowImage("Input", img);
cvNot(img, img1);
// cvSmooth(img1, img2, CV_BLUR, 25,25,0,0);
cvSmooth(img, img2, CV_GAUSSIAN, 7, 7, 0, 0);
for (row_1 = 0; row_1 < img1->height; row_1++)
{
for (col_1 = 0; col_1 < img1->width; col_1++)
{
b_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3);
g_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3 + 1);
r_1 = CV_IMAGE_ELEM(img1, uchar, row_1, col_1 * 3 + 2);
b_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3);
g_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3 + 1);
r_2 = CV_IMAGE_ELEM(img2, uchar, row_1, col_1 * 3 + 2);
// b_d = b_1 + b_2;
// g_d = g_1 + g_2;
// r_d = r_1 + r_2;
b_d = std::min(255, b_1 + b_2);
g_d = std::min(255, g_1 + g_2);
r_d = std::min(255, r_1 + r_2);
dst->imageData[img1->widthStep * row_1 + col_1 * 3] = b_d;
dst->imageData[img1->widthStep * row_1 + col_1 * 3 + 1] = g_d;
dst->imageData[img1->widthStep * row_1 + col_1 * 3 + 2] = r_d;
}
}
cvCvtColor(dst, gray, CV_BGR2GRAY);
cvShowImage("Output", gray);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&img1);
cvReleaseImage(&img2);
cvReleaseImage(&dst);
cvReleaseImage(&gray);
cvDestroyWindow("Input");
cvDestroyWindow("Output");
} | 32.233333 | 93 | 0.640641 |
cfc100bde1c5aae9d74ba6d1e7071f3bd1096362 | 3,215 | cpp | C++ | src/common/timer/timer_1ms.cpp | caozhiyi/quicX | 46b486fc7786faf479b60c24da8ebdec783b3d5b | [
"BSD-3-Clause"
] | 1 | 2021-11-02T14:31:12.000Z | 2021-11-02T14:31:12.000Z | src/common/timer/timer_1ms.cpp | caozhiyi/quicX | 46b486fc7786faf479b60c24da8ebdec783b3d5b | [
"BSD-3-Clause"
] | null | null | null | src/common/timer/timer_1ms.cpp | caozhiyi/quicX | 46b486fc7786faf479b60c24da8ebdec783b3d5b | [
"BSD-3-Clause"
] | 1 | 2021-09-30T08:23:58.000Z | 2021-09-30T08:23:58.000Z | // Use of this source code is governed by a BSD 3-Clause License
// that can be found in the LICENSE file.
// Author: caozhiyi (caozhiyi5@gmail.com)
#include "timer_1ms.h"
namespace quicx {
static const TIMER_CAPACITY __timer_accuracy = TC_1MS; // 1 millisecond
static const TIMER_CAPACITY __timer_capacity = TC_50MS; // 50 millisecond
Timer1ms::Timer1ms() : _cur_index(0) {
_timer_wheel.resize(__timer_capacity);
_bitmap.Init(__timer_capacity);
}
Timer1ms::~Timer1ms() {
}
bool Timer1ms::AddTimer(std::weak_ptr<TimerSolt> t, uint32_t time, bool always) {
if (time >= __timer_capacity) {
return false;
}
auto ptr = t.lock();
if (!ptr) {
return false;
}
if (ptr->IsInTimer()) {
return true;
}
if (always) {
ptr->SetAlways(__timer_accuracy);
}
ptr->SetInterval(time);
time += _cur_index;
if (time > __timer_capacity) {
time %= __timer_capacity;
}
ptr->SetIndex(time);
ptr->SetTimer();
_timer_wheel[time].push_back(t);
return _bitmap.Insert(time);
}
bool Timer1ms::RmTimer(std::weak_ptr<TimerSolt> t) {
auto ptr = t.lock();
if (!ptr) {
return false;
}
auto index = ptr->GetIndex(__timer_accuracy);
bool ret = _bitmap.Remove(index);
ptr->RmTimer();
return ret;
}
int32_t Timer1ms::CurrentTimer() {
return _cur_index;
}
int32_t Timer1ms::MinTime() {
if (_bitmap.Empty()) {
return NO_TIMER;
}
int32_t next_setp = _bitmap.GetMinAfter(_cur_index);
if (next_setp >= 0) {
return next_setp - _cur_index;
}
if (_cur_index > 0) {
next_setp = _bitmap.GetMinAfter(0);
}
if (next_setp >= 0) {
return next_setp + __timer_capacity - _cur_index;
}
return NO_TIMER;
}
uint32_t Timer1ms::TimerRun(uint32_t time) {
time = time % __timer_capacity;
_cur_index += time;
uint32_t ret = 0;
if (_cur_index >= __timer_capacity) {
_cur_index %= __timer_capacity;
ret++;
}
auto& bucket = _timer_wheel[_cur_index];
if (bucket.size() > 0) {
for (auto iter = bucket.begin(); iter != bucket.end();) {
auto ptr = (iter)->lock();
if (ptr && ptr->IsInTimer()) {
ptr->OnTimer();
}
// remove from current bucket
iter = bucket.erase(iter);
_bitmap.Remove(ptr->GetIndex(__timer_accuracy));
if (!ptr->IsAlways(__timer_accuracy) || !ptr->IsInTimer()) {
ptr->RmTimer();
continue;
} else {
// add to timer again
uint16_t next_index = ptr->GetInterval() + _cur_index;
if (next_index >= __timer_capacity) {
next_index = next_index % __timer_capacity;
}
AddTimerByIndex(ptr, uint8_t(next_index));
}
}
}
return ret;
}
void Timer1ms::AddTimerByIndex(std::weak_ptr<TimerSolt> t, uint8_t index) {
auto ptr = t.lock();
if (!ptr) {
return;
}
ptr->SetIndex(index, TC_1MS);
_timer_wheel[index].push_back(t);
_bitmap.Insert(index);
}
} | 22.640845 | 81 | 0.576361 |
cfc56aecda2a23487b740604cb490928ac2a12b8 | 1,893 | cpp | C++ | src/v3/action_constants.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 139 | 2016-09-20T00:28:04.000Z | 2020-09-27T15:05:11.000Z | src/v3/action_constants.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 85 | 2020-09-29T16:33:00.000Z | 2022-03-30T01:23:23.000Z | src/v3/action_constants.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 63 | 2016-12-06T11:42:29.000Z | 2020-09-24T06:15:49.000Z | #include "etcd/v3/action_constants.hpp"
char const * etcdv3::CREATE_ACTION = "create";
char const * etcdv3::COMPARESWAP_ACTION = "compareAndSwap";
char const * etcdv3::UPDATE_ACTION = "update";
char const * etcdv3::SET_ACTION = "set";
char const * etcdv3::GET_ACTION = "get";
char const * etcdv3::PUT_ACTION = "put";
char const * etcdv3::DELETE_ACTION = "delete";
char const * etcdv3::COMPAREDELETE_ACTION = "compareAndDelete";
char const * etcdv3::LOCK_ACTION = "lock";
char const * etcdv3::UNLOCK_ACTION = "unlock";
char const * etcdv3::TXN_ACTION = "txn";
char const * etcdv3::WATCH_ACTION = "watch";
char const * etcdv3::LEASEGRANT = "leasegrant";
char const * etcdv3::LEASEREVOKE = "leaserevoke";
char const * etcdv3::LEASEKEEPALIVE = "leasekeepalive";
char const * etcdv3::LEASETIMETOLIVE = "leasetimetolive";
char const * etcdv3::LEASELEASES = "leaseleases";
char const * etcdv3::CAMPAIGN_ACTION = "campaign";
char const * etcdv3::PROCLAIM_ACTION = "preclaim";
char const * etcdv3::LEADER_ACTION = "leader";
char const * etcdv3::OBSERVE_ACTION = "obverse";
char const * etcdv3::RESIGN_ACTION = "resign";
// see: noPrefixEnd in etcd, however c++ doesn't allows '\0' inside a string, thus we use
// the UTF-8 char U+0000 (i.e., "\xC0\x80").
char const * etcdv3::NUL = "\xC0\x80";
char const * etcdv3::KEEPALIVE_CREATE = "keepalive create";
char const * etcdv3::KEEPALIVE_WRITE = "keepalive write";
char const * etcdv3::KEEPALIVE_READ = "keepalive read";
char const * etcdv3::KEEPALIVE_DONE = "keepalive done";
char const * etcdv3::WATCH_CREATE = "watch create";
char const * etcdv3::WATCH_WRITE = "watch write";
char const * etcdv3::WATCH_WRITES_DONE = "watch writes done";
char const * etcdv3::ELECTION_OBSERVE_CREATE = "observe create";
const int etcdv3::ERROR_KEY_NOT_FOUND = 100;
const int etcdv3::ERROR_COMPARE_FAILED = 101;
const int etcdv3::ERROR_KEY_ALREADY_EXISTS = 105;
| 41.152174 | 89 | 0.733228 |
cfc5afce8a871cbdf7809d3bd8833c1e30182e5b | 4,823 | cc | C++ | src/Table.cc | mgonnav/flaviadb | af133b30ec97834753d4d24a682cb2691688a854 | [
"Apache-2.0"
] | 1 | 2020-08-20T22:34:36.000Z | 2020-08-20T22:34:36.000Z | src/Table.cc | mgonnav/flaviadb | af133b30ec97834753d4d24a682cb2691688a854 | [
"Apache-2.0"
] | 1 | 2020-08-27T00:01:42.000Z | 2020-11-27T17:18:58.000Z | src/Table.cc | mgonnav/flaviadb | af133b30ec97834753d4d24a682cb2691688a854 | [
"Apache-2.0"
] | null | null | null | #include "Where.hh"
#include "printutils.hh"
namespace ft = ftools;
namespace fs = std::filesystem;
namespace pu = printUtils;
Table::Table(std::string name)
{
this->name = name;
loadPaths(name);
checkTableExists();
load_metadata();
this->reg_count = ft::getRegCount(name);
this->indexes = new std::vector<Index*>;
loadIndexes();
}
void Table::loadPaths(std::string const& name)
{
this->path = ft::getTablePath(name);
this->regs_path = ft::getRegistersPath(name);
this->indexes_path = ft::getIndexesPath(name);
this->metadata_path = ft::getMetadataPath(name);
}
void Table::checkTableExists()
{
if (!ft::dirExists(this->path))
throw DBException{NON_EXISTING_TABLE, this->name};
}
bool Table::load_metadata()
{
openMetadataFile();
loadMetadataHeader();
for (auto& column : *this->columns)
loadColumnData(column);
return 1;
}
void Table::openMetadataFile()
{
this->metadata_file.open(this->metadata_path);
if (!this->metadata_file.is_open())
throw DBException{UNREADABLE_METADATA};
}
void Table::loadMetadataHeader()
{
loadTableName();
loadColumnCount();
loadRegSize();
}
void Table::loadTableName()
{
std::string metadata_table_name;
getline(this->metadata_file, metadata_table_name, '\t');
if (this->name != metadata_table_name)
throw DBException{DIFFERENT_METADATA_NAME};
}
void Table::loadColumnCount()
{
std::string column_count;
getline(this->metadata_file, column_count, '\t');
this->columns = new std::vector<hsql::ColumnDefinition*>(stoi(column_count));
}
void Table::loadRegSize()
{
std::string reg_size;
getline(this->metadata_file, reg_size, '\n');
this->reg_size = stoi(reg_size);
}
void Table::loadColumnData(hsql::ColumnDefinition*& column)
{
std::string data;
getline(this->metadata_file, data, '\t');
char* col_name = new char[data.size()];
strcpy(col_name, data.c_str());
hsql::ColumnType col_type = getColumnType();
getline(this->metadata_file, data, '\n');
bool col_nullable = stoi(data);
column = new hsql::ColumnDefinition(col_name, col_type, col_nullable);
}
void Table::loadIndexes()
{
for (const auto& reg : fs::directory_iterator(this->indexes_path))
{
std::string idx_name = reg.path().filename();
indexes->push_back(new Index(idx_name));
}
}
void Table::loadStoredRegisters()
{
this->registers =
std::make_unique<std::list<std::pair<std::string, RegisterData>>>();
for (const auto& reg : fs::directory_iterator(this->regs_path))
{
// Load data in file to reg_data
std::ifstream data_file(reg.path());
std::vector<std::string> reg_data;
// Load each piece of data into reg_data
std::string data;
for (size_t i = 0; i < this->columns->size(); i++)
{
getline(data_file, data, '\t');
reg_data.push_back(data);
}
this->registers->push_back({reg.path().filename(), RegisterData(reg_data)});
}
}
Table::Table(std::string name, std::vector<hsql::ColumnDefinition*>* cols)
{
this->name = name;
loadPaths(name);
this->indexes = new std::vector<Index*>;
createTableFolders();
this->columns = cols;
this->reg_size = calculateRegSize();
this->registers =
std::make_unique<std::list<std::pair<std::string, RegisterData>>>();
// Create medata.dat file for table
// and fill it with table's name & cols info
std::ofstream wMetadata(this->metadata_path);
wMetadata << this->name << "\t" << this->columns->size() << "\t"
<< this->reg_size << "\n";
for (const hsql::ColumnDefinition* col : *this->columns)
wMetadata << col->name << "\t" << (int)col->type.data_type << "\t"
<< col->type.length << "\t" << col->nullable << "\n";
wMetadata.close();
std::ofstream wCount(ft::getRegCountPath(this->name));
wCount << 0; // 0 regs when table is created
wCount.close();
std::cout << "Table " << this->name << " was created successfully.\n";
}
void Table::createTableFolders()
{
ft::createFolder(this->path);
ft::createFolder(this->regs_path);
ft::createFolder(this->indexes_path);
}
int Table::calculateRegSize()
{
int reg_size = 0;
for (const auto& col : *this->columns)
{
hsql::DataType data_type = col->type.data_type;
if (data_type == hsql::DataType::INT)
reg_size += 4;
else if (data_type == hsql::DataType::CHAR)
reg_size += col->type.length;
else if (data_type == hsql::DataType::DATE)
reg_size += 8;
}
return reg_size;
}
Table::~Table()
{
delete this->columns;
delete this->indexes;
}
hsql::ColumnType Table::getColumnType()
{
std::string data;
getline(this->metadata_file, data, '\t');
int col_enum = stoi(data);
getline(this->metadata_file, data, '\t');
int col_length = stoi(data);
hsql::ColumnType col_type((hsql::DataType)col_enum, col_length);
return col_type;
}
| 23.758621 | 80 | 0.667427 |
cfc723067d77b4f03d2ddc39c019224197156336 | 5,293 | cpp | C++ | SimulationsOMP/ParaUtilMSDRadix16Sort.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | null | null | null | SimulationsOMP/ParaUtilMSDRadix16Sort.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 2 | 2020-10-19T02:03:11.000Z | 2021-03-19T16:34:39.000Z | SimulationsOMP/ParaUtilMSDRadix16Sort.cpp | COFS-UWA/MPM3D | 1a0c5dc4e92dff3855367846002336ca5a18d124 | [
"MIT"
] | 1 | 2020-04-28T00:33:14.000Z | 2020-04-28T00:33:14.000Z | #include "SimulationsOMP_pcp.h"
#include "ParaUtil.h"
#include "ParaUtilSerialSort.h"
#include "ParaUtilMSDRadix16Sort.h"
#define Data_Digit(num, disp, mask) (((num) >> (disp)) & (mask))
#define Data_Digit_16(num, disp) Data_Digit(num, disp, 0xF)
namespace ParaUtil
{
namespace Internal
{
static constexpr uint64_t radix_num = 1 << msd_radix_16_bit_num;
static constexpr uint64_t radix_mask = radix_num - 1;
static constexpr uint64_t max_radix = radix_mask;
inline void prefix_scan_16_serial(
size_t keys[],
size_t data_num,
size_t bit_offset,
size_t sum_bin[radix_num])
{
size_t i;
memset(sum_bin, 0, radix_num * sizeof(size_t));
for (i = 0; i < data_num; ++i)
++sum_bin[Data_Digit_16(keys[i], bit_offset)];
for (i = 1; i < (radix_num - 1); ++i)
sum_bin[i] += sum_bin[i - 1];
for (i = radix_num - 1; i != 0; --i)
sum_bin[i] = sum_bin[i - 1];
sum_bin[0] = 0;
};
inline void swap_reorder_16_serial(
size_t keys[],
size_t values[],
size_t data_num,
size_t bit_offset,
size_t sum_bin[radix_num])
{
const size_t end_bin[radix_num] = {
sum_bin[1], sum_bin[2], sum_bin[3], sum_bin[4],
sum_bin[5], sum_bin[6], sum_bin[7], sum_bin[8],
sum_bin[9], sum_bin[10], sum_bin[11], sum_bin[12],
sum_bin[13], sum_bin[14], sum_bin[15], data_num
};
for (uint64_t radix = 0; radix < radix_num; ++radix)
{
size_t& data_pos = sum_bin[radix];
const size_t end_pos = end_bin[radix];
while (data_pos < end_pos)
{
uint64_t tmp_radix = Data_Digit_16(keys[data_pos], bit_offset);
if (tmp_radix != radix) // skip sorted part
{
// fill misplaced item by swap reordering
do
{
size_t& new_data_pos = sum_bin[tmp_radix];
size_t new_radix;
while ((new_radix = Data_Digit_16(keys[new_data_pos], bit_offset)) == tmp_radix)
++new_data_pos;
// swap data
size_t tmp = keys[data_pos];
keys[data_pos] = keys[new_data_pos];
keys[new_data_pos] = tmp;
tmp = values[data_pos];
values[data_pos] = values[new_data_pos];
values[new_data_pos] = tmp;
//
++new_data_pos;
tmp_radix = new_radix;
} while (tmp_radix != radix);
}
++data_pos;
}
}
};
tbb::task* MSDRadixSort16Task::execute()
{
if (!is_continuation)
{
if (data_num < min_data_num_for_msd_radix_sort_16 ||
key_bit_num < (msd_radix_16_bit_num + 1))
{
serial_sort(keys, values, data_num,
key_bit_num, tmp_keys, tmp_values);
return nullptr;
}
key_bit_num -= msd_radix_16_bit_num;
size_t sum_bin[radix_num];
prefix_scan_16_serial(keys, data_num, key_bit_num, sum_bin);
swap_reorder_16_serial(keys, values, data_num, key_bit_num, sum_bin);
is_continuation = true;
recycle_as_continuation();
size_t num = sum_bin[0] > 1 ? 1 : 0;
for (size_t radix = 1; radix < radix_num; ++radix)
if ((sum_bin[radix] - sum_bin[radix - 1]) > 1)
++num;
set_ref_count(num);
tbb::task* child_task1 = nullptr;
if (sum_bin[0] > 1)
child_task1 = new (allocate_child())
MSDRadixSort16Task(keys, values, sum_bin[0],
key_bit_num, tmp_keys, tmp_values);
for (size_t radix = 1; radix < radix_num; ++radix)
if ((num = sum_bin[radix] - sum_bin[radix - 1]) > 1)
{
const size_t offset = sum_bin[radix - 1];
spawn(*new (allocate_child())
MSDRadixSort16Task(
keys + offset,
values + offset,
num, key_bit_num,
tmp_keys + offset,
tmp_values + offset));
}
return child_task1;
}
return nullptr;
}
void msd_radix_sort_16(
size_t keys[],
size_t values[],
size_t data_num,
size_t max_key,
size_t tmp_keys[],
size_t tmp_values[],
int thread_num)
{
if (data_num < 2)
return;
tbb::task_scheduler_init init(thread_num);
size_t key_bit_num = cal_digit_num<4>(max_key);
if (key_bit_num)
{
MSDRadixSort16Task& task = *new(tbb::task::allocate_root())
MSDRadixSort16Task(keys, values, data_num, key_bit_num, tmp_keys, tmp_values);
tbb::task::spawn_root_and_wait(task);
}
}
}
} | 33.289308 | 104 | 0.501795 |
cfd0a388d365849c55299571788a64f78b67ee78 | 631 | cpp | C++ | src/scene/Stage.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | src/scene/Stage.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | src/scene/Stage.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | #include "../../include/kit2d/scene/Stage.hpp"
#include "../../include/kit2d/scene/Scene.hpp"
namespace kit2d {
Stage::Stage(Window& window) : window(window) {
window.onUpdate([this](float deltaTime) {
this->scene->update(deltaTime);
});
window.onRender([this](Renderer& renderer) {
this->scene->render(spriteBatch);
spriteBatch.process(renderer);
});
}
void Stage::setScene(std::shared_ptr<Scene> scene) {
this->scene = scene;
scene->prepare();
}
void Stage::play() {
window.loop();
}
Rect Stage::bounds() {
return Rect { window->x, y, width, height };
}
}
| 20.354839 | 54 | 0.613312 |
cfd3aedf01baa8d1ae911ed9694eab6fcd72cd46 | 1,492 | cc | C++ | poj/3/3194.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/3/3194.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/3/3194.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
bool equidivision(const vector<vector<int> >& grid)
{
const int N = grid.size();
vector<vector<bool> > visited(N, vector<bool>(N, false));
for (int n = 0; n < N; n++) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (grid[i][j] != n || visited[i][j]) {
continue;
}
queue<pair<int,int> > q;
q.push(make_pair(i, j));
visited[i][j] = true;
int c = 0;
while (!q.empty()) {
const pair<int,int> p = q.front(); q.pop();
++c;
for (int d = 0; d < 4; d++) {
static const int di[] = {-1, 1, 0, 0}, dj[] = {0, 0, -1, 1};
const int k = p.first + di[d], l = p.second + dj[d];
if (0 <= k && k < N && 0 <= l && l < N && grid[k][l] == n && !visited[k][l]) {
q.push(make_pair(k, l));
visited[k][l] = true;
}
}
}
if (c != N) {
return false;
}
}
}
}
return true;
}
int main()
{
int N;
while (cin >> N && N != 0) {
vector<vector<int> > grid(N, vector<int>(N, N-1));
for (int i = 0; i < N-1; i++) {
for (int j = 0; j < N; j++) {
int x, y;
cin >> x >> y;
--x; --y;
grid[x][y] = i;
}
}
if (equidivision(grid)) {
cout << "good" << endl;
} else {
cout << "wrong" << endl;
}
}
return 0;
} | 24.064516 | 90 | 0.400134 |
cfd67f07a35b31f5fa7582523cad4390e276715f | 1,015 | cpp | C++ | src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | src/io/github/technicalnotes/programming/basics/36-threadNlocking.cpp | chiragbhatia94/programming-cpp | efd6aa901deacf416a3ab599e6599845a8111eac | [
"MIT"
] | null | null | null | #include "bits/stdc++.h"
using namespace std;
char *getTime()
{
chrono::time_point<chrono::system_clock> now = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(now);
return ctime(&t);
}
double accountBalance = 100;
mutex accountLock;
void getMoney(int id, double amount)
{
lock_guard<mutex> lock(accountLock);
this_thread::sleep_for(chrono::seconds(2));
cout << id << " tries to withdraw Rs " << amount << " at " << getTime() << endl;
if ((accountBalance - amount) >= 0)
{
accountBalance -= amount;
cout << "New account balance is Rs " << accountBalance << endl;
}
else
{
cout << "Insufficient funds, current balance is Rs " << accountBalance << endl;
}
}
int main()
{
thread threads[10];
for (int i = 0; i < 10; i++)
{
threads[i] = thread(getMoney, i, 15);
}
for (int i = 0; i < 10; i++)
{
threads[i].join();
}
return 0;
} | 23.068182 | 88 | 0.553695 |
cfd6ec574659e3d92a6abb352f6e84dd8242fc97 | 4,026 | cpp | C++ | window.cpp | mauriliodc/path_aligner | fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7 | [
"MIT"
] | null | null | null | window.cpp | mauriliodc/path_aligner | fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7 | [
"MIT"
] | null | null | null | window.cpp | mauriliodc/path_aligner | fba4a8f95cac54c2bd5ee36626980ca7c4b9efb7 | [
"MIT"
] | null | null | null | #include "window.h"
Window::Window (QWidget *parent) : QMainWindow (parent),ui (new Ui::Window)
{
ui->setupUi(this);
p=0;
laser=0;
}
Window::~Window(){
delete ui;
}
void Window::on_fixed_frame_clicked()
{
QString odometryFilename = QFileDialog::getOpenFileName(this,tr("Open ODOMETRY log file"),"~",tr("All files (*.*)"));
if(odometryFilename.length()>0){
QStringList l = odometryFilename.split("/");
p = new Path(odometryFilename.toStdString());
p->color.r=1.0f;
this->ui->Scene->_drawables.push_back(p);
}
else{
std::cout <<"[BUTTON 1][ON FILE OPEN] no file selected"<<std::endl;
}
}
void Window::on_target_frame_clicked()
{
QString odometryFilename = QFileDialog::getOpenFileName(this,tr("Open ODOMETRY log file"),"~",tr("All files (*.*)"));
if(odometryFilename.length()>0){
QStringList l = odometryFilename.split("/");
laser = new Path(odometryFilename.toStdString());
laser->color.r=1.0f;
laser->color.g=1.0f;
this->ui->Scene->_drawables.push_back(laser);
}
else{
std::cout <<"[BUTTON 2][ON FILE OPEN] no file selected"<<std::endl;
}
}
void Window::on_t_x_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().x()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_t_y_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().y()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_t_z_valueChanged(double arg1)
{
if(laser==0)return;
laser->transform.translation().z()=(float)arg1;
this->ui->Scene->updateGL();
}
void Window::on_r_x_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(this->ui->r_y->value(), Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(this->ui->r_z->value(), Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_r_y_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(this->ui->r_x->value(), Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(this->ui->r_z->value(), Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_r_z_valueChanged(double arg1)
{
if(laser==0)return;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(this->ui->r_x->value(), Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(this->ui->r_y->value(), Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(arg1, Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
void Window::on_print_clicked()
{
std::cout<<"Translation:"<<std::endl;
std::cout<< laser->transform.translation().transpose()<<std::endl<< std::endl;
std::cout<<"Rotation quaternion:"<<std::endl;
std::cout<< Eigen::Quaternionf(laser->transform.linear()).x()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).y()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).z()<< " "
<<Eigen::Quaternionf(laser->transform.linear()).w()<< std::endl<< std::endl;
Eigen::Vector3f ea = laser->transform.linear().matrix().eulerAngles(0, 1, 2);
std::cout<<"RPY:"<<std::endl;
std::cout<<ea.transpose()<<std::endl<< std::endl;
}
void Window::on_reset_button_clicked()
{
if(laser==0)return;
laser->transform.translation().x()=0.0f;
laser->transform.translation().y()=0.0f;
laser->transform.translation().z()=0.0f;
Eigen::Matrix3f m;
m = Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitX())
* Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitY())
* Eigen::AngleAxisf(0.0f, Eigen::Vector3f::UnitZ());
laser->transform.linear() = m;
this->ui->Scene->updateGL();
}
| 30.969231 | 121 | 0.616244 |
cfd7726a7169408dc4d932fb2ff1afdf7efd955f | 917 | cpp | C++ | dp/multi_zero_one_pack.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | 1 | 2020-04-14T05:44:50.000Z | 2020-04-14T05:44:50.000Z | dp/multi_zero_one_pack.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | null | null | null | dp/multi_zero_one_pack.cpp | FrancsXiang/DataStructure-Algorithms | f8f9e6d7be94057b955330cb7058235caef5cfed | [
"MIT"
] | 2 | 2020-09-02T08:56:31.000Z | 2021-06-22T11:20:58.000Z | #include <iostream>
#include <algorithm>
#define MAXN 101
#define MAXV 1001
using namespace std;
// if you want the full pack,initialize res[0] = 0,res[1:] = -inf
// or you want the maximum value, initialize res[:] = 0;
//you could also use cost-effective sort to solve
void orgin() {
int vol[MAXN];
int val[MAXN];
int res[MAXN][MAXV];
int v, n;
cin >> v >> n;
for (int i = 1; i <= n; i++) cin >> vol[i] >> val[i];
for (int i = 0; i <= v; i++) res[0][i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = vol[i]; j <= v; j++) {
res[i][j] = max(res[i - 1][j], res[i][j - vol[i]] + val[i]);
}
}
}
void space_opt() {
int vol[MAXN];
int val[MAXN];
int res[MAXV];
int v, n;
for (int i = 1; i <= n; i++) cin >> vol[i] >> val[i];
for (int i = 0; i <= v; i++) res[i] = 0;
for (int i = 1; i <= n; i++) {
for (int j = vol[i]; j <= v; j++) {
res[j] = max(res[j], res[j - vol[i]] + val[i]);
}
}
}
| 24.131579 | 65 | 0.514722 |
cfd7f3d4507d7cb87ee8165eb1333897a0568f38 | 2,841 | cpp | C++ | src/example.cpp | tammoippen/timer | 7ae22bd8ac1ec1c28046c0558dd69bb34b7a8d5f | [
"MIT"
] | 7 | 2017-02-08T19:30:12.000Z | 2021-08-18T06:42:38.000Z | src/example.cpp | tammoippen/timer | 7ae22bd8ac1ec1c28046c0558dd69bb34b7a8d5f | [
"MIT"
] | null | null | null | src/example.cpp | tammoippen/timer | 7ae22bd8ac1ec1c28046c0558dd69bb34b7a8d5f | [
"MIT"
] | 2 | 2017-02-08T19:30:13.000Z | 2018-04-09T14:25:03.000Z | /**
* example.cpp
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tammo Ippen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <iostream>
#include "scopetimer.hpp"
#include "seriestimer.hpp"
#include "stopwatch.hpp"
#include <unistd.h>
using namespace std;
using namespace timer;
unsigned long
fib( size_t n )
{
// ScopeTimer f("inFib");
if ( n == 0 )
return 0;
if ( n == 1 )
return 1;
return fib( n - 1 ) + fib( n - 2 );
}
int
main( int32_t, char const** )
{
SeriesTimer y;
#pragma omp parallel num_threads( 4 )
{
ScopeTimer f( "fib" );
Stopwatch x;
y.start();
x.start();
fib( 43 );
x.stop();
y.stop();
x.print( "First fib time = " );
y.start();
x.start(); // resume
fib( 43 );
x.print( "Some intermediate: " );
x.stop();
y.stop();
x.print( "First & Second fib time = " );
cout << "Time for 3 fib ... " << endl;
y.start();
x.start(); // resume
fib( 43 );
x.stop();
x.print( "", Stopwatch::MICROSEC );
x.print( "", Stopwatch::MILLISEC );
x.print();
x.print( "", Stopwatch::MINUTES );
x.print( "", Stopwatch::HOURS );
x.print( "", Stopwatch::DAYS, cerr );
y.stop();
x.reset();
x.start(); // start from new
fib( 43 );
x.stop();
x.print( "Last fib time = " );
}
{
ScopeTimer ot( "outside for-loop" );
for ( int32_t i = 0; i < 5; ++i )
{
ScopeTimer t( "in for-loop" );
y.start();
usleep( 831234 ); // ... do computations for 5.83 sec each
y.stop();
}
}
y.print( "Hi" );
{
SeriesTimer x;
for ( int32_t i = 0; i < 10; ++i )
{
x.start();
// do computation for about 1 sec ...
usleep( 1000236 );
x.stop();
}
x.print( "Timings: " );
}
return 0;
}
| 24.076271 | 80 | 0.607181 |
cfdaca73ae234be2ccb6cf70c985a27b77a94a2f | 12,440 | cpp | C++ | src/gui/qgsmessagebar.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/gui/qgsmessagebar.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/gui/qgsmessagebar.cpp | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgsmessagebar.cpp - description
-------------------
begin : June 2012
copyright : (C) 2012 by Giuseppe Sucameli
email : sucameli at faunalia dot it
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsmessagebar.h"
#include "qgsmessagebaritem.h"
#include "qgsapplication.h"
#include "qgsmessagelog.h"
#include "qgsmessageviewer.h"
#include <QWidget>
#include <QPalette>
#include <QStackedWidget>
#include <QProgressBar>
#include <QToolButton>
#include <QTimer>
#include <QGridLayout>
#include <QMenu>
#include <QMouseEvent>
#include <QLabel>
QgsMessageBar::QgsMessageBar( QWidget *parent )
: QFrame( parent )
{
QPalette pal = palette();
pal.setBrush( backgroundRole(), pal.window() );
setPalette( pal );
setAutoFillBackground( true );
setFrameShape( QFrame::StyledPanel );
setFrameShadow( QFrame::Plain );
mLayout = new QGridLayout( this );
const int xMargin = std::max( 9.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.45 );
const int yMargin = std::max( 1.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.05 );
mLayout->setContentsMargins( xMargin, yMargin, xMargin, yMargin );
setLayout( mLayout );
mCountProgress = new QProgressBar( this );
mCountStyleSheet = QString( "QProgressBar { border: 1px solid rgba(0, 0, 0, 75%);"
" border-radius: 2px; background: rgba(0, 0, 0, 0);"
" image: url(:/images/themes/default/%1) }"
"QProgressBar::chunk { background-color: rgba(0, 0, 0, 30%); width: 5px; }" );
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
mCountProgress->setObjectName( QStringLiteral( "mCountdown" ) );
const int barWidth = std::max( 25.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 1.25 );
const int barHeight = std::max( 14.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.7 );
mCountProgress->setFixedSize( barWidth, barHeight );
mCountProgress->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
mCountProgress->setTextVisible( false );
mCountProgress->setRange( 0, 5 );
mCountProgress->setHidden( true );
mLayout->addWidget( mCountProgress, 0, 0, 1, 1 );
mItemCount = new QLabel( this );
mItemCount->setObjectName( QStringLiteral( "mItemCount" ) );
mItemCount->setToolTip( tr( "Remaining messages" ) );
mItemCount->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred );
mLayout->addWidget( mItemCount, 0, 2, 1, 1 );
mCloseMenu = new QMenu( this );
mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) );
mActionCloseAll = new QAction( tr( "Close All" ), this );
mCloseMenu->addAction( mActionCloseAll );
connect( mActionCloseAll, &QAction::triggered, this, &QgsMessageBar::clearWidgets );
mCloseBtn = new QToolButton( this );
mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) );
mCloseBtn->setToolTip( tr( "Close" ) );
mCloseBtn->setMinimumWidth( 40 );
mCloseBtn->setStyleSheet(
"QToolButton { border:none; background-color: rgba(0, 0, 0, 0); }"
"QToolButton::menu-button { border:none; background-color: rgba(0, 0, 0, 0); }" );
mCloseBtn->setCursor( Qt::PointingHandCursor );
mCloseBtn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconClose.svg" ) ) );
const int iconSize = std::max( 18.0, Qgis::UI_SCALE_FACTOR * fontMetrics().height() * 0.9 );
mCloseBtn->setIconSize( QSize( iconSize, iconSize ) );
mCloseBtn->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum );
mCloseBtn->setMenu( mCloseMenu );
mCloseBtn->setPopupMode( QToolButton::MenuButtonPopup );
connect( mCloseBtn, &QAbstractButton::clicked, this, static_cast < bool ( QgsMessageBar::* )() > ( &QgsMessageBar::popWidget ) );
mLayout->addWidget( mCloseBtn, 0, 3, 1, 1 );
mCountdownTimer = new QTimer( this );
mCountdownTimer->setInterval( 1000 );
connect( mCountdownTimer, &QTimer::timeout, this, &QgsMessageBar::updateCountdown );
connect( this, &QgsMessageBar::widgetAdded, this, &QgsMessageBar::updateItemCount );
connect( this, &QgsMessageBar::widgetRemoved, this, &QgsMessageBar::updateItemCount );
// start hidden
setVisible( false );
}
void QgsMessageBar::mousePressEvent( QMouseEvent *e )
{
if ( mCountProgress == childAt( e->pos() ) && e->button() == Qt::LeftButton )
{
if ( mCountdownTimer->isActive() )
{
mCountdownTimer->stop();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerContinue.svg" ) ) );
}
else
{
mCountdownTimer->start();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
}
}
}
void QgsMessageBar::popItem( QgsMessageBarItem *item )
{
Q_ASSERT( item );
if ( item != mCurrentItem && !mItems.contains( item ) )
return;
if ( item == mCurrentItem )
{
mLayout->removeWidget( mCurrentItem );
mCurrentItem->hide();
disconnect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
mCurrentItem->deleteLater();
mCurrentItem = nullptr;
if ( !mItems.isEmpty() )
{
showItem( mItems.at( 0 ) );
}
else
{
hide();
}
}
else
{
mItems.removeOne( item );
}
emit widgetRemoved( item );
}
bool QgsMessageBar::popWidget( QgsMessageBarItem *item )
{
if ( !item || !mCurrentItem )
return false;
if ( item == mCurrentItem )
{
popItem( mCurrentItem );
return true;
}
for ( QgsMessageBarItem *existingItem : qgis::as_const( mItems ) )
{
if ( existingItem == item )
{
mItems.removeOne( existingItem );
existingItem->deleteLater();
return true;
}
}
return false;
}
bool QgsMessageBar::popWidget()
{
if ( !mCurrentItem )
return false;
resetCountdown();
QgsMessageBarItem *item = mCurrentItem;
popItem( item );
return true;
}
bool QgsMessageBar::clearWidgets()
{
if ( !mCurrentItem && mItems.empty() )
return true;
while ( !mItems.isEmpty() )
{
popWidget();
}
popWidget();
return !mCurrentItem && mItems.empty();
}
void QgsMessageBar::pushSuccess( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Success );
}
void QgsMessageBar::pushInfo( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Info );
}
void QgsMessageBar::pushWarning( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Warning );
}
void QgsMessageBar::pushCritical( const QString &title, const QString &message )
{
pushMessage( title, message, Qgis::Critical );
}
void QgsMessageBar::showItem( QgsMessageBarItem *item )
{
Q_ASSERT( item );
if ( mCurrentItem )
disconnect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
if ( item == mCurrentItem )
return;
if ( mItems.contains( item ) )
mItems.removeOne( item );
if ( mCurrentItem )
{
mItems.prepend( mCurrentItem );
mLayout->removeWidget( mCurrentItem );
mCurrentItem->hide();
}
mCurrentItem = item;
mLayout->addWidget( item, 0, 1, 1, 1 );
mCurrentItem->show();
if ( item->duration() > 0 )
{
mCountProgress->setRange( 0, item->duration() );
mCountProgress->setValue( item->duration() );
mCountProgress->setVisible( true );
mCountdownTimer->start();
}
connect( mCurrentItem, &QgsMessageBarItem::styleChanged, this, &QWidget::setStyleSheet );
setStyleSheet( item->getStyleSheet() );
show();
emit widgetAdded( item );
}
void QgsMessageBar::pushItem( QgsMessageBarItem *item )
{
resetCountdown();
item->mMessageBar = this;
// avoid duplicated widget
popWidget( item );
showItem( item );
// Log all messages that are sent to the message bar into the message log so the
// user can get them back easier.
QString formattedTitle = QStringLiteral( "%1 : %2" ).arg( item->title(), item->text() );
QgsMessageLog::logMessage( formattedTitle, tr( "Messages" ), item->level() );
}
QgsMessageBarItem *QgsMessageBar::pushWidget( QWidget *widget, Qgis::MessageLevel level, int duration )
{
QgsMessageBarItem *item = nullptr;
item = dynamic_cast<QgsMessageBarItem *>( widget );
if ( item )
{
item->setLevel( level )->setDuration( duration );
}
else
{
item = new QgsMessageBarItem( widget, level, duration );
}
pushItem( item );
return item;
}
void QgsMessageBar::pushMessage( const QString &title, const QString &text, Qgis::MessageLevel level, int duration )
{
// keep the number of items in the message bar to a maximum of 20, avoids flooding (and freezing) of the main window
if ( mItems.count() > 20 )
mItems.removeFirst();
// block duplicate items, avoids flooding (and freezing) of the main window
for ( auto it = mItems.constBegin(); it != mItems.constEnd(); ++it )
{
if ( level == ( *it )->level() && title == ( *it )->title() && text == ( *it )->text() )
return;
}
QgsMessageBarItem *item = new QgsMessageBarItem( title, text, level, duration );
pushItem( item );
}
void QgsMessageBar::pushMessage( const QString &title, const QString &text, const QString &showMore, Qgis::MessageLevel level, int duration )
{
QgsMessageViewer *mv = new QgsMessageViewer();
mv->setWindowTitle( title );
mv->setMessageAsPlainText( text + "\n\n" + showMore );
QToolButton *showMoreButton = new QToolButton();
QAction *act = new QAction( showMoreButton );
act->setText( tr( "Show more" ) );
showMoreButton->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) );
showMoreButton->setCursor( Qt::PointingHandCursor );
showMoreButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred );
showMoreButton->addAction( act );
showMoreButton->setDefaultAction( act );
connect( showMoreButton, &QToolButton::triggered, mv, &QDialog::exec );
connect( showMoreButton, &QToolButton::triggered, showMoreButton, &QObject::deleteLater );
QgsMessageBarItem *item = new QgsMessageBarItem(
title,
text,
showMoreButton,
level,
duration );
pushItem( item );
}
QgsMessageBarItem *QgsMessageBar::createMessage( const QString &text, QWidget *parent )
{
QgsMessageBarItem *item = new QgsMessageBarItem( text, Qgis::Info, 0, parent );
return item;
}
QgsMessageBarItem *QgsMessageBar::createMessage( const QString &title, const QString &text, QWidget *parent )
{
return new QgsMessageBarItem( title, text, Qgis::Info, 0, parent );
}
QgsMessageBarItem *QgsMessageBar::createMessage( QWidget *widget, QWidget *parent )
{
return new QgsMessageBarItem( widget, Qgis::Info, 0, parent );
}
void QgsMessageBar::updateCountdown()
{
if ( !mCountdownTimer->isActive() )
{
resetCountdown();
return;
}
if ( mCountProgress->value() < 2 )
{
popWidget();
}
else
{
mCountProgress->setValue( mCountProgress->value() - 1 );
}
}
void QgsMessageBar::resetCountdown()
{
if ( mCountdownTimer->isActive() )
mCountdownTimer->stop();
mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.svg" ) ) );
mCountProgress->setVisible( false );
}
void QgsMessageBar::updateItemCount()
{
mItemCount->setText( !mItems.isEmpty() ? tr( "%n more", "unread messages", mItems.count() ) : QString() );
// do not show the down arrow for opening menu with "close all" if there is just one message
mCloseBtn->setMenu( !mItems.isEmpty() ? mCloseMenu : nullptr );
mCloseBtn->setPopupMode( !mItems.isEmpty() ? QToolButton::MenuButtonPopup : QToolButton::DelayedPopup );
}
| 31.573604 | 141 | 0.650482 |
cfdc72d8794b82cf9e672af70af4f7c1f6509f18 | 1,467 | cpp | C++ | src/app/VideoCanvas.cpp | wolodyx/equvator | e246ebf8bdc48e3955cf7f0650eb88ae57e24ad3 | [
"MIT"
] | null | null | null | src/app/VideoCanvas.cpp | wolodyx/equvator | e246ebf8bdc48e3955cf7f0650eb88ae57e24ad3 | [
"MIT"
] | null | null | null | src/app/VideoCanvas.cpp | wolodyx/equvator | e246ebf8bdc48e3955cf7f0650eb88ae57e24ad3 | [
"MIT"
] | null | null | null | #include "VideoCanvas.h"
#include <wx/dcbuffer.h>
#include <wx/rawbmp.h>
#include <opencv2/opencv.hpp>
VideoCanvas::VideoCanvas(wxWindow* parent)
: wxScrolledCanvas(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
{
SetBackgroundColour(*wxBLACK);
SetBackgroundStyle(wxBG_STYLE_PAINT);
m_bitmap = new wxBitmap();
Bind(wxEVT_PAINT, &VideoCanvas::OnPaint, this);
}
VideoCanvas::~VideoCanvas()
{
delete m_bitmap;
}
namespace {;
bool Convert(const cv::Mat& img, wxBitmap& bitmap)
{
bitmap.Create(img.cols, img.rows, 24);
wxNativePixelData pixelData(bitmap);
wxNativePixelData::Iterator pixelDataIt(pixelData);
const uchar* bgr = img.data;
for(int row = 0; row < pixelData.GetHeight(); ++row)
{
pixelDataIt.MoveTo(pixelData, 0, row);
for(int col = 0; col < pixelData.GetWidth(); ++col, ++pixelDataIt)
{
pixelDataIt.Blue() = *bgr++;
pixelDataIt.Green() = *bgr++;
pixelDataIt.Red() = *bgr++;
}
}
return bitmap.IsOk();
}
}
bool VideoCanvas::LoadImage(const cv::Mat& img)
{
if(!Convert(img,*m_bitmap))
return false;
Refresh();
Update();
return false;
}
void VideoCanvas::OnPaint(wxPaintEvent&)
{
if(!m_bitmap || !m_bitmap->IsOk())
return;
wxAutoBufferedPaintDC dc(this);
dc.Clear();
DoPrepareDC(dc);
dc.DrawBitmap(*m_bitmap, 0, 0, false);
}
| 20.375 | 100 | 0.63122 |
cfdd07948334c7fc84c2caf3fa62b4a2bfad4efa | 1,252 | cpp | C++ | test/src/Version.test.cpp | AMS21/CppBase | a6ec5542682bcebf5958d54557af1e03752a132f | [
"CC0-1.0"
] | null | null | null | test/src/Version.test.cpp | AMS21/CppBase | a6ec5542682bcebf5958d54557af1e03752a132f | [
"CC0-1.0"
] | 1 | 2020-05-12T19:48:20.000Z | 2020-05-12T19:48:20.000Z | test/src/Version.test.cpp | AMS21/CppBase | a6ec5542682bcebf5958d54557af1e03752a132f | [
"CC0-1.0"
] | null | null | null | #include <doctest.h>
#include <cpp/Version.hpp>
TEST_CASE("Version.Attribute")
{
#if __has_cpp_attribute(carries_dependencies)
#endif
#if __has_cpp_attribute(deprecated)
#endif
#if __has_cpp_attribute(fallthrough)
#endif
#if __has_cpp_attribute(likely)
#endif
#if __has_cpp_attribute(unlikely)
#endif
#if __has_cpp_attribute(maybe_unused)
#endif
#if __has_cpp_attribute(no_unique_address)
#endif
#if __has_cpp_attribute(nodiscard)
#endif
#if __has_cpp_attribute(noreturn)
#endif
}
TEST_CASE("Version.CoreLanguage")
{
int cpp_aggregate_bases = __cpp_aggregate_bases;
int cpp_aggregate_nsdmi = __cpp_aggregate_nsdmi;
int cpp_aggregate_paren_init = __cpp_aggregate_paren_init;
int cpp_alias_templates = __cpp_alias_templates;
int cpp_aligned_new = __cpp_aligned_new;
int cpp_attributes = __cpp_attributes;
int cpp_binary_literals = __cpp_binary_literals;
int cpp_capture_star_this = __cpp_capture_star_this;
int cpp_char8_t = __cpp_char8_t;
int cpp_concepts = __cpp_concepts;
int cpp_conditional_explicit = __cpp_conditional_explicit;
int cpp_consteval = __cpp_consteval;
int cpp_constexpr = __cpp_constexpr;
}
| 29.116279 | 62 | 0.746006 |
cfdf565d5dd6e610dedcd293ffce8989883de855 | 1,302 | cpp | C++ | HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp | nik3212/hackerrank-challenges | 676cf748a437117016607ae17c15211269bf2f92 | [
"MIT"
] | 1 | 2018-11-14T14:14:20.000Z | 2018-11-14T14:14:20.000Z | HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp | nik3212/challenges | b127bc66ffa27bfdef87ac402dc080f933dad893 | [
"MIT"
] | null | null | null | HackerRank/Mathematics/Fundamentals/Handshake/Solution.cpp | nik3212/challenges | b127bc66ffa27bfdef87ac402dc080f933dad893 | [
"MIT"
] | null | null | null | /*
At the annual meeting of Board of Directors of Acme Inc, every one starts shaking hands with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can you tell the total count of handshakes?
Input Format
The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of Board of Directors of Acme.
Output Format
Print the number of handshakes for each test-case in a new line.
Constraints
1 <= T <= 1000
0 < N < 10^6
Sample Input
2
1
2
Sample Output
0
1
Explanation
Case 1 : The lonely board member shakes no hands, hence 0.
Case 2 : There are 2 board members, 1 handshake takes place.
*/
#include <bits/stdc++.h>
using namespace std;
/*
* Complete the handshake function below.
*/
int handshake(int n) {
if (n == 0 || n == 1) {
return 0;
}
return n * (n - 1) / 2;
}
int main() {
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int result = handshake(n);
fout << result << "\n";
}
fout.close();
return 0;
}
| 18.083333 | 224 | 0.634409 |
cfe36472f7d92eb5ec50760171e5141b925409af | 4,454 | cpp | C++ | graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp | vlsinitsyn/axis1 | 65a622201e526dedf7c3aeadce7cac5bd79895bf | [
"Apache-2.0"
] | 1 | 2021-11-10T19:36:30.000Z | 2021-11-10T19:36:30.000Z | graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp | vlsinitsyn/axis1 | 65a622201e526dedf7c3aeadce7cac5bd79895bf | [
"Apache-2.0"
] | null | null | null | graveyard/src/transport/axis2/ssl/AxisSSLChannelException.cpp | vlsinitsyn/axis1 | 65a622201e526dedf7c3aeadce7cac5bd79895bf | [
"Apache-2.0"
] | 2 | 2021-11-02T13:09:57.000Z | 2021-11-10T19:36:22.000Z | /* -*- C++ -*- */
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @author Damitha Kumarage (damitha@hsenid.lk, damitha@opensource.lk)
*
*/
#include "AxisSSLChannelException.hpp"
/**
* Default when no parameter passed. When thrown with no parameter
* more general SERVER_TRANSPORT_EXCEPTION is assumed.
*/
AxisSSLChannelException::AxisSSLChannelException()
{
processException(SERVER_TRANSPORT_EXCEPTION);
}
AxisSSLChannelException::AxisSSLChannelException (const int iExceptionCode)
{
m_iExceptionCode = iExceptionCode;
processException (iExceptionCode);
}
AxisSSLChannelException::AxisSSLChannelException(const int iExceptionCode, char* pcMessage)
{
m_iExceptionCode = iExceptionCode;
processException(iExceptionCode, pcMessage);
}
AxisSSLChannelException::AxisSSLChannelException (const exception* e)
{
processException (e);
}
AxisSSLChannelException::AxisSSLChannelException (const exception* e, const int iExceptionCode)
{
processException (e, iExceptionCode);
}
AxisSSLChannelException::~AxisSSLChannelException() throw ()
{
}
void AxisSSLChannelException::processException (const exception* e, const int iExceptionCode)
{
m_sMessage = getMessage (iExceptionCode) + ":" + getMessage(e);
}
void AxisSSLChannelException::processException (const exception* e, char* pcMessage)
{
m_sMessage += "AxisSSLChannelException:" + string(pcMessage) + ":" + getMessage (e);
}
void AxisSSLChannelException::processException (const exception* e)
{
m_sMessage += "AxisSSLChannelException:" + getMessage (e);
}
void AxisSSLChannelException::processException(const int iExceptionCode)
{
m_sMessage = getMessage (iExceptionCode);
}
void AxisSSLChannelException::processException(const int iExceptionCode, char* pcMessage)
{
AxisString sMessage = pcMessage;
m_sMessage = getMessage(iExceptionCode) + " " + sMessage;
}
const string AxisSSLChannelException::getMessage (const exception* objException)
{
static string objExDetail = objException->what();
return objExDetail;
}
const string AxisSSLChannelException::getMessage (const int iExceptionCode)
{
switch(iExceptionCode)
{
case CLIENT_SSLCHANNEL_RECEPTION_EXCEPTION:
m_sMessage = "AxisSSLChannelException:Problem occured when" \
" receiving the stream";
break;
case CLIENT_SSLCHANNEL_SENDING_EXCEPTION:
m_sMessage = "AxisSSLChannelException:Problem occured when sending" \
" the stream";
break;
case CLIENT_SSLCHANNEL_CHANNEL_INIT_ERROR:
m_sMessage = "AxisSSLChannelException:Cannot initialize a " \
"channel to the remote end";
break;
case CLIENT_SSLCHANNEL_SOCKET_CREATE_ERROR:
m_sMessage = "AxisSSLChannelException:Sockets error Couldn't" \
" create socket";
break;
case CLIENT_SSLCHANNEL_SOCKET_CONNECT_ERROR:
m_sMessage = "AxisSSLChannelException:Cannot open a channel to the" \
" remote end, shutting down the channel";
break;
case CLIENT_SSLCHANNEL_INVALID_SOCKET_ERROR:
m_sMessage = "AxisSSLChannelException:Socket used to write is invalid";
break;
case CLIENT_SSLCHANNEL_CONTEXT_CREATE_ERROR:
m_sMessage = "AxisSSLChannelException:Could not create SSL context";
break;
case CLIENT_SSLCHANNEL_ERROR:
m_sMessage = "AxisSSLChannelException:OpenSSL Error code is:";
break;
default:
m_sMessage = "AxisSSLChannelException:Unknown SSL Channel Exception";
}
return m_sMessage;
}
const char* AxisSSLChannelException::what() throw ()
{
return m_sMessage.c_str ();
}
const int AxisSSLChannelException::getExceptionCode()
{
return m_iExceptionCode;
}
| 31.146853 | 95 | 0.710373 |
cfe61a58a6e7ef9adddfaffe4f3aa0846db4eb44 | 4,744 | cpp | C++ | src/progress_bar.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | src/progress_bar.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | src/progress_bar.cpp | sweetkristas/anura | 5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd | [
"CC0-1.0"
] | null | null | null | /*
Copyright (C) 2003-2013 by David White <davewx7@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include "graphics.hpp"
#include "progress_bar.hpp"
#include "raster.hpp"
namespace gui {
progress_bar::progress_bar(int progress, int minv, int maxv, const std::string& gui_set)
: progress_(progress), min_(minv), max_(maxv), completion_called_(false),
upscale_(false), color_(128,128,128,255), hpad_(10), vpad_(10)
{
if(gui_set.empty() == false) {
frame_image_set_ = framed_gui_element::get(gui_set);
}
}
progress_bar::progress_bar(const variant& v, game_logic::formula_callable* e)
: widget(v,e), completion_called_(false),
progress_(v["progress"].as_int(0)),
min_(v["min"].as_int(0)), max_(v["max"].as_int(100)),
hpad_(10), vpad_(10)
{
if(v.has_key("on_completion")) {
ASSERT_LOG(get_environment() != 0, "You must specify a callable environment");
completion_handler_ = get_environment()->create_formula(v["on_completion"]);
oncompletion_ = boost::bind(&progress_bar::complete, this);
}
std::string frame_set = v["frame_set"].as_string_default("");
if(frame_set != "none" && frame_set.empty() == false) {
frame_image_set_ = framed_gui_element::get(frame_set);
}
upscale_ = v["resolution"].as_string_default("normal") == "normal" ? false : true;
if(v.has_key("color")) {
color_ = graphics::color(v["color"]);
} else if(v.has_key("colour")) {
color_ = graphics::color(v["colour"]);
} else {
color_ = graphics::color("grey");
}
if(v.has_key("padding")) {
ASSERT_LOG(v["padding"].num_elements() == 2, "Padding field must be two element, found " << v["padding"].num_elements())
hpad_ = v["padding"][0].as_int();
vpad_ = v["padding"][1].as_int();
}
}
void progress_bar::complete()
{
if(get_environment()) {
variant value = completion_handler_->execute(*get_environment());
get_environment()->execute_command(value);
} else {
std::cerr << "progress_bar::complete() called without environment!" << std::endl;
}
}
void progress_bar::set_progress(int value)
{
progress_ = std::min(max_, value);
progress_ = std::max(min_, progress_);
if(progress_ >= max_ && completion_called_ == false) {
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
}
void progress_bar::update_progress(int delta)
{
progress_ = std::min(max_, progress_ + delta);
progress_ = std::max(min_, progress_);
if(progress_ >= max_ && completion_called_ == false) {
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
}
void progress_bar::set_completion_handler(boost::function<void ()> oncompletion)
{
oncompletion_ = oncompletion;
}
void progress_bar::reset()
{
progress_ = min_;
completion_called_ = false;
}
variant progress_bar::get_value(const std::string& key) const
{
if(key == "progress") {
return variant(progress_);
} else if(key == "min") {
return variant(min_);
} else if(key == "max") {
return variant(max_);
}
return variant();
}
void progress_bar::set_value(const std::string& key, const variant& value)
{
if(key == "progress") {
set_progress(value.as_int());
} else if(key == "min") {
min_ = value.as_int();
} else if(key == "max") {
max_ = value.as_int();
if(progress_ < max_) {
completion_called_ = false;
} else if(completion_called_ == false) {
progress_ = max_;
completion_called_ = true;
if(oncompletion_) {
oncompletion_();
}
}
} else if(key == "resolution") {
upscale_ = value.as_string_default("normal") == "normal" ? false : true;
} else if(key == "color" || key == "colour") {
color_ = graphics::color(value);
} else if(key == "padding") {
ASSERT_LOG(value.num_elements() == 2, "Padding field must be two element, found " << value.num_elements())
hpad_ = value[0].as_int();
vpad_ = value[1].as_int();
}
widget::set_value(key, value);
}
void progress_bar::handle_draw() const
{
if(frame_image_set_) {
frame_image_set_->blit(x(),y(),width(),height(), upscale_);
}
const int w = int((width()-hpad_*2) * float(progress_-min_)/float(max_-min_));
graphics::draw_rect(rect(x()+hpad_,y()+vpad_,w,height()-vpad_*2), color_);
}
}
| 29.283951 | 122 | 0.684233 |
cfe8e78c2ad096dcfd8c34d5cbddaf14f96b6892 | 674 | cpp | C++ | Cpp_Projects/tryandcatch.cpp | EderLukas/Portfolio | 1c9adef3435129d26d3c6275a79ed363bf062e8f | [
"MIT"
] | null | null | null | Cpp_Projects/tryandcatch.cpp | EderLukas/Portfolio | 1c9adef3435129d26d3c6275a79ed363bf062e8f | [
"MIT"
] | null | null | null | Cpp_Projects/tryandcatch.cpp | EderLukas/Portfolio | 1c9adef3435129d26d3c6275a79ed363bf062e8f | [
"MIT"
] | null | null | null | /*
* source code: tryandcatch.cpp
* author: Lukas Eder
* date: 01.01.2018
*
* Descr.:
* Uebung zu try and catch Fehlerbehandlung inkl. inteligentem Array
*/
#include <iostream>
#include <array>
using namespace std;
int main() {
//Variablen
array<double, 3> preise;
preise.at(0) = 1.45;
preise.at(1) = 3.55;
preise.at(2) = 5.25;
for (unsigned int i = 0; i < preise.size(); i++) {
try {
cout << "Preise pos 1 mit []: " << preise[1] << endl;
cout << "Preise pos 5 mit at()" << preise.at(5) << endl;
cout << "Ende des Try-Blocks" << endl;
}
catch(exception &e){
cout << "Fehler: " << e.what() << endl;
}
}
} | 21.741935 | 69 | 0.55638 |
cfeb15a71d3d8c8a5b4ee0d3a96fd66458c16cc0 | 1,209 | hpp | C++ | include/ISubThread.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | 1 | 2015-02-05T10:41:14.000Z | 2015-02-05T10:41:14.000Z | include/ISubThread.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | 1 | 2015-02-04T20:47:52.000Z | 2015-02-05T07:43:05.000Z | include/ISubThread.hpp | lordio/insanity | 7dfbf398fe08968f40a32280bf2b16cca2b476a1 | [
"MIT"
] | null | null | null | #ifndef INSANITY_INTERFACE_SUB_THREAD
#define INSANITY_INTERFACE_SUB_THREAD
#include "Constants.hpp"
#include "IThread.hpp"
namespace Insanity
{
//"Sub," in opposition to the "main" thread, represented by IApplication.
class INSANITY_API ISubThread : public virtual IThread
{
public:
//=================================================
//Create a new subthread.
//Not intended for use outside the library.
//Inherit from Default::Thread instead.
//=================================================
static ISubThread * Create(ISubThread * ext, bool start = true);
//=================================================
//Start a thread that is not currently running,
// whether it hasn't started yet,
// or has already returned.
//Immediately returns if called relative to current thread.
//=================================================
virtual void Start() = 0;
//=================================================
//The main body of a thread's operations.
// An implementation will call this through the function
// passed to the platform-specific thread creation API.
//=================================================
virtual void Main() = 0;
};
}
#endif
| 31.815789 | 74 | 0.539289 |
cff5243f89c24da48b4e1a8e5bee40914b35363e | 16,909 | cpp | C++ | src/TextureLoaderFrontend/load_dds.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | 2 | 2020-05-31T19:54:19.000Z | 2021-09-14T12:00:12.000Z | src/TextureLoaderFrontend/load_dds.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | src/TextureLoaderFrontend/load_dds.cpp | WubiCookie/VkRenderer | 87cc5d858591fc976c197ab2834e1ac9a418becd | [
"MIT"
] | null | null | null | #include "load_dds.hpp"
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
//#define MEAN_AND_LEAN
//#define NO_MINMAX
//#include <windows.h>
#include <iostream>
/*
Can load easier and more indepth with https://github.com/Hydroque/DDSLoader
Because a lot of crappy, weird DDS file loader files were found online. The
resources are actually VERY VERY limited. Written in C, can very easily port to
C++ through casting mallocs (ensure your imports are correct), goto can be
replaced.
https://www.gamedev.net/forums/topic/637377-loading-dds-textures-in-opengl-black-texture-showing/
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
^ Two examples of terrible code
https://gist.github.com/Hydroque/d1a8a46853dea160dc86aa48618be6f9
^ My first look and clean up 'get it working'
https://ideone.com/WoGThC
^ Improvement details
File Structure:
Section Length
///////////////////
FILECODE 4
HEADER 124
HEADER_DX10* 20
(https://msdn.microsoft.com/en-us/library/bb943983(v=vs.85).aspx) PIXELS
fseek(f, 0, SEEK_END); (ftell(f) - 128) - (fourCC == "DX10" ? 17 or 20 : 0)
* the link tells you that this section isn't written unless its a DX10 file
Supports DXT1, DXT3, DXT5.
The problem with supporting DX10 is you need to know what it is used for and
how opengl would use it. File Byte Order: typedef unsigned int DWORD; // 32bits
little endian type index attribute // description
///////////////////////////////////////////////////////////////////////////////////////////////
DWORD 0 file_code; //. always `DDS `, or 0x20534444
DWORD 4 size; //. size of the header, always 124
(includes PIXELFORMAT) DWORD 8 flags; //. bitflags that
tells you if data is present in the file
// CAPS 0x1
// HEIGHT 0x2
// WIDTH 0x4
// PITCH 0x8
// PIXELFORMAT 0x1000
// MIPMAPCOUNT 0x20000
// LINEARSIZE 0x80000
// DEPTH 0x800000
DWORD 12 height; //. height of the base image (biggest
mipmap) DWORD 16 width; //. width of the base image
(biggest mipmap) DWORD 20 pitchOrLinearSize; //. bytes per scan line in
an uncompressed texture, or bytes in the top level texture for a compressed
texture
// D3DX11.lib and other similar
libraries unreliably or inconsistently provide the pitch, convert with
// DX* && BC*: max( 1, ((width+3)/4)
) * block-size
// *8*8_*8*8 && UYVY && YUY2:
((width+1) >> 1) * 4
// (width * bits-per-pixel + 7)/8
(divide by 8 for byte alignment, whatever that means) DWORD 24 depth;
//. Depth of a volume texture (in pixels), garbage if no volume data DWORD 28
mipMapCount; //. number of mipmaps, garbage if no pixel data DWORD 32
reserved1[11]; //. unused DWORD 76 Size; //. size of
the following 32 bytes (PIXELFORMAT) DWORD 80 Flags; //.
bitflags that tells you if data is present in the file for following 28 bytes
// ALPHAPIXELS 0x1
// ALPHA 0x2
// FOURCC 0x4
// RGB 0x40
// YUV 0x200
// LUMINANCE 0x20000
DWORD 84 FourCC; //. File format: DXT1, DXT2, DXT3, DXT4,
DXT5, DX10. DWORD 88 RGBBitCount; //. Bits per pixel DWORD 92
RBitMask; //. Bit mask for R channel DWORD 96 GBitMask; //.
Bit mask for G channel DWORD 100 BBitMask; //. Bit mask for B
channel DWORD 104 ABitMask; //. Bit mask for A channel DWORD
108 caps; //. 0x1000 for a texture w/o mipmaps
// 0x401008 for a texture w/ mipmaps
// 0x1008 for a cube map
DWORD 112 caps2; //. bitflags that tells you if data is
present in the file
// CUBEMAP 0x200 Required
for a cube map.
// CUBEMAP_POSITIVEX 0x400 Required
when these surfaces are stored in a cube map.
// CUBEMAP_NEGATIVEX 0x800 ^
// CUBEMAP_POSITIVEY 0x1000 ^
// CUBEMAP_NEGATIVEY 0x2000 ^
// CUBEMAP_POSITIVEZ 0x4000 ^
// CUBEMAP_NEGATIVEZ 0x8000 ^
// VOLUME 0x200000
Required for a volume texture. DWORD 114 caps3; //. unused
DWORD 116 caps4; //. unused
DWORD 120 reserved2; //. unused
*/
struct PixelFormatHeader
{
enum class FlagBits : uint32_t
{
AlphaPixels = 0x1,
Alpha = 0x2,
FourCC = 0x4,
Rgb = 0x40,
Yuv = 0x200,
Luminance = 0x20000,
};
uint32_t dwSize;
FlagBits dwFlags;
char dwFourCC[4];
uint32_t dwRGBBitCount;
uint32_t dwRBitMask;
uint32_t dwGBitMask;
uint32_t dwBBitMask;
uint32_t dwABitMask;
};
struct Header
{
enum class FlagBits : uint32_t
{
Caps = 0x1,
Height = 0x2,
Width = 0x4,
Pitch = 0x8,
PixelFormat = 0x1000,
MipmapCount = 0x20000,
LinearSize = 0x80000,
Depth = 0x800000,
Texture = Caps | Height | Width | PixelFormat,
Mipmap = MipmapCount,
Volume = Depth,
};
enum class Caps_bits : uint32_t
{
Complex = 0x8,
Mipmap = 0x400000,
Texture = 0x1000,
};
enum class Caps2_bits : uint32_t
{
Cubemap = 0x200,
CubemapPositiveX = 0x400,
CubemapNegativeX = 0x800,
CubemapPositiveY = 0x1000,
CubemapNegativeY = 0x2000,
CubemapPositiveZ = 0x4000,
CubemapNegativeZ = 0x8000,
Volume = 0x200000,
CubemapAllFaces = CubemapPositiveX | CubemapNegativeX |
CubemapPositiveY | CubemapNegativeY |
CubemapPositiveZ | CubemapNegativeZ,
};
char fourCC[4];
FlagBits dwSize;
uint32_t dwFlags;
uint32_t dwHeight;
uint32_t dwWidth;
uint32_t dwPitchOrLinearSize;
uint32_t dwDepth;
uint32_t dwMipMapCount;
uint32_t dwReserved1[11];
PixelFormatHeader ddspf;
Caps_bits dwCaps;
Caps2_bits dwCaps2;
uint32_t dwCaps3;
uint32_t dwCaps4;
uint32_t dwReserved2;
};
enum class Format : uint32_t
{
UNKNOWN,
R32G32B32A32_TYPELESS,
R32G32B32A32_FLOAT,
R32G32B32A32_UINT,
R32G32B32A32_SINT,
R32G32B32_TYPELESS,
R32G32B32_FLOAT,
R32G32B32_UINT,
R32G32B32_SINT,
R16G16B16A16_TYPELESS,
R16G16B16A16_FLOAT,
R16G16B16A16_UNORM,
R16G16B16A16_UINT,
R16G16B16A16_SNORM,
R16G16B16A16_SINT,
R32G32_TYPELESS,
R32G32_FLOAT,
R32G32_UINT,
R32G32_SINT,
R32G8X24_TYPELESS,
D32_FLOAT_S8X24_UINT,
R32_FLOAT_X8X24_TYPELESS,
X32_TYPELESS_G8X24_UINT,
R10G10B10A2_TYPELESS,
R10G10B10A2_UNORM,
R10G10B10A2_UINT,
R11G11B10_FLOAT,
R8G8B8A8_TYPELESS,
R8G8B8A8_UNORM,
R8G8B8A8_UNORM_SRGB,
R8G8B8A8_UINT,
R8G8B8A8_SNORM,
R8G8B8A8_SINT,
R16G16_TYPELESS,
R16G16_FLOAT,
R16G16_UNORM,
R16G16_UINT,
R16G16_SNORM,
R16G16_SINT,
R32_TYPELESS,
D32_FLOAT,
R32_FLOAT,
R32_UINT,
R32_SINT,
R24G8_TYPELESS,
D24_UNORM_S8_UINT,
R24_UNORM_X8_TYPELESS,
X24_TYPELESS_G8_UINT,
R8G8_TYPELESS,
R8G8_UNORM,
R8G8_UINT,
R8G8_SNORM,
R8G8_SINT,
R16_TYPELESS,
R16_FLOAT,
D16_UNORM,
R16_UNORM,
R16_UINT,
R16_SNORM,
R16_SINT,
R8_TYPELESS,
R8_UNORM,
R8_UINT,
R8_SNORM,
R8_SINT,
A8_UNORM,
R1_UNORM,
R9G9B9E5_SHAREDEXP,
R8G8_B8G8_UNORM,
G8R8_G8B8_UNORM,
BC1_TYPELESS,
BC1_UNORM,
BC1_UNORM_SRGB,
BC2_TYPELESS,
BC2_UNORM,
BC2_UNORM_SRGB,
BC3_TYPELESS,
BC3_UNORM,
BC3_UNORM_SRGB,
BC4_TYPELESS,
BC4_UNORM,
BC4_SNORM,
BC5_TYPELESS,
BC5_UNORM,
BC5_SNORM,
B5G6R5_UNORM,
B5G5R5A1_UNORM,
B8G8R8A8_UNORM,
B8G8R8X8_UNORM,
R10G10B10_XR_BIAS_A2_UNORM,
B8G8R8A8_TYPELESS,
B8G8R8A8_UNORM_SRGB,
B8G8R8X8_TYPELESS,
B8G8R8X8_UNORM_SRGB,
BC6H_TYPELESS,
BC6H_UF16,
BC6H_SF16,
BC7_TYPELESS,
BC7_UNORM,
BC7_UNORM_SRGB,
AYUV,
Y410,
Y416,
NV12,
P010,
P016,
_420_OPAQUE,
YUY2,
Y210,
Y216,
NV11,
AI44,
IA44,
P8,
A8P8,
B4G4R4A4_UNORM,
P208,
V208,
V408,
SAMPLER_FEEDBACK_MIN_MIP_OPAQUE,
SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE,
FORCE_UINT
};
enum class ResourceDim : uint32_t
{
UNKNOWN,
BUFFER,
TEXTURE1D,
TEXTURE2D,
TEXTURE3D
};
enum class MiscFlags2 : uint32_t
{
ALPHA_MODE_UNKNOWN = 0x0,
ALPHA_MODE_STRAIGHT = 0x1,
ALPHA_MODE_PREMULTIPLIED = 0x2,
ALPHA_MODE_OPAQUE = 0x3,
ALPHA_MODE_CUSTOM = 0x4,
};
struct Header_DXT10
{
Format dxgiFormat;
ResourceDim resourceDimension;
uint32_t miscFlag;
uint32_t arraySize;
MiscFlags2 miscFlags2;
};
static_assert(sizeof(Header) == 128);
cdm::Texture2D texture_loadDDS(const char* path, cdm::TextureFactory& factory,
cdm::CommandBufferPool& pool,
VkImageLayout outputLayout)
{
// lay out variables to be used
Header header;
memset(&header, 0xcccc, sizeof(header));
Header_DXT10 header10;
memset(&header10, 0xcccc, sizeof(header10));
uint32_t width;
uint32_t height;
uint32_t mipmapCount;
uint32_t blockSize;
VkFormat format;
uint32_t w;
uint32_t h;
std::vector<std::byte> buffer;
// GLuint tid = 0;
cdm::Texture2D texture;
// open the DDS file for binary reading and get file size
FILE* f;
if ((f = fopen(path, "rb")) == 0)
return texture;
fseek(f, 0, SEEK_END);
long file_size = ftell(f);
fseek(f, 0, SEEK_SET);
// allocate new unsigned char space with 4 (file code) + 124 (header size)
// bytes read in 128 bytes from the file
fread(&header, 1, sizeof(header), f);
// compare the `DDS ` signature
if (memcmp(&header, "DDS ", 4) != 0)
goto exit;
//*
// extract height, width, and amount of mipmaps - yes it is stored height
// then width
height = header.dwHeight;
width = header.dwWidth;
mipmapCount = header.dwMipMapCount;
factory.setWidth(width);
factory.setHeight(height);
// factory.setMipLevels(mipmapCount);
factory.setMipLevels(1);
size_t bufferSize = file_size - 128;
// figure out what format to use for what fourCC file type it is
// block size is about physical chunk storage of compressed data in file
// (important)
if (char(header.ddspf.dwFourCC[0]) == 'D')
{
switch (char(header.ddspf.dwFourCC[3]))
{
case '1': // DXT1
format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK;
blockSize = 8;
break;
case '3': // DXT3
format = VK_FORMAT_BC3_UNORM_BLOCK;
blockSize = 16;
break;
case '5': // DXT5
format = VK_FORMAT_BC5_UNORM_BLOCK;
blockSize = 16;
break;
case '0': // DX10
// unsupported, else will error
// as it adds sizeof(struct DDS_HEADER_DXT10) between pixels
// so, buffer = malloc((file_size - 128) - sizeof(struct
// DDS_HEADER_DXT10));
fread(&header10, 1, sizeof(header10), f);
if (header10.dxgiFormat == Format::R32G32B32A32_FLOAT)
{
format = VK_FORMAT_R32G32B32A32_SFLOAT;
blockSize = 16;
}
else if (header10.dxgiFormat == Format::R32G32_FLOAT)
{
format = VK_FORMAT_R32G32_SFLOAT;
blockSize = 8;
}
bufferSize -= sizeof(Header_DXT10);
break;
default: goto exit;
}
}
else // BC4U/BC4S/ATI2/BC55/R8G8_B8G8/G8R8_G8B8/UYVY-packed/YUY2-packed
// unsupported
goto exit;
factory.setFormat(format);
// allocate new unsigned char space with file_size - (file_code +
// header_size) magnitude read rest of file
buffer.resize(bufferSize);
// buffer = (unsigned char*)malloc(file_size - 128);
// if(buffer == 0)
// goto exit;
fread(buffer.data(), 1, file_size, f);
// prepare new incomplete texture
// glGenTextures(1, &tid);
// if(tid == 0)
// goto exit;
// texture = factory.createTexture2D();
// bind the texture
// make it complete by specifying all needed parameters and ensuring all
// mipmaps are filled
// glBindTexture(GL_TEXTURE_2D, tid);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipMapCount-1); //
// opengl likes array length of mipmaps glTexParameteri(GL_TEXTURE_2D,
// GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,
// GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // don't forget to
// enable mipmaping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
// GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
// GL_REPEAT);
// prepare some variables
unsigned int offset = 0;
unsigned int size = 0;
w = width;
h = height;
// loop through sending block at a time with the magic formula
// upload to opengl properly, note the offset transverses the pointer
// assumes each mipmap is 1/2 the size of the previous mipmap
// std::cout << path << " has " << mipmapCount << " mipLevels" <<
// std::endl;
std::cout << path << std::endl;
VkBufferImageCopy region{};
// region.imageExtent.width = width;
// region.imageExtent.height = height;
region.imageExtent.depth = 1;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
// region.imageSubresource.mipLevel = 0;
/*
for (unsigned int i = 0; i < mipmapCount; i++)
{
if (w == 0 || h == 0)
{ // discard any odd mipmaps 0x1 0x2 resolutions
std::cout << "odd mipmap " << i << "/" << mipmapCount << " (" << w
<< ";" << h << ")" << std::endl;
// mipmapCount--;
// continue;
}
size = ((w + 3) / 4) * ((h + 3) / 4) * blockSize;
//VkBufferImageCopy region{};
region.imageExtent.width = w;
region.imageExtent.height = h;
//region.imageExtent.depth = 1;
//region.bufferRowLength = 0;
//region.bufferImageHeight = 0;
//region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
//region.imageSubresource.baseArrayLayer = 0;
//region.imageSubresource.layerCount = 1;
region.imageSubresource.mipLevel = i;
//if (i == mipmapCount - 2)
{
std::cout << "loading level " << i << "/" << mipmapCount << " ("
<< w << ";" << h << ")" << std::endl;
factory.setWidth(w);
factory.setHeight(h);
texture = factory.createTexture2D();
region.imageSubresource.mipLevel = 0;
texture.uploadData(buffer.data() + offset, size, region,
VK_IMAGE_LAYOUT_UNDEFINED, outputLayout, pool);
if (texture == nullptr)
{
std::cout << "what" << std::endl;
}
break;
}
// glCompressedTexImage2D(GL_TEXTURE_2D, i, format, w, h, 0, size,
// buffer + offset);
offset += size;
w /= 2;
h /= 2;
}
//*/
if (texture.image() == nullptr)
{
region.imageExtent.width = width;
region.imageExtent.height = height;
region.imageSubresource.mipLevel = 0;
std::cout << "loading level " << 0 << "/" << mipmapCount << " ("
<< width << ";" << height << ")" << std::endl;
//size = ((width + 3) / 4) * ((width + 3) / 4) * blockSize;
size = width * width * blockSize;
std::cout << "blockSize " << blockSize << std::endl;
std::cout << "size " << ((width + 3) / 4) << " * " << ((width + 3) / 4)
<< " * " << blockSize << std::endl;
factory.setWidth(width);
factory.setHeight(height);
texture = factory.createTexture2D();
texture.uploadData(buffer.data(), size, region,
VK_IMAGE_LAYOUT_UNDEFINED, outputLayout, pool);
}
// discard any odd mipmaps, ensure a complete texture
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipMapCount-1);
// unbind
// glBindTexture(GL_TEXTURE_2D, 0);
//*/
// easy macro to get out quick and uniform (minus like 15 lines of bulk)
exit:
// free(buffer);
// free(header);
fclose(f);
// return tid;
return texture;
}
| 29.305026 | 98 | 0.603288 |
cfff7dbf1afee58f5dd3a04d6f58c871730fa696 | 712 | cpp | C++ | cpp/stl/05_insert.cpp | Trickness/pl_learning | 53c10490aed1ba4a02b14aae4890321ad099cc60 | [
"Unlicense"
] | null | null | null | cpp/stl/05_insert.cpp | Trickness/pl_learning | 53c10490aed1ba4a02b14aae4890321ad099cc60 | [
"Unlicense"
] | null | null | null | cpp/stl/05_insert.cpp | Trickness/pl_learning | 53c10490aed1ba4a02b14aae4890321ad099cc60 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <iterator>
using namespace std;
int iArray[5] = {1,2,3,4,5};
void Display(list<int> &a , const char* s){
cout << s << endl;
copy(a.begin(),a.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
int main(){
list<int> iList;
// Copy iArray backwards into iList
copy(iArray,iArray + 5, back_inserter(iList));
Display(iList,"Before find and copy");
// Locate value 3 in iList
auto p = find(iList.begin(),iList.end(),3);
// Copy first two iArray values to iList ahead of p
copy(iArray, iArray + 2, inserter(iList,p));
Display(iList,"After find and copy");
return 0;
}
| 22.25 | 62 | 0.629213 |
320137136c52e931b584258a161d058676af59d5 | 3,292 | hpp | C++ | yelp.hpp | jkatsioloudes/Yelp_ObjectRelationalMapping | 596bef42d9623f2e46b6f5e711493687c35822f2 | [
"MIT"
] | 1 | 2021-02-10T20:35:09.000Z | 2021-02-10T20:35:09.000Z | yelp.hpp | jkatsioloudes/Yelp-ORM | 596bef42d9623f2e46b6f5e711493687c35822f2 | [
"MIT"
] | null | null | null | yelp.hpp | jkatsioloudes/Yelp-ORM | 596bef42d9623f2e46b6f5e711493687c35822f2 | [
"MIT"
] | null | null | null | #include <memory>
#include <odb/core.hxx>
#include <odb/lazy-ptr.hxx>
#include <set>
#include <string>
#pragma db view
class StarCount{
public:
int stars;
int count;
};
#pragma db view query("select top 1 text, last_elapsed_time from sys.dm_exec_query_stats cross apply sys.dm_exec_sql_text(sql_handle) order by last_execution_time desc")
class LastQueryTime{
public:
std::string text;
long elapsed_time;
};
// ---------------------------------------------
// No need to change anything above this line
// ---------------------------------------------
// out of scope declarations predeclared here.
class hour;
class category;
class business;
class review;
class user;
class photo;
# pragma db object no_id
class attribute {
public:
std::string name;
std::string value;
odb::lazy_ptr<business> business_id;
};
# pragma db object
class business {
public:
# pragma db id
std::string id;
std::string name;
std::string neighborhood;
std::string address;
std::string city;
std::string state;
std::string postal_code;
float latitude;
float longitude;
float stars;
int review_count;
short int is_open;
# pragma db inverse(business_id)
std::vector<std::shared_ptr<hour>> business_hours;
# pragma db inverse(business_id)
std::vector<std::shared_ptr<review>> business_reviews;
# pragma db inverse(business_id)
std::vector<std::shared_ptr<photo>> business_photos;
};
# pragma db object no_id
class category {
public:
std::string category;
odb::lazy_ptr<business> business_id;
};
# pragma db object no_id
class checkin {
public:
std::string date;
int count;
odb::lazy_ptr<business> business_id;
};
# pragma db object no_id
class elite_years {
public:
int year;
odb::lazy_ptr<user> user_id;
};
# pragma db object table("friend") // because 'friend' is a reserved C++ keyword.
class friends {
public:
# pragma db id
std::string friend_id;
odb::lazy_ptr<user> user_id;
};
#pragma db object table("hours") // because overlaps with the attribute name.
class hour {
public:
# pragma db id
int id;
std::string hours;
odb::lazy_ptr<business> business_id;
};
# pragma db object
class photo {
public:
# pragma db id
std::string id;
std::string caption;
std::string label;
odb::lazy_ptr<business> business_id;
};
# pragma db object
class review {
public:
# pragma db id
std::string id;
int stars;
std::string date;
std::string text;
int useful;
int funny;
int cool;
odb::lazy_ptr<business> business_id;
odb::lazy_ptr<user> user_id;
};
# pragma db object no_id
class tip {
public:
std::string text;
std::string date;
int likes;
odb::lazy_ptr<business> business_id;
odb::lazy_ptr<user> user_id;
};
# pragma db object
class user {
public:
# pragma db id
std::string id;
std::string name;
int review_count;
std::string yelping_since;
int useful;
int funny;
int cool;
int fans;
float average_stars;
int compliment_hot;
int compliment_more;
int compliment_profile;
int compliment_cute;
int compliment_list;
int compliment_note;
int compliment_plain;
int compliment_cool;
int compliment_funny;
int compliment_writer;
int compliment_photos;
# pragma db inverse(user_id)
std::vector<std::shared_ptr<review>> user_reviews;
# pragma db inverse(user_id)
std::vector<std::shared_ptr<friends>> user_friends;
};
| 18.391061 | 169 | 0.712333 |
3202fd54536a01efd617e80e180b3288cabceecd | 2,511 | cc | C++ | src/developer/debug/zxdb/symbols/identifier_unittest.cc | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | src/developer/debug/zxdb/symbols/identifier_unittest.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | src/developer/debug/zxdb/symbols/identifier_unittest.cc | bootingman/fuchsia2 | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia 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 "src/developer/debug/zxdb/symbols/identifier.h"
#include "gtest/gtest.h"
#include "src/developer/debug/zxdb/common/err.h"
namespace zxdb {
TEST(Identifier, GetName) {
// Empty.
Identifier unqualified;
EXPECT_EQ("", unqualified.GetFullName());
// Single name with no "::" at the beginning.
unqualified.AppendComponent("First");
EXPECT_EQ("First", unqualified.GetFullName());
std::vector<std::string> expected_index = {"First"};
// Single name with a "::" at the beginning.
Identifier qualified(Identifier::kGlobal, "First");
EXPECT_EQ("::First", qualified.GetFullName());
// Append some template stuff.
qualified.AppendComponent("Second", {"int", "Foo"});
EXPECT_EQ("::First::Second<int, Foo>", qualified.GetFullName());
expected_index.push_back("Second<int, Foo>");
}
TEST(Identifier, GetScope) {
std::string name1("Name1");
std::string name2("Name2");
std::string name3("Name3");
// "" -> "".
Identifier empty;
EXPECT_EQ("", empty.GetScope().GetDebugName());
// "::" -> "::".
Identifier scope_only(Identifier::kGlobal);
EXPECT_EQ("::", scope_only.GetScope().GetDebugName());
// "Name1" -> "".
Identifier name_only(Identifier::kRelative, Identifier::Component(name1));
EXPECT_EQ("", name_only.GetScope().GetDebugName());
// ::Name1" -> "::".
Identifier scoped_name(Identifier::kGlobal, Identifier::Component(name1));
EXPECT_EQ("::", scoped_name.GetScope().GetDebugName());
// "Name1::Name2" -> "Name1".
Identifier two_names(Identifier::kRelative, Identifier::Component(name1));
two_names.AppendComponent(Identifier::Component(name2));
EXPECT_EQ("\"Name1\"", two_names.GetScope().GetDebugName());
// "::Name1::Name2" -> "::Name1".
Identifier two_scoped_names(Identifier::kGlobal,
Identifier::Component(name1));
two_scoped_names.AppendComponent(Identifier::Component(name2));
EXPECT_EQ("::\"Name1\"", two_scoped_names.GetScope().GetDebugName());
// "Name1::Name2::Name3" -> "Name1::Name2".
Identifier three_scoped_names(Identifier::kRelative,
Identifier::Component(name1));
three_scoped_names.AppendComponent(name2);
three_scoped_names.AppendComponent(name3);
EXPECT_EQ("\"Name1\"; ::\"Name2\"",
three_scoped_names.GetScope().GetDebugName());
}
} // namespace zxdb
| 33.932432 | 76 | 0.680207 |
3205b13f2b67c5c04db23a69f1ebf07a9e31ed5d | 3,456 | cpp | C++ | 1082_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 1082_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 1082_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | // Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
int t;
cin>>t;
string s;
cin>>s;
vector<int>v(t,0);
if(s[0]=='G')
v[0]=1;
else
v[0]=0;
for(int i=1;i<t;i++)
{
if(s[i]=='G' && s[i-1]=='G')
v[i]=v[i-1]+1;
if(s[i]=='G' && s[i-1]=='S')
v[i]=1;
}
for(int i=t-2;i>=0;i--)
{
if(v[i]!=0)
v[i]=max(v[i+1],v[i]);
}
int mx=*max_element(v.begin(),v.end());
//if can swap is >=2 then i can swap the current s with any of the g
vector<int>prefix(t,0),suffix(t,0);
if(s[0]=='G')
prefix[0]=1;
for(int i=1;i<t;i++)
{
if(s[i]=='G')
prefix[i]=prefix[i-1]+1;
else
prefix[i]=prefix[i-1];
}
if(s[t-1]=='G')
suffix[t-1]=1;
for(int i=t-2;i>=0;i--)
{
if(s[i]=='G')
suffix[i]=suffix[i+1]+1;
else
suffix[i]=suffix[i+1];
}
//print
// for(int i=0;i<t;i++)
// cout<<v[i]<<" ";
// cout<<endl;
// for(int i=0;i<t;i++)
// cout<<prefix[i]<<" ";
// cout<<endl;
// for(int i=0;i<t;i++)
// cout<<suffix[i]<<" ";
// cout<<endl;
//print over
for(int i=1;i<t-1;i++)
{
if(v[i]==0 && v[i-1]!=0 && v[i+1]!=0)
{
//check if we have an extra g to swap beyond the 2 consective seq
bool ok=false;
int look_back=i-v[i-1]-1;
int look_front=i+v[i+1]+1;
//cout<<i<<" "<<look_back<<" "<<look_front<<endl;
if(look_back>=0 && prefix[look_back]>0)
ok=true;
if(look_front<t && suffix[look_front]>0)
ok=true;
if(ok)
mx=max(mx,v[i-1]+v[i+1]+1);
else
mx=max(mx,v[i-1]+v[i+1]);
}
//case 1 GSSGGGG
//if here i replce the first S i get the size of 2 if I replace the second S i get 4
else if(v[i]==0 && v[i-1]!=0)
{
//we are extending the last segment
int look_front=i;
int look_back=i-v[i-1]-1;
bool ok=false;
if(suffix[look_front]>0)
ok=true;
if(look_back>=0 && prefix[look_back]>0)
ok=true;
if(ok)
mx=max(mx,v[i-1]+1);
}
else if(v[i]==0 && v[i+1]!=0)
{
bool ok=false;
int look_front=i+v[i+1]+1;
int look_back=i;
if(prefix[look_back]>0)
ok=true;
if(look_front<t && suffix[look_front]>0)
ok=true;
if(ok)
mx=max(mx,v[i+1]+1);
}
}
cout<<mx<<endl;
return 0;
} | 23.510204 | 106 | 0.530093 |
32068b4b1824704c656cc7de0c98cd0424582e15 | 10,626 | cpp | C++ | main.cpp | CKilburn12/Tic-Tac-Done-To-Death | d952f194f02efa8274bbf73aa097766c5354264d | [
"MIT"
] | null | null | null | main.cpp | CKilburn12/Tic-Tac-Done-To-Death | d952f194f02efa8274bbf73aa097766c5354264d | [
"MIT"
] | null | null | null | main.cpp | CKilburn12/Tic-Tac-Done-To-Death | d952f194f02efa8274bbf73aa097766c5354264d | [
"MIT"
] | 1 | 2020-10-25T23:10:58.000Z | 2020-10-25T23:10:58.000Z | /**
This is a pretty basic command line Tic-Tac-Toe game.
Its been totally done to death, but I felt like it would
be a relatively easy way to apply what I've learned with
C++ so far.
Author: CKilburn12 (Colin Kilburn)
**/
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
using namespace std;
/**
The board class serves to create a board object with
ways to check if anyone has won the game of Tic-Tac-Toe
**/
class Board
{
private:
//Starts out with a blank board.
vector<vector<string>> board = {{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}};
public:
/**
Returns the 2D board vector.
**/
vector<vector<string>> getArray()
{
return this->board;
}
/**
Ensures a valid move by the player, if it is,
the board is updated and true is returned. Otherwise it does nothing
and returns false.
**/
bool setArray(int row, int col, string player)
{
bool safeRow = row < 3 && row >= 0;
bool safeCol = col < 3 && row >=0;
bool safeIndex = safeRow && safeCol;
if(safeIndex)
{
if(this->board[row][col] == " ") //checking for a blank place within the board.
{
this->board[row][col] = player;
return true;
}
}
return false;
}
/**
Calls the functions to check if someone has won on rows, columns, or diagonal.
**/
bool checkWinStatus()
{
return (this->checkRow() || this->checkCol() || this->checkDiag());
}
/**
Checks if either player has won on any of the three rows.
**/
bool checkRow()
{
for(int col = 0; col<3; col++)
{
bool twoEqual = !this->board[col][0].compare(this->board[col][1]);
bool threeEqual = !this->board[col][1].compare(this->board[col][2]);
bool notBlank = this->board[col][0].compare(" ");
if(twoEqual && threeEqual && notBlank)
return true;
}
return false;
}
/**
Checks if either player has won on any of the three columns.
**/
bool checkCol()
{
for(int row = 0; row<3; row++)
{
bool twoEqual = !this->board[0][row].compare(this->board[1][row]);
bool threeEqual = !this->board[1][row].compare(this->board[2][row]);
bool notBlank = this->board[0][row].compare(" ");
if(twoEqual && threeEqual && notBlank)
return true;
}
return false;
}
/**
Checks if either player has won on either diagonal.
**/
bool checkDiag()
{
bool leftToRight{false};
bool rightToLeft{false};
bool twoEqual{false};
bool threeEqual{false};
bool notBlank = this->board[1][1].compare(" ");
twoEqual = !this->board[0][0].compare(this->board[1][1]);
threeEqual = !this->board[2][2].compare(this->board[1][1]);
leftToRight = twoEqual && threeEqual;
twoEqual = !this->board[0][2].compare(this->board[1][1]);
threeEqual = !this->board[2][0].compare(this->board[1][1]);
rightToLeft = twoEqual && threeEqual;
return ((rightToLeft || leftToRight) && notBlank);
}
bool checkUnwinnable()
{
bool XPresent{false};
bool OPresent{false};
vector<bool> validRows(8);
vector<vector<string>> sidewaysBoard = {{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}};
vector<vector<string>> diagonals = {{" ", " ", " "}, {" ", " ", " "}};
for(int row = 0; row < 3; row++)
{
for(int col = 0; col < 3; col++)
{
sidewaysBoard[row][col] = this->board[col][row];
}
}
for(int i = 0; i < 3; i++)
{
XPresent = (find(this->board[i].begin(), this->board[i].end(), "X") != this->board[i].end());
OPresent = (find(this->board[i].begin(), this->board[i].end(), "O") != this->board[i].end());
validRows[i] = XPresent && OPresent;
XPresent = (find(sidewaysBoard[i].begin(), sidewaysBoard[i].end(), "X") != sidewaysBoard[i].end());
OPresent = (find(sidewaysBoard[i].begin(), sidewaysBoard[i].end(), "O") != sidewaysBoard[i].end());
validRows[i+3] = XPresent && OPresent;
diagonals[0][i] = this->board[i][i];
diagonals[1][i] = sidewaysBoard[i][i];
}
XPresent = (find(diagonals[0].begin(), diagonals[0].end(), "X") != diagonals[0].end());
OPresent = (find(diagonals[0].begin(), diagonals[0].end(), "O") != diagonals[0].end());
validRows[6] = XPresent && OPresent;
XPresent = (find(diagonals[1].begin(), diagonals[1].end(), "X") != diagonals[1].end());
OPresent = (find(diagonals[1].begin(), diagonals[1].end(), "O") != diagonals[1].end());
validRows[7] = XPresent && OPresent;
return accumulate(validRows.begin(), validRows.end(), 0 ) >= 7;
}
};
/**
Overloading the << operator for a board object to display
the values divided by | characters.
**/
ostream& operator<<(ostream& os, Board& b)
{
vector<vector<string>> board = b.getArray();
for(int i = 0; i < 3; i++)
{
os << "|";
for(int j = 0; j < 3; j++)
{
os << board[i][j] + "|";
}
os << "\n";
}
return os;
}
class Oponent
{
protected:
Board aiBoard;
public:
Board getBoard()
{
return aiBoard;
}
void setBoard(Board& b)
{
aiBoard = b;
}
vector<string> flattenVector()
{
vector<string> flatVector;
vector<vector<string>> tempVector = this->aiBoard.getArray();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
string temp = tempVector[i][j];
flatVector.push_back(temp);
}
}
return flatVector;
}
};
class easyOponent: public Oponent
{
public:
void move()
{
int xPos{};
int yPos{};
bool validMove{false};
do
{
xPos = rand()%3;
yPos = rand()%3;
validMove = this->aiBoard.setArray(xPos, yPos, "O");
} while(!validMove);
system("clear");
cout << this->aiBoard;
}
};
/**
This function takes input of rows and cols and puts it into a map.
Using a map is probably overkill for this, but I'm trying to learn C++
**/
map<string, int> userInput()
{
map<string, int> position;
int row{};
int col{};
cout << "Row: ";
cin >> row;
cout << "Column: ";
cin >> col;
position.insert(make_pair("Row", --row));
position.insert(make_pair("Col", --col));
return position;
}
/**
This goes through everything that needs to happen on each turn,
including clearing the screen, displaying the board, and taking the input
**/
void playerTurn(string player, Board& b)
{
map<string, int> position;
string playerName{};
bool validMove{};
if(player == "X") playerName = "Player 1";
else playerName = "Player 2";
do
{
cout << playerName << "\n";
position = userInput();
validMove = b.setArray(position["Row"], position["Col"], player);
system("clear");
cout << b;
if(!validMove) cout << "Not a valid move!\n";
} while(!validMove);
}
void twoPlayer(Board &newBoard)
{
while(true)
{
playerTurn("X", newBoard);
if(newBoard.checkWinStatus())
{
system("clear");
cout << "Player 1 Wins!\n";
break;
}
if(newBoard.checkUnwinnable())
{
system("clear");
cout << "Tie!\n";
break;
}
playerTurn("O", newBoard);
if(newBoard.checkWinStatus())
{
system("clear");
cout << "Player 2 Wins!\n";
break;
}
if(newBoard.checkUnwinnable())
{
system("clear");
cout << "Tie!\n";
break;
}
}
}
void playEasyAI(Board &newBoard)
{
easyOponent AI;
while(true)
{
playerTurn("X", newBoard);
if(newBoard.checkWinStatus())
{
system("clear");
cout << "Player 1 Wins!\n";
break;
}
if(newBoard.checkUnwinnable())
{
system("clear");
cout << "Tie!\n";
break;
}
AI.setBoard(newBoard);
AI.move();
newBoard = AI.getBoard();
if(newBoard.checkWinStatus())
{
system("clear");
cout << "Player 2 Wins!\n";
break;
}
if(newBoard.checkUnwinnable())
{
system("clear");
cout << "Tie!\n";
break;
}
}
}
/**
Main function,
just shows the blank board then starts calling the turn function.
Stops running once someone wins.
**/
int main()
{
Board newBoard;
system("clear");
int mode{};
cout << "What mode do you want to play:" << endl;
cout << "(1) Two Player\n (2) Easy AI" << endl;
cin >> mode;
cout << newBoard;
switch(mode)
{
case 1:
twoPlayer(newBoard);
break;
case 2:
playEasyAI(newBoard);
break;
}
cout << newBoard;
return 0;
} | 24.885246 | 115 | 0.455487 |
3208164d79e66be477ab220e6442a26586383448 | 8,075 | cpp | C++ | Leaf/src/Application.cpp | miki134/Leaf | 1fc9857c8e803bf0f029fbe93ab473a17fb56719 | [
"Apache-2.0"
] | null | null | null | Leaf/src/Application.cpp | miki134/Leaf | 1fc9857c8e803bf0f029fbe93ab473a17fb56719 | [
"Apache-2.0"
] | null | null | null | Leaf/src/Application.cpp | miki134/Leaf | 1fc9857c8e803bf0f029fbe93ab473a17fb56719 | [
"Apache-2.0"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
const char* vertexShaderSource = R"(
#version 330 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texPos;
out vec2 texPosFrag;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(pos, 1.0f);
texPosFrag = texPos;
}
)";
const char* fragmentShaderSource = R"(
#version 330 core
in vec2 texPosFrag;
out vec4 color;
uniform sampler2D CPUtexture;
void main()
{
color = texture(CPUtexture, texPosFrag);
}
)";
static glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f);
static glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
static glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
static float delta_time;
static float last_frame;
static float pitch;
static float yaw = -90.0f;
static float lastX;
static float lastY;
static bool firstMouse = true;
void FramebufferSizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void MouseCallback(GLFWwindow* window, double xPos, double yPos)
{
if (firstMouse)
{
lastX = xPos;
lastY = yPos;
firstMouse = false;
}
float xOffset = float(xPos) - lastX;
float yOffset = float(yPos) - lastY;
lastX = xPos;
lastY = yPos;
float sensitivity = 0.1f;
xOffset *= sensitivity;
yOffset *= sensitivity;
pitch += yOffset;
yaw += xOffset;
if (pitch > 89.9f)
pitch = 89.9f;
if (pitch < -89.9f)
pitch = -89.9f;
glm::vec3 direction;
direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
direction.y = sin(glm::radians(-pitch));
direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
cameraFront = glm::normalize(direction);
}
void ProcessInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
const float cameraSpeed = 2.5f * delta_time;
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
cameraPos -= cameraFront * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
cameraPos += cameraFront * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;
}
int CheckShaderCompilationStatus(GLuint shader)
{
int success;
char infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
return -1;
}
}
int CheckShaderProgramLinkingStatus(GLuint program)
{
int success;
char infoLog[512];
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(program, 512, NULL, infoLog);
std::cout << "Shader Program linking error" << std::endl;
return -1;
}
}
int main()
{
glfwInit();
glfwInitHint(GLFW_VERSION_MAJOR, 3);
glfwInitHint(GLFW_VERSION_MINOR, 3);
glfwInitHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "Leaf", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create a Window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initalize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, 800, 600);
glfwSetFramebufferSizeCallback(window, FramebufferSizeCallback);
glfwSetCursorPosCallback(window, MouseCallback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
CheckShaderCompilationStatus(vertexShader);
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
CheckShaderCompilationStatus(fragmentShader);
unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
CheckShaderCompilationStatus(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
unsigned int VBO, VAO;
glGenBuffers(1, &VBO);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
unsigned int soilTexture;
glGenTextures(1, &soilTexture);
glBindTexture(GL_TEXTURE_2D, soilTexture);
int width, height, nrChannels;
unsigned char* data = stbi_load("soil.jpg", &width, &height, &nrChannels, 0);
if (!data)
{
std::cout << "Failed to load texture" << std::endl;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(data);
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window))
{
auto current_frame = glfwGetTime();
delta_time = last_frame - current_frame;
last_frame = current_frame;
ProcessInput(window);
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, -2.0f));
model = glm::rotate(model, glm::radians(1.f), glm::vec3(0.7f, 0.3f, 0.4f));
glm::mat4 view = glm::mat4(1.0f);
view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
glm::mat4 projection;
projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "view"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
glClearColor(0.1f, 0.1f, 0.1f, 0.1f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteBuffers(1, &VBO);
glDeleteVertexArrays(1, &VAO);
glfwTerminate();
return 0;
} | 27.006689 | 113 | 0.681858 |
3208de8949a1662d0acd4a62337215eb51f7ad50 | 1,728 | hpp | C++ | modules/core/feature/include/opengv2/feature/FeatureBase.hpp | MobilePerceptionLab/EventCameraCalibration | debd774ac989674b500caf27641b7ad4e94681e9 | [
"Apache-2.0"
] | 22 | 2021-08-06T03:21:03.000Z | 2022-02-25T03:40:54.000Z | modules/core/feature/include/opengv2/feature/FeatureBase.hpp | MobilePerceptionLab/MultiCamCalib | 2f0e94228c2c4aea7f20c26e3e8daa6321ce8022 | [
"Apache-2.0"
] | 1 | 2022-02-25T02:55:13.000Z | 2022-02-25T15:18:45.000Z | modules/core/feature/include/opengv2/feature/FeatureBase.hpp | MobilePerceptionLab/MultiCamCalib | 2f0e94228c2c4aea7f20c26e3e8daa6321ce8022 | [
"Apache-2.0"
] | 7 | 2021-08-11T12:29:35.000Z | 2022-02-25T03:41:01.000Z | //
// Created by huangkun on 2019/12/30.
//
#ifndef OPENGV2_FEATUREBASE_HPP
#define OPENGV2_FEATUREBASE_HPP
#include <memory>
#include <Eigen/Eigen>
#include <opengv2/landmark/LandmarkBase.hpp>
namespace opengv2 {
class FeatureBase { // TODO: inherit ObservationBase
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef std::shared_ptr<FeatureBase> Ptr;
explicit FeatureBase(const Eigen::Ref<const Eigen::VectorXd> &loc) :
locBackup(loc), landmark_(LandmarkBase::Ptr()), loc_(loc), bearingVector_(Eigen::VectorXd()) {}
virtual ~FeatureBase() = default;
inline LandmarkBase::Ptr landmark() const noexcept {
return landmark_.lock();
}
/**
* @note Warning: Not thread safe.
*/
inline void setLandmark(const LandmarkBase::Ptr &lm) noexcept {
landmark_ = lm;
}
inline const Eigen::VectorXd &location() const noexcept {
return loc_;
}
/**
* @note Warning: Not thread safe.
*/
virtual inline void setLocation(const Eigen::Ref<const Eigen::VectorXd> &loc) noexcept {
loc_ = loc;
}
inline const Eigen::VectorXd &bearingVector() noexcept {
return bearingVector_;
}
/**
* @note Warning: Not thread safe.
*/
inline void setBearingVector(const Eigen::Ref<const Eigen::VectorXd> &bv) {
bearingVector_ = bv;
}
Eigen::VectorXd locBackup; // backup
protected:
std::weak_ptr<LandmarkBase> landmark_;
Eigen::VectorXd loc_;
Eigen::VectorXd bearingVector_;
};
}
#endif //OPENGV2_FEATUREBASE_HPP
| 25.043478 | 111 | 0.600116 |
320ad7582601aa0c407b9fc613bf6d96159f5191 | 518 | hpp | C++ | src/wrapper.hpp | Dreae/SourceLua | 5737eaf3d77bbd715b258df78ab101265890662c | [
"Apache-2.0"
] | null | null | null | src/wrapper.hpp | Dreae/SourceLua | 5737eaf3d77bbd715b258df78ab101265890662c | [
"Apache-2.0"
] | null | null | null | src/wrapper.hpp | Dreae/SourceLua | 5737eaf3d77bbd715b258df78ab101265890662c | [
"Apache-2.0"
] | null | null | null | #ifndef _INCLUDE_WRAPPER
#define _INCLUDE_WRAPPER
#include <ISmmPlugin.h>
#include "iplayerinfo.h"
#if SOURCE_ENGINE <= SE_DARKMESSIAH
/**
* Wrap the CCommand class so our code looks the same on all engines.
*/
class CCommand
{
public:
const char *ArgS()
{
return g_Engine->Cmd_Args();
}
int ArgC()
{
return g_Engine->Cmd_Argc();
}
const char *Arg(int index)
{
return g_Engine->Cmd_Argv(index);
}
};
#define CVAR_INTERFACE_VERSION VENGINE_CVAR_INTERFACE_VERSION
#endif
#endif // _INCLUDE_WRAPPER
| 15.69697 | 69 | 0.727799 |
320aee2d2c17261395b2ff39b854baa01a6971bb | 8,311 | cc | C++ | pigasus/software/tools/snort2lua/output_states/out_csv.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/output_states/out_csv.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | pigasus/software/tools/snort2lua/output_states/out_csv.cc | zhipengzhaocmu/fpga2022_artifact | 0ac088a5b04c5c75ae6aef25202b66b0f674acd3 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | //--------------------------------------------------------------------------
// Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License Version 2 as published
// by the Free Software Foundation. You may not use, modify or distribute
// this program under any other version of the GNU General Public License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//--------------------------------------------------------------------------
// out_csv.cc author Josh Rosenbaum <jrosenba@cisco.com>
#include <sstream>
#include <vector>
#include "conversion_state.h"
#include "helpers/converter.h"
#include "helpers/s2l_util.h"
namespace output
{
namespace
{
class AlertCsv : public ConversionState
{
public:
AlertCsv(Converter& c) : ConversionState(c) { }
bool convert(std::istringstream& data_stream) override;
};
} // namespace
bool AlertCsv::convert(std::istringstream& data_stream)
{
std::string keyword;
std::string val;
bool retval = true;
int limit;
char c = '\0';
table_api.open_top_level_table("alert_csv");
if (!(data_stream >> keyword))
return true;
table_api.add_deleted_comment("<filename> can no longer be specific");
if (!(data_stream >> keyword))
return retval;
table_api.add_diff_option_comment("csv", "fields");
// parsing the format list.
std::istringstream format(keyword);
while (std::getline(format, val, ','))
{
bool tmpval = true;
if (val == "default")
table_api.add_deleted_comment("default");
else if (val == "timestamp")
tmpval = table_api.add_list("fields", "timestamp");
else if (val == "msg")
tmpval = table_api.add_list("fields", "msg");
else if (val == "proto")
tmpval = table_api.add_list("fields", "proto");
else if (val == "ttl")
tmpval = table_api.add_list("fields", "ttl");
else if (val == "tos")
tmpval = table_api.add_list("fields", "tos");
else if (val == "trheader")
tmpval = table_api.add_deleted_comment("trheader");
else if (val == "dst")
{
table_api.add_diff_option_comment("dst", "dst_addr");
tmpval = table_api.add_list("fields", "dst_addr");
}
else if (val == "src")
{
table_api.add_diff_option_comment("src", "src_addr");
tmpval = table_api.add_list("fields", "src_addr");
}
else if (val == "sig_generator")
{
table_api.add_diff_option_comment("sig_generator", "gid");
tmpval = table_api.add_list("fields", "gid");
}
else if (val == "sig_id")
{
table_api.add_diff_option_comment("sig_id", "sid");
tmpval = table_api.add_list("fields", "sid");
}
else if (val == "sig_rev")
{
table_api.add_diff_option_comment("sig_rev", "rev");
tmpval = table_api.add_list("fields", "rev");
}
else if (val == "srcport")
{
table_api.add_diff_option_comment("srcport", "src_port");
tmpval = table_api.add_list("fields", "src_port");
}
else if (val == "dstport")
{
table_api.add_diff_option_comment("dstport", "dst_port");
tmpval = table_api.add_list("fields", "dst_port");
}
else if (val == "ethsrc")
{
table_api.add_diff_option_comment("ethsrc", "eth_src");
tmpval = table_api.add_list("fields", "eth_src");
}
else if (val == "ethdst")
{
table_api.add_diff_option_comment("ethdst", "eth_dst");
tmpval = table_api.add_list("fields", "eth_dst");
}
else if (val == "ethlen")
{
table_api.add_diff_option_comment("ethlen", "eth_len");
tmpval = table_api.add_list("fields", "eth_len");
}
else if (val == "ethtype")
{
table_api.add_diff_option_comment("ethtype", "eth_type");
tmpval = table_api.add_list("fields", "eth_type");
}
else if (val == "tcpflags")
{
table_api.add_diff_option_comment("tcpflags", "tcp_flags");
tmpval = table_api.add_list("fields", "tcp_flags");
}
else if (val == "tcpseq")
{
table_api.add_diff_option_comment("tcpseq", "tcp_seq");
tmpval = table_api.add_list("fields", "tcp_seq");
}
else if (val == "tcpack")
{
table_api.add_diff_option_comment("tcpack", "tcp_ack");
tmpval = table_api.add_list("fields", "tcp_ack");
}
else if (val == "tcplen")
{
table_api.add_diff_option_comment("tcplen", "tcp_len");
tmpval = table_api.add_list("fields", "tcp_len");
}
else if (val == "tcpwindow")
{
table_api.add_diff_option_comment("tcpwindow", "tcp_win");
tmpval = table_api.add_list("fields", "tcp_win");
}
else if (val == "dgmlen")
{
table_api.add_diff_option_comment("dgmlen", "pkt_len");
tmpval = table_api.add_list("fields", "pkt_len");
}
else if (val == "id")
{
table_api.add_diff_option_comment("id", "ip_id");
tmpval = table_api.add_list("fields", "ip_id");
}
else if (val == "iplen")
{
table_api.add_diff_option_comment("iplen", "ip_len");
tmpval = table_api.add_list("fields", "ip_len");
}
else if (val == "icmptype")
{
table_api.add_diff_option_comment("icmptype", "icmp_type");
tmpval = table_api.add_list("fields", "icmp_type");
}
else if (val == "icmpcode")
{
table_api.add_diff_option_comment("icmpcode", "icmp_code");
tmpval = table_api.add_list("fields", "icmp_code");
}
else if (val == "icmpid")
{
table_api.add_diff_option_comment("icmpid", "icmp_id");
tmpval = table_api.add_list("fields", "icmp_id");
}
else if (val == "icmpseq")
{
table_api.add_diff_option_comment("icmpseq", "icmp_seq");
tmpval = table_api.add_list("fields", "icmp_seq");
}
else if (val == "udplength")
{
table_api.add_diff_option_comment("udplength", "udp_len");
tmpval = table_api.add_list("fields", "udp_len");
}
else
{
tmpval = false;
}
if (!tmpval)
{
data_api.failed_conversion(data_stream, val);
retval = false;
}
}
if (!(data_stream >> limit))
return retval;
if (data_stream >> c)
{
if (limit <= 0)
limit = 0;
else if (c == 'K' || c == 'k')
limit = (limit + 1023) / 1024;
else if (c == 'G' || c == 'g')
limit *= 1024;
}
else
limit = (limit + 1024*1024 - 1) / (1024*1024);
retval = table_api.add_option("limit", limit) && retval;
retval = table_api.add_comment("limit now in MB, converted") && retval;
retval = table_api.add_deleted_comment("units") && retval;
return retval;
}
/**************************
******* A P I ***********
**************************/
static ConversionState* ctor(Converter& c)
{
c.get_table_api().open_top_level_table("alert_csv"); // in case there are no arguments
c.get_table_api().close_table();
return new AlertCsv(c);
}
static const ConvertMap alert_csv_api =
{
"alert_csv",
ctor,
};
const ConvertMap* alert_csv_map = &alert_csv_api;
} // namespace output
| 32.088803 | 90 | 0.553844 |
320ba053f76ac48a47fd3cf23ed89c7d478b06f7 | 3,891 | cpp | C++ | src/SplitFit.cpp | IWantedToBeATranslator/2D-Strip-Packing | 4ee9a220f2e9debf775b020d961f0ba547f32636 | [
"MIT"
] | 1 | 2017-12-12T19:23:44.000Z | 2017-12-12T19:23:44.000Z | src/SplitFit.cpp | IWantedToBeATranslator/2D-Strip-Packing | 4ee9a220f2e9debf775b020d961f0ba547f32636 | [
"MIT"
] | 1 | 2016-04-20T18:47:05.000Z | 2016-05-04T08:05:45.000Z | src/SplitFit.cpp | IWantedToBeATranslator/2D-Strip-Packing | 4ee9a220f2e9debf775b020d961f0ba547f32636 | [
"MIT"
] | 1 | 2019-07-14T15:39:27.000Z | 2019-07-14T15:39:27.000Z | #include "SplitFit.h"
SplitFit::SplitFit()
{
int levelH[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levels = 1;
int levelW[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levelHmin = 0;
int levelRH[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int levelsR = 1;
int levelRW[30] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
spColorRectSprite bloxBuffer;
spColorRectSprite *WideBlox = new spColorRectSprite[eCount];
spColorRectSprite *ThinBlox = new spColorRectSprite[eCount];
sortNonDecr(_bloxArray, bloxHeights, bloxWidths);
int CountRest = 0;
int Count12 = 0;
FOR(i, 0, eCount)
{
if (_bloxArray[i]->getWidth() > clipWidth / 2)
{
WideBlox[Count12] = _bloxArray[i];
Count12++;
}
else
{
ThinBlox[CountRest] = _bloxArray[i];
CountRest++;
}
}
FOR(i, 0, Count12)
FOR(j, 0, Count12 - 1)
if (WideBlox[j]->getWidth() < WideBlox[j + 1]->getWidth())
{
bloxBuffer = WideBlox[j];
WideBlox[j] = WideBlox[j + 1];
WideBlox[j + 1] = bloxBuffer;
}
FOR(i, 0, Count12)
{
WideBlox[i]->addTween(Actor::TweenPosition(0, levelHmin), 500);
levelHmin += WideBlox[i]->getHeight();
}
int regionRW = 0;
int regionRH = 0;
int regionRX = 0;
int regionRY = 0;
int levelRHmin = 0;
FOR(i, 0, Count12)
{
if (WideBlox[i]->getWidth() < 2 * clipWidth / 3)
{
regionRX = WideBlox[i]->getWidth();
regionRY = regionRH;
regionRW = clipWidth - regionRX;
regionRH = levelHmin - regionRH;
break;
}
regionRH += WideBlox[i]->getHeight();
}
int Rcheck = 0;
int Restcheck = 0;
int checker = 0;
int RorO = 0;
FOR(i, 0, CountRest)
{
if ((ThinBlox[i]->getHeight() <= regionRH) && (ThinBlox[i]->getWidth() <= regionRW))
RorO = 1;
else
RorO = 0;
if (RorO)
{
if (Rcheck)
{
checker = 0;
FOR(k, 0, levelsR)
{
if (regionRW - levelRW[k] >= ThinBlox[i]->getWidth() && !checker)
{
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX + levelRW[k], regionRY + levelRH[k]), 500);
levelRW[k] += ThinBlox[i]->getWidth();
checker = 1;
}
}
if (!checker)
{
if (ThinBlox[i]->getHeight() <= regionRH - levelRHmin)
{
levelsR++;
levelRHmin += ThinBlox[i]->getHeight();
levelRH[levelsR] = levelRHmin;
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX + levelRW[levelsR - 1], regionRY + levelRH[levelsR - 1]), 500);
levelRW[levelsR - 1] += ThinBlox[i]->getWidth();
}
else
RorO = 0;
}
}
else
{
Rcheck = 1;
ThinBlox[i]->addTween(Actor::TweenPosition(regionRX, regionRY), 500);
levelRH[1] = ThinBlox[i]->getHeight();
levelRW[0] = ThinBlox[i]->getWidth();
levelRHmin = levelRH[1];
checker = 0;
}
}
if (!RorO)
{
if (Restcheck)
{
checker = 0;
FOR(k, 0, levels)
{
if (clipWidth - levelW[k] >= ThinBlox[i]->getWidth() && !checker)
{
ThinBlox[i]->addTween(Actor::TweenPosition(levelW[k], levelH[k]), 500);
levelW[k] += ThinBlox[i]->getWidth();
checker = 1;
}
}
if (!checker)
{
levels++;
levelHmin += ThinBlox[i]->getHeight();
levelH[levels] = levelHmin;
ThinBlox[i]->addTween(Actor::TweenPosition(levelW[levels - 1], levelH[levels - 1]), 500);
levelW[levels - 1] += ThinBlox[i]->getWidth();
}
}
else
{
Restcheck = 1;
ThinBlox[i]->addTween(Actor::TweenPosition(0, levelHmin), 500);
levelH[0] = levelHmin;
levelH[1] = levelHmin + ThinBlox[i]->getHeight();
levelW[0] = ThinBlox[i]->getWidth();
levelHmin = levelH[1];
checker = 0;
}
}
}
algosHeights = levelHmin;
updateState;
} | 24.018519 | 122 | 0.555641 |
320bf69707aaae190ebccb03cd7d07ac9c80ace7 | 677 | cpp | C++ | codes_of_questions/1007_DNA_sorting.cpp | Zaryob/algorithmsolutions | 3f3270aed8274b5a7102afe5f21aa8da0245625e | [
"MIT"
] | 5 | 2021-03-27T21:26:07.000Z | 2021-12-23T22:15:37.000Z | codes_of_questions/1007_DNA_sorting.cpp | Zaryob/algorithmsolutions | 3f3270aed8274b5a7102afe5f21aa8da0245625e | [
"MIT"
] | null | null | null | codes_of_questions/1007_DNA_sorting.cpp | Zaryob/algorithmsolutions | 3f3270aed8274b5a7102afe5f21aa8da0245625e | [
"MIT"
] | null | null | null | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct dna
{
int pos;
int key;
string str;
};
bool cmp(const dna &a, const dna &b)
{
if (a.key != b.key)
{
return a.key < b.key;
}
else
{
return a.pos < b.pos;
}
}
int main()
{
int n, m, count;
dna inv[110];
string str;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> str;
count = 0;
for (int j = 0; j < n - 1; j++)
{
for (int k = j + 1; k < n; k++)
{
if (str[j] > str[k]) count++;
}
}
inv[i].key = count;
inv[i].pos = i;
inv[i].str = str;
}
sort(inv, inv + m, cmp);
for (int i = 0; i < m; i++)
{
cout << inv[i].str << endl;
}
return 0;
}
| 11.877193 | 36 | 0.478582 |
320cf2711bacf04a487260e91cd6e5effe949e09 | 2,792 | cpp | C++ | source/resource/font.cpp | synaodev/LeviathanRacket | c70dfddf0097c7f4e902ec5de46a6eabed5a4691 | [
"MIT"
] | 5 | 2020-03-25T14:46:23.000Z | 2022-02-23T01:46:26.000Z | source/resource/font.cpp | synaodev/LeviathanRacket | c70dfddf0097c7f4e902ec5de46a6eabed5a4691 | [
"MIT"
] | 1 | 2022-01-14T00:01:48.000Z | 2022-01-14T00:01:48.000Z | source/resource/font.cpp | synaodev/LeviathanRacket | c70dfddf0097c7f4e902ec5de46a6eabed5a4691 | [
"MIT"
] | 2 | 2020-03-25T14:46:24.000Z | 2020-08-21T04:33:23.000Z | #include "./font.hpp"
#include "./vfs.hpp"
#include "../utility/logger.hpp"
#include "../video/texture.hpp"
#include <fstream>
#include <glm/gtc/constants.hpp>
#include <nlohmann/json.hpp>
const font_glyph_t font_t::kNullGlyph {};
void font_t::load(const std::string& directory, const std::string& name) {
auto make_table = [](const std::string& value) {
switch (std::stoi(value)) {
case 1: return 2;
case 2: return 1;
case 4: return 0;
case 8: return 3;
default: return 0;
}
};
if (!glyphs.empty()) {
synao_log("Warning! Tried to overwrite font!\n");
return;
}
const std::string full_path = directory + name;
std::ifstream ifs { full_path, std::ios::binary };
if (ifs.is_open()) {
nlohmann::json file = nlohmann::json::parse(ifs);
auto block = file["font"];
dimensions.x = std::stof(block["common"]["-base"].get<std::string>());
dimensions.y = std::stof(block["common"]["-lineHeight"].get<std::string>());
atlas = vfs_t::atlas(block["pages"]["page"]["-file"].get<std::string>());
for (auto ot : block["chars"]["char"]) {
char32_t id = std::stoi(ot["-id"].get<std::string>());
const font_glyph_t glyph {
std::stof(ot["-x"].get<std::string>()),
std::stof(ot["-y"].get<std::string>()),
std::stof(ot["-width"].get<std::string>()),
std::stof(ot["-height"].get<std::string>()),
std::stof(ot["-xoffset"].get<std::string>()),
std::stof(ot["-yoffset"].get<std::string>()),
std::stof(ot["-xadvance"].get<std::string>()),
std::invoke(make_table, ot["-chnl"].get<std::string>())
};
glyphs[id] = glyph;
}
if (block.find("kernings") != block.end()) {
for (auto ot : block["kernings"]["kerning"]) {
char32_t first = std::stoi(ot["-first"].get<std::string>());
char32_t second = std::stoi(ot["-second"].get<std::string>());
auto key = std::pair{first, second};
kernings[key] = std::stof(ot["-amount"].get<std::string>());
}
}
} else {
synao_log("Failed to load font from {}!\n", full_path);
}
}
const font_glyph_t& font_t::glyph(char32_t code_point) const {
auto it = glyphs.find(code_point);
if (it == glyphs.end()) {
return kNullGlyph;
}
return it->second;
}
real_t font_t::kerning(char32_t first, char32_t second) const {
if (first == U'\0' or second == U'\0') {
return 0.0f;
}
auto it = kernings.find(std::pair{first, second});
if (it == kernings.end()) {
return 0.0f;
}
return it->second;
}
const atlas_t* font_t::get_atlas() const {
return atlas;
}
sint_t font_t::get_atlas_name() const {
if (atlas) {
return atlas->get_name();
}
return 0;
}
glm::vec2 font_t::get_inverse_dimensions() const {
if (atlas) {
return atlas->get_inverse_dimensions();
}
return glm::one<glm::vec2>();
}
glm::vec2 font_t::get_dimensions() const {
return dimensions;
}
| 25.851852 | 78 | 0.625358 |
320e6f684dea75528b653b8b6172938f63e9d919 | 436 | cpp | C++ | src/Red/Data/JSON/Number.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | 1 | 2020-06-14T06:14:50.000Z | 2020-06-14T06:14:50.000Z | src/Red/Data/JSON/Number.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | null | null | null | src/Red/Data/JSON/Number.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | null | null | null | #include <Red/Data/JSON/Number.h>
Red::Data::JSON::Number :: Number ( double Value ):
RefCounted ( 0 ),
Value ( Value )
{
}
Red::Data::JSON::Number :: ~Number ()
{
}
Red::Data::JSON::IType :: DataType Red::Data::JSON::Number :: GetType () const
{
return kDataType_Number;
}
double Red::Data::JSON::Number :: Get ()
{
return Value;
}
void Red::Data::JSON::Number :: Set ( double Value )
{
this -> Value = Value;
}
| 13.212121 | 78 | 0.605505 |
32112ab813d3aa682de5b9cba42ab4654fb1fb80 | 10,516 | cpp | C++ | work_addons/ofxXTween/src/ofxXTweener.cpp | jjongun/ofxAddons | 44958f20e5dfcd71cfa5c5596aa0c480893894b8 | [
"MIT"
] | null | null | null | work_addons/ofxXTween/src/ofxXTweener.cpp | jjongun/ofxAddons | 44958f20e5dfcd71cfa5c5596aa0c480893894b8 | [
"MIT"
] | null | null | null | work_addons/ofxXTween/src/ofxXTweener.cpp | jjongun/ofxAddons | 44958f20e5dfcd71cfa5c5596aa0c480893894b8 | [
"MIT"
] | null | null | null |
#include "ofxXTweener.h"
#pragma region Easing functions
/***** LINEAR ****/
float Linear::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeIn(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeOut(float t, float b, float c, float d) {
return c*t / d + b;
}
float Linear::easeInOut(float t, float b, float c, float d) {
return c*t / d + b;
}
/***** SINE ****/
float Sine::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Sine::easeIn(float t, float b, float c, float d) {
return -c * cos(t / d * float(PI / 2)) + c + b;
}
float Sine::easeOut(float t, float b, float c, float d) {
return c * sin(t / d * float(PI / 2)) + b;
}
float Sine::easeInOut(float t, float b, float c, float d) {
return -c / 2 * float(cos(PI*t / d) - 1) + b;
}
/**** Quint ****/
float Quint::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quint::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t*t*t + b;
}
float Quint::easeOut(float t, float b, float c, float d) {
return c*((t = t / d - 1)*t*t*t*t + 1) + b;
}
float Quint::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t*t*t + b;
return c / 2 * ((t -= 2)*t*t*t*t + 2) + b;
}
/**** Quart ****/
float Quart::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quart::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t*t + b;
}
float Quart::easeOut(float t, float b, float c, float d) {
return -c * ((t = t / d - 1)*t*t*t - 1) + b;
}
float Quart::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t*t + b;
return -c / 2 * ((t -= 2)*t*t*t - 2) + b;
}
/**** Quad ****/
float Quad::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Quad::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t + b;
}
float Quad::easeOut(float t, float b, float c, float d) {
return -c *(t /= d)*(t - 2) + b;
}
float Quad::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return ((c / 2)*(t*t)) + b;
return -c / 2 * (((t - 2)*(--t)) - 1) + b;
/*
originally return -c/2 * (((t-2)*(--t)) - 1) + b;
I've had to swap (--t)*(t-2) due to diffence in behaviour in
pre-increment operators between java and c++, after hours
of joy
*/
}
/**** Expo ****/
float Expo::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Expo::easeIn(float t, float b, float c, float d) {
return float((t == 0) ? b : c * pow(2, 10 * (t / d - 1)) + b);
}
float Expo::easeOut(float t, float b, float c, float d) {
return float((t == d) ? b + c : c * (-pow(2, -10 * t / d) + 1) + b);
}
float Expo::easeInOut(float t, float b, float c, float d) {
if (t == 0) return b;
if (t == d) return b + c;
if ((t /= d / 2) < 1) return float(c / 2 * pow(2, 10 * (t - 1)) + b);
return float(c / 2 * (-pow(2, -10 * --t) + 2) + b);
}
/**** Elastic ****/
float Elastic::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Elastic::easeIn(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d) == 1) return b + c;
float p = d*.3f;
float a = c;
float s = p / 4;
float postFix = float(a*pow(2, 10 * (t -= 1))); // this is a fix, again, with post-increment operators
return float(-(postFix * sin((t*d - s)*(2 * PI) / p)) + b);
}
float Elastic::easeOut(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d) == 1) return b + c;
float p = d*.3f;
float a = c;
float s = p / 4;
return float(a*pow(2, -10 * t) * sin((t*d - s)*(2 * PI) / p) + c + b);
}
float Elastic::easeInOut(float t, float b, float c, float d) {
if (t == 0) return b; if ((t /= d / 2) == 2) return b + c;
float p = d*(.3f*1.5f);
float a = c;
float s = p / 4;
if (t < 1) {
float postFix = float(a*pow(2, 10 * (t -= 1))); // postIncrement is evil
return float(-.5f*(postFix* sin((t*d - s)*(2 * PI) / p)) + b);
}
float postFix = float(a*pow(2, -10 * (t -= 1))); // postIncrement is evil
return postFix * float(sin((t*d - s)*(2 * PI) / p)*.5f + c + b);
}
/**** Cubic ****/
float Cubic::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Cubic::easeIn(float t, float b, float c, float d) {
return c*(t /= d)*t*t + b;
}
float Cubic::easeOut(float t, float b, float c, float d) {
return c*((t = t / d - 1)*t*t + 1) + b;
}
float Cubic::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return c / 2 * t*t*t + b;
return c / 2 * ((t -= 2)*t*t + 2) + b;
}
/*** Circ ***/
float Circ::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Circ::easeIn(float t, float b, float c, float d) {
return -c * (sqrt(1 - (t /= d)*t) - 1) + b;
}
float Circ::easeOut(float t, float b, float c, float d) {
return c * sqrt(1 - (t = t / d - 1)*t) + b;
}
float Circ::easeInOut(float t, float b, float c, float d) {
if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t*t) - 1) + b;
return c / 2 * (sqrt(1 - t*(t -= 2)) + 1) + b;
}
/**** Bounce ****/
float Bounce::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Bounce::easeIn(float t, float b, float c, float d) {
return c - easeOut(d - t, 0, c, d) + b;
}
float Bounce::easeOut(float t, float b, float c, float d) {
if ((t /= d) < (1 / 2.75f)) {
return c*(7.5625f*t*t) + b;
}
else if (t < (2 / 2.75f)) {
float postFix = t -= (1.5f / 2.75f);
return c*(7.5625f*(postFix)*t + .75f) + b;
}
else if (t < (2.5 / 2.75)) {
float postFix = t -= (2.25f / 2.75f);
return c*(7.5625f*(postFix)*t + .9375f) + b;
}
else {
float postFix = t -= (2.625f / 2.75f);
return c*(7.5625f*(postFix)*t + .984375f) + b;
}
}
float Bounce::easeInOut(float t, float b, float c, float d) {
if (t < d / 2) return easeIn(t * 2, 0, c, d) * .5f + b;
else return easeOut(t * 2 - d, 0, c, d) * .5f + c*.5f + b;
}
/**** Back *****/
float Back::easeNone(float t, float b, float c, float d) {
return c*t / d + b;
}
float Back::easeIn(float t, float b, float c, float d) {
float s = 1.70158f;
float postFix = t /= d;
return c*(postFix)*t*((s + 1)*t - s) + b;
}
float Back::easeOut(float t, float b, float c, float d) {
float s = 1.70158f;
return c*((t = t / d - 1)*t*((s + 1)*t + s) + 1) + b;
}
float Back::easeInOut(float t, float b, float c, float d) {
float s = 1.70158f;
if ((t /= d / 2) < 1) return c / 2 * (t*t*(((s *= (1.525f)) + 1)*t - s)) + b;
float postFix = t -= 2;
return c / 2 * ((postFix)*t*(((s *= (1.525f)) + 1)*t + s) + 2) + b;
}
#pragma endregion
//implementation Tweener Class*********************************************************
#pragma region ofxXTween
float ofxXTweener::runEquation(int transition, int equation, float t, float b, float c, float d) {
float result = 0;
if (equation == EASE_IN) {
result = funcs[transition]->easeIn(t, b, c, d);
}
else if (equation == EASE_OUT) {
result = funcs[transition]->easeOut(t, b, c, d);
}
else if (equation == EASE_IN_OUT) {
result = funcs[transition]->easeInOut(t, b, c, d);
}
else if (equation == EASE_NONE)
{
result = funcs[transition]->easeNone(t, b, c, d);
}
return result;
}
void ofxXTweener::callTween(long duration, float start , float end, int draw_priority, Transition transition, Equation ease , TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
updateTween = update;
completeTween = complete;
this->duration = duration;
this->start_value = start;
this->end_value = end;
this->draw_priority = draw_priority;
this->transition = transition;
this->ease = ease;
zerofloat = 0.0f;
updateTween(0.0f);
StartTimer(draw_priority);
}
void ofxXTweener::Run(long duration, float start, float end, int draw_priority, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, draw_priority, transition, ease, update,
[complete , tween]() {
complete();
delete tween;
});
}
void ofxXTweener::Run(long duration, float start, float end, int draw_priority, Transition transition, Equation ease, TWEEN_CALLBACK update)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, draw_priority, transition, ease, update ,
[tween]() {
delete tween;
});
}
void ofxXTweener::Run(long duration, float start, float end, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, start, end, ofEventOrder::OF_EVENT_ORDER_APP, transition, ease, update,
[complete , tween]() {
complete();
delete tween;
});
}
void ofxXTweener::RunZeroToOne(long duration, Transition transition, Equation ease, TWEEN_CALLBACK update, DEFALUT_CALLBACK complete)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, 0, 1, ofEventOrder::OF_EVENT_ORDER_APP , transition, ease, update,
[complete, tween]() {
complete();
delete tween;
});
}
void ofxXTweener::RunZeroToOne(long duration, Transition transition, Equation ease, TWEEN_CALLBACK update)
{
ofxXTweener* tween = new ofxXTweener();
tween->callTween(duration, 0, 1, ofEventOrder::OF_EVENT_ORDER_APP, transition, ease, update,
[tween]() {
delete tween;
});
}
void ofxXTweener::StartTimer(int draw_priority)
{
start_time = ofGetElapsedTimef();
ofAddListener(ofEvents().draw, this, &ofxXTweener::timeElapsed , draw_priority);
}
void ofxXTweener::StopTimer(int draw_priority)
{
ofRemoveListener(ofEvents().draw, this, &ofxXTweener::timeElapsed , draw_priority);
}
void ofxXTweener::timeElapsed(ofEventArgs &e)
{
float elapsed = ofGetElapsedTimef() - start_time;
if (elapsed < 0.0001f)
elapsed = 0;
//float res = runEquation(CUBIC, EASE_OUT, elapsed, 0, 1, duration);
float res = runEquation(transition, ease, elapsed, 0, 1, duration);
res = ofMap(res, 0, 1, start_value, end_value);
updateTween(res);
if (elapsed > duration)
{
StopTimer(this->draw_priority);
completeTween();
}
}
ofxXTweener::ofxXTweener()
{
zerofloat = 0.0f;
this->funcs[LINEAR] = &nfLinear;
this->funcs[SINE] = &nfSine;
this->funcs[QUINT] = &nfQuint;
this->funcs[QUART] = &nfQuart;
this->funcs[QUAD] = &nfQuad;
this->funcs[EXPO] = &nfExpo;
this->funcs[ELASTIC] = &nfElastic;
this->funcs[CUBIC] = &nfCubic;
this->funcs[CIRC] = &nfCirc;
this->funcs[BOUNCE] = &nfBounce;
this->funcs[BACK] = &nfBack;
lastTime = 0;
}
ofxXTweener::~ofxXTweener()
{
}
#pragma endregion
| 27.103093 | 176 | 0.603461 |
32121d63e621256eef322efc6b1f72fcfcc9a340 | 761 | hpp | C++ | src/protocols/wl/data_device.hpp | Link1J/Awning | 4e35e092725d1688ac94f8473fb6bffd99a5cfa0 | [
"MIT"
] | null | null | null | src/protocols/wl/data_device.hpp | Link1J/Awning | 4e35e092725d1688ac94f8473fb6bffd99a5cfa0 | [
"MIT"
] | null | null | null | src/protocols/wl/data_device.hpp | Link1J/Awning | 4e35e092725d1688ac94f8473fb6bffd99a5cfa0 | [
"MIT"
] | null | null | null | #pragma once
#include <wayland-server.h>
#include <unordered_map>
#include <vector>
#include <string>
namespace Awning::Protocols::WL::Data_Device
{
extern const struct wl_data_device_interface interface;
namespace Interface
{
void Start_Drag(struct wl_client* client, struct wl_resource* resource, struct wl_resource* source, struct wl_resource* origin, struct wl_resource* icon, uint32_t serial);
void Set_Selection(struct wl_client* client, struct wl_resource* resource, struct wl_resource* source, uint32_t serial);
void Release(struct wl_client* client, struct wl_resource* resource);
}
wl_resource* Create(struct wl_client* wl_client, uint32_t version, uint32_t id, struct wl_resource* seat);
void Destroy(struct wl_resource* resource);
}
| 34.590909 | 173 | 0.792378 |
321459382e58a205aac83dd508d19189b1440df1 | 7,119 | cpp | C++ | Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp | GlebShikovec/SREngine | bb806c3e4da06ef6fddee5b46ed5d2fca231be43 | [
"MIT"
] | 7 | 2020-10-16T11:34:27.000Z | 2022-03-12T17:53:15.000Z | Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp | Kiper220/SREngine | f1fa36b5ded1f489a9fdb59d8d4b40eb294ba9ec | [
"MIT"
] | 1 | 2022-03-07T14:42:22.000Z | 2022-03-07T14:42:22.000Z | Engine/Dependences/Framework/Depends/LuaBridge/Tests/Source/NamespaceTests.cpp | GlebShikovec/SREngine | bb806c3e4da06ef6fddee5b46ed5d2fca231be43 | [
"MIT"
] | 6 | 2021-05-06T15:09:52.000Z | 2022-03-12T17:57:14.000Z | // https://github.com/vinniefalco/LuaBridge
//
// Copyright 2019, Dmitry Tarakanov
// SPDX-License-Identifier: MIT
#include "TestBase.h"
struct NamespaceTests : TestBase
{
template <class T>
T variable (const std::string& name)
{
runLua ("result = " + name);
return result <T> ();
}
};
TEST_F (NamespaceTests, Variables)
{
int int_ = -10;
auto any = luabridge::newTable (L);
any ["a"] = 1;
ASSERT_THROW (
luabridge::getGlobalNamespace (L).addProperty ("int", &int_),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &int_)
.addProperty ("any", &any)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
runLua ("ns.int = -20");
ASSERT_EQ (-20, int_);
runLua ("ns.any = {b = 2}");
ASSERT_TRUE (any.isTable ());
ASSERT_TRUE (any ["b"].isNumber ());
ASSERT_EQ (2, any ["b"].cast <int> ());
}
TEST_F (NamespaceTests, ReadOnlyVariables)
{
int int_ = -10;
auto any = luabridge::newTable (L);
any ["a"] = 1;
ASSERT_THROW (
luabridge::getGlobalNamespace (L).addProperty ("int", &int_),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &int_, false)
.addProperty ("any", &any, false)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
ASSERT_THROW (runLua ("ns.int = -20"), std::runtime_error);
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_THROW (runLua ("ns.any = {b = 2}"), std::runtime_error);
ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any"));
}
namespace {
template <class T>
struct Property
{
static T value;
};
template <class T>
T Property <T>::value;
template <class T>
void setProperty (const T& value)
{
Property <T>::value = value;
}
template <class T>
const T& getProperty ()
{
return Property <T>::value;
}
} // namespace
TEST_F (NamespaceTests, Properties)
{
setProperty <int> (-10);
ASSERT_THROW (
luabridge::getGlobalNamespace (L)
.addProperty ("int", &getProperty <int>, &setProperty <int>),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &getProperty <int>, &setProperty <int>)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
runLua ("ns.int = -20");
ASSERT_EQ (-20, getProperty <int> ());
}
TEST_F (NamespaceTests, ReadOnlyProperties)
{
setProperty <int> (-10);
ASSERT_THROW (
luabridge::getGlobalNamespace (L)
.addProperty ("int", &getProperty <int>),
std::logic_error);
runLua ("result = int");
ASSERT_TRUE (result ().isNil ());
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("int", &getProperty <int>)
.endNamespace ();
ASSERT_EQ (-10, variable <int> ("ns.int"));
ASSERT_THROW (
runLua ("ns.int = -20"),
std::runtime_error);
ASSERT_EQ (-10, getProperty <int> ());
}
namespace {
template <class T>
struct Storage
{
static T value;
};
template <class T>
T Storage <T>::value;
template <class T>
int getDataC (lua_State* L)
{
luabridge::Stack <T>::push (L, Storage <T>::value);
return 1;
}
template <class T>
int setDataC (lua_State* L)
{
Storage <T>::value = luabridge::Stack <T>::get (L, -1);
return 0;
}
} // namespace
TEST_F (NamespaceTests, Properties_ProxyCFunctions)
{
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("value", &getDataC <int>, &setDataC <int>)
.endNamespace ();
Storage <int>::value = 1;
runLua ("ns.value = 2");
ASSERT_EQ (2, Storage <int>::value);
Storage <int>::value = 3;
runLua ("result = ns.value");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (3, result ().cast <int> ());
}
TEST_F (NamespaceTests, Properties_ProxyCFunctions_ReadOnly)
{
luabridge::getGlobalNamespace (L)
.beginNamespace ("ns")
.addProperty ("value", &getDataC <int>)
.endNamespace ();
Storage <int>::value = 1;
ASSERT_THROW (runLua ("ns.value = 2"), std::exception);
ASSERT_EQ (1, Storage <int>::value);
Storage <int>::value = 3;
runLua ("result = ns.value");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (3, result ().cast <int> ());
}
namespace {
struct Class {};
}
TEST_F (NamespaceTests, LuaStackIntegrity)
{
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
{
auto ns2 = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginNamespace ("ns2");
ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., global namespace table (gns), namespace table (ns), ns2
ns2.endNamespace (); // Stack: ...
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
{
auto globalNs = luabridge::getGlobalNamespace (L);
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
{
auto ns = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace");
// both globalNs an ns are active
ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., gns, gns, ns
}
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
{
auto ns = globalNs
.beginNamespace ("namespace");
// globalNs became inactive
ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
ASSERT_THROW (globalNs.beginNamespace ("namespace"), std::exception);
ASSERT_THROW (globalNs.beginClass <Class> ("Class"), std::exception);
}
{
auto globalNs = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.endNamespace ();
// globalNs is active
ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns
}
ASSERT_EQ (1, lua_gettop (L)); // StacK: ...
{
auto cls = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginClass <Class> ("Class");
ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table
{
auto ns = cls.endClass ();
ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
ASSERT_EQ (1, lua_gettop (L)); // StacK: ...
// Test class continuation
{
auto cls = luabridge::getGlobalNamespace (L)
.beginNamespace ("namespace")
.beginClass <Class> ("Class");
ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table
}
ASSERT_EQ (1, lua_gettop (L)); // Stack: ...
}
#ifdef _M_IX86 // Windows 32bit only
namespace {
int __stdcall StdCall (int i)
{
return i + 10;
}
} // namespace
TEST_F (NamespaceTests, StdCallFunctions)
{
luabridge::getGlobalNamespace (L)
.addFunction ("StdCall", &StdCall);
runLua ("result = StdCall (2)");
ASSERT_TRUE (result ().isNumber ());
ASSERT_EQ (12, result <int> ());
}
#endif // _M_IX86
| 22.817308 | 105 | 0.617643 |
3216a0912083e09e1e4d9a060d8eb8d6739fa22f | 5,810 | cc | C++ | cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc | linghusmile/Cartographer_- | 28be85c1af353efae802cebb299b8d2486fbd800 | [
"Apache-2.0"
] | 2 | 2020-02-25T05:52:57.000Z | 2021-03-18T08:28:38.000Z | cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc | linghusmile/Cartographer_- | 28be85c1af353efae802cebb299b8d2486fbd800 | [
"Apache-2.0"
] | null | null | null | cartographer/mapping_2d/scan_matching/ceres_scan_matcher.cc | linghusmile/Cartographer_- | 28be85c1af353efae802cebb299b8d2486fbd800 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 The Cartographer Authors
*
* 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 "../mapping_2d/scan_matching/ceres_scan_matcher.h"
#include <utility>
#include <vector>
#include "eigen3/Eigen/Core"
#include "../common/ceres_solver_options.h"
#include "../common/lua_parameter_dictionary.h"
#include "../kalman_filter/pose_tracker.h"
#include "../mapping_2d/probability_grid.h"
#include "../mapping_2d/scan_matching/occupied_space_cost_functor.h"
#include "../mapping_2d/scan_matching/rotation_delta_cost_functor.h"
#include "../mapping_2d/scan_matching/translation_delta_cost_functor.h"
#include "../transform/transform.h"
#include "ceres/ceres.h"
#include "glog/logging.h"
/*
* 用优化的方式进行scan-match。也就是说这里是用梯度下降的方式来进行scan-match
* 因此这里的作用实际上和gmapping的hill-climb方法是差不多的。
* 这种局部优化的方法很容易陷入到局部极小值当中。因此这个方法能正常工作的前提是初始值离全局最优值比较近。
* 因此这个方法一般是用作其他方法的优化。
* 比如在cartographer中 在调用这个方法之前,首先会用CSM方法来进行搜索出来一个初值,然后再用这个优化的方法来进行优化
*/
namespace cartographer {
namespace mapping_2d {
namespace scan_matching {
proto::CeresScanMatcherOptions CreateCeresScanMatcherOptions(
common::LuaParameterDictionary* const parameter_dictionary) {
proto::CeresScanMatcherOptions options;
options.set_occupied_space_cost_functor_weight(
parameter_dictionary->GetDouble("occupied_space_cost_functor_weight"));
options.set_previous_pose_translation_delta_cost_functor_weight(
parameter_dictionary->GetDouble(
"previous_pose_translation_delta_cost_functor_weight"));
options.set_initial_pose_estimate_rotation_delta_cost_functor_weight(
parameter_dictionary->GetDouble(
"initial_pose_estimate_rotation_delta_cost_functor_weight"));
options.set_covariance_scale(
parameter_dictionary->GetDouble("covariance_scale"));
*options.mutable_ceres_solver_options() =
common::CreateCeresSolverOptionsProto(
parameter_dictionary->GetDictionary("ceres_solver_options").get());
return options;
}
CeresScanMatcher::CeresScanMatcher(
const proto::CeresScanMatcherOptions& options)
: options_(options),
ceres_solver_options_(
common::CreateCeresSolverOptions(options.ceres_solver_options())) {
ceres_solver_options_.linear_solver_type = ceres::DENSE_QR;
}
CeresScanMatcher::~CeresScanMatcher() {}
void CeresScanMatcher::Match(const transform::Rigid2d& previous_pose,
const transform::Rigid2d& initial_pose_estimate,
const sensor::PointCloud2D& point_cloud,
const ProbabilityGrid& probability_grid,
transform::Rigid2d* const pose_estimate,
kalman_filter::Pose2DCovariance* const covariance,
ceres::Solver::Summary* const summary) const
{
double ceres_pose_estimate[3] = {initial_pose_estimate.translation().x(),
initial_pose_estimate.translation().y(),
initial_pose_estimate.rotation().angle()};
ceres::Problem problem;
CHECK_GT(options_.occupied_space_cost_functor_weight(), 0.);
//构造残差--栅格
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<OccupiedSpaceCostFunctor, ceres::DYNAMIC,
3>(
new OccupiedSpaceCostFunctor(
options_.occupied_space_cost_functor_weight() /
std::sqrt(static_cast<double>(point_cloud.size())),
point_cloud, probability_grid),
point_cloud.size()),
nullptr, ceres_pose_estimate);
CHECK_GT(options_.previous_pose_translation_delta_cost_functor_weight(), 0.);
//构造残差--平移
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<TranslationDeltaCostFunctor, 2, 3>(
new TranslationDeltaCostFunctor(
options_.previous_pose_translation_delta_cost_functor_weight(),
previous_pose)),
nullptr, ceres_pose_estimate);
CHECK_GT(options_.initial_pose_estimate_rotation_delta_cost_functor_weight(),
0.);
//构造残差--旋转
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<RotationDeltaCostFunctor, 1,
3>(new RotationDeltaCostFunctor(
options_.initial_pose_estimate_rotation_delta_cost_functor_weight(),
ceres_pose_estimate[2])),
nullptr, ceres_pose_estimate);
//求解器
ceres::Solve(ceres_solver_options_, &problem, summary);
//优化完毕之后得到的最优位姿
*pose_estimate = transform::Rigid2d(
{ceres_pose_estimate[0], ceres_pose_estimate[1]}, ceres_pose_estimate[2]);
//计算位姿的方差
ceres::Covariance::Options options;
ceres::Covariance covariance_computer(options);
std::vector<std::pair<const double*, const double*>> covariance_blocks;
covariance_blocks.emplace_back(ceres_pose_estimate, ceres_pose_estimate);
CHECK(covariance_computer.Compute(covariance_blocks, &problem));
double ceres_covariance[3 * 3];
covariance_computer.GetCovarianceBlock(ceres_pose_estimate,
ceres_pose_estimate, ceres_covariance);
*covariance = Eigen::Map<kalman_filter::Pose2DCovariance>(ceres_covariance);
*covariance *= options_.covariance_scale();
}
} // namespace scan_matching
} // namespace mapping_2d
} // namespace cartographer
| 40.068966 | 80 | 0.724269 |
3217a82afab606ad838675c40d023585b0b4a668 | 10,699 | hpp | C++ | cpp/src/test/test_position_manipulation.hpp | arthur-bit-monnot/fire-rs-saop | 321e16fceebf44e8e97b482c24f37fbf6dd7d162 | [
"BSD-2-Clause"
] | 13 | 2018-11-19T15:51:23.000Z | 2022-01-16T11:24:21.000Z | cpp/src/test/test_position_manipulation.hpp | fire-rs-laas/fire-rs-saop | 321e16fceebf44e8e97b482c24f37fbf6dd7d162 | [
"BSD-2-Clause"
] | 14 | 2017-10-12T16:19:19.000Z | 2018-03-12T12:07:56.000Z | cpp/src/test/test_position_manipulation.hpp | fire-rs-laas/fire-rs-saop | 321e16fceebf44e8e97b482c24f37fbf6dd7d162 | [
"BSD-2-Clause"
] | 4 | 2018-03-12T12:28:55.000Z | 2021-07-07T18:32:17.000Z | /* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#include <iostream>
#include "../ext/dubins.h"
#include "../core/trajectory.hpp"
#include "../core/raster.hpp"
#include "../core/uav.hpp"
#include "../vns/vns_interface.hpp"
#include "../vns/factory.hpp"
#include "../vns/neighborhoods/dubins_optimization.hpp"
#include "../core/fire_data.hpp"
#include <boost/test/included/unit_test.hpp>
namespace SAOP {
namespace Test {
using namespace boost::unit_test;
UAV uav("test", 10., 32. * M_PI / 180, 0.1);
void test_single_point_to_observe() {
// all points ignited at time 0, except ont at time 100
DRaster ignitions(100, 100, 0, 0, 25);
ignitions.set(10, 10, 100);
DRaster elevation(100, 100, 0, 0, 25);
auto fd = make_shared<FireData>(ignitions, elevation);
// only interested in the point ignited at time 100
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 100)};
Plan p(confs, fd, TimeWindow{90, 110});
auto vns = SAOP::build_default();
auto res = vns->search(p, 0, 1);
// BOOST_CHECK(res.final());
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe() {
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(std::move(p), 0, 1);
// BOOST_CHECK(Plan(res.final()));
cout << "SUCCESS" << endl;
}
void test_many_points_to_observe_with_start_end_positions() {
Waypoint3d start(5, 5, 0, 0);
Waypoint3d end(11, 11, 0, 0);
// circular firedata spread
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));
}
}
DRaster elevation(100, 100, 0, 0, 1);
auto fd = make_shared<FireData>(ignitions, elevation);
vector<TrajectoryConfig> confs{TrajectoryConfig(
uav,
start,
end,
10)};
Plan p(confs, fd, TimeWindow{0, 110});
auto vns = SAOP::build_default();
auto res = vns->search(std::move(p), 0, 1);
// BOOST_CHECK(Plan(res.final()));
const auto& traj = res.final().trajectories()[0];
//ASSERT(traj[0] == start);
//ASSERT(traj[traj.size()-1] == end);
BOOST_CHECK(traj.insertion_range_start() == 1);
BOOST_CHECK(traj.insertion_range_end() == traj.size() - 2);
cout << "SUCCESS" << endl;
}
void test_segment_rotation() {
for (size_t i = 0; i < 100; i++) {
Waypoint wp(drand(-100000, 10000), drand(-100000, 100000), drand(-10 * M_PI, 10 * M_PI));
Segment seg(wp, drand(0, 1000));
Segment seg_rotated = uav.rotate_on_visibility_center(seg, drand(-10 * M_PI, 10 * M_PI));
Segment seg_back = uav.rotate_on_visibility_center(seg_rotated, wp.dir);
BOOST_CHECK(seg == seg_back);
}
}
void test_projection_on_firefront() {
// uniform propagation along the y axis
{
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, y);
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 50.5);
BOOST_CHECK(res && res->y == 50);
auto res_back = fd.project_on_fire_front(Cell{79, 1}, 50.5);
BOOST_CHECK(res_back && res_back->y == 50);
}
// uniform propagation along the x axis
{
DRaster ignitions(10, 10, 0, 0, 1);
for (size_t x = 0; x < 10; x++) {
for (size_t y = 0; y < 10; y++) {
ignitions.set(x, y, x);
}
}
DRaster elevation(10, 10, 0, 0, 1);
FireData fd(ignitions, elevation);
auto res = fd.project_on_fire_front(Cell{1, 1}, 5.5);
BOOST_CHECK(res && res->x == 5);
auto res_back = fd.project_on_fire_front(Cell{7, 1}, 5.5);
BOOST_CHECK(res_back && res_back->x == 5);
}
// circular propagation center on (50,50)
{
auto dist = [](size_t x, size_t y) {
return sqrt(pow((double) x - 50., 2.) + pow((double) y - 50., 2.));
};
DRaster ignitions(100, 100, 0, 0, 1);
for (size_t x = 0; x < 100; x++) {
for (size_t y = 0; y < 100; y++) {
ignitions.set(x, y, dist(x, y));
}
}
DRaster elevation(100, 100, 0, 0, 1);
FireData fd(ignitions, elevation);
for (size_t i = 0; i < 100; i++) {
const size_t x = rand(0, 100);
const size_t y = rand(0, 100);
auto res = fd.project_on_fire_front(Cell{x, y}, 25);
BOOST_CHECK(res && abs(dist(res->x, res->y) - 25) < 1.5);
}
}
}
void test_trajectory_as_waypoints() {
Trajectory traj((TrajectoryConfig(uav)));
traj.sampled(2);
}
void test_trajectory_slice() {
TimeWindow tw1 = TimeWindow(10, 300);
TrajectoryConfig config1 = TrajectoryConfig(uav, tw1.start, tw1.end);
Trajectory traj = Trajectory(config1);
traj.append_segment(Segment3d(Waypoint3d(0, 0, 0, 0)));
traj.append_segment(Segment3d(Waypoint3d(100, 100, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(300, 200, 0, 0), 50));
traj.append_segment(Segment3d(Waypoint3d(500, 500, 0, 0)));
Trajectory sliced1 = traj.slice(TimeWindow(tw1.start + 1, tw1.end - 1));
Trajectory sliced2 = traj.slice(TimeWindow(tw1.start + 1, 85));
BOOST_CHECK(sliced1.size() == traj.size() - 1);
BOOST_CHECK(sliced2.size() == traj.size() - 2);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced1.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(1), sliced2.start_time(0), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(3), sliced1.start_time(2), 0.1);
BOOST_CHECK_CLOSE(traj.start_time(2), sliced2.start_time(1), 0.1);
}
void test_time_window_order() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
BOOST_CHECK(tw1.start == s);
BOOST_CHECK(tw1.end == e);
BOOST_CHECK(tw1.start == tw2.start);
BOOST_CHECK(tw1.end == tw1.end);
}
void test_time_window() {
double s = 10;
double e = 25;
TimeWindow tw1 = TimeWindow(s, e);
TimeWindow tw2 = TimeWindow(e, s);
TimeWindow tw3 = TimeWindow(s - 1, e);
TimeWindow tw4 = TimeWindow(s, e + 1);
BOOST_CHECK(tw1 == tw2);
BOOST_CHECK(tw1 != tw3);
BOOST_CHECK(tw3.contains(tw1));
BOOST_CHECK(tw3.contains(tw1.center()));
BOOST_CHECK(tw3.intersects(tw4));
BOOST_CHECK(tw3.union_with(tw1) == tw3);
BOOST_CHECK(tw4.intersection_with(tw3) == tw1);
auto empty_intersect = TimeWindow(s - 1, s).intersection_with(TimeWindow(e, e + 1));
BOOST_CHECK(empty_intersect.is_empty());
}
test_suite* position_manipulation_test_suite() {
test_suite* ts2 = BOOST_TEST_SUITE("position_manipulation_tests");
srand(time(0));
ts2->add(BOOST_TEST_CASE(&test_trajectory_slice));
ts2->add(BOOST_TEST_CASE(&test_time_window_order));
ts2->add(BOOST_TEST_CASE(&test_time_window));
ts2->add(BOOST_TEST_CASE(&test_trajectory_as_waypoints));
ts2->add(BOOST_TEST_CASE(&test_segment_rotation));
ts2->add(BOOST_TEST_CASE(&test_single_point_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe));
ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe_with_start_end_positions));
ts2->add(BOOST_TEST_CASE(&test_projection_on_firefront));
return ts2;
}
}
} | 38.210714 | 105 | 0.549397 |
32195b99c77ad49abb0663ef57842b878994afb9 | 23,631 | cpp | C++ | GRAS/raspberry_pi/two_muscle.cpp | KseniiaKarpova/memristive-spinal-cord | 15be4aea80ede6315b9bf4ea76eec17b900f31e4 | [
"MIT"
] | null | null | null | GRAS/raspberry_pi/two_muscle.cpp | KseniiaKarpova/memristive-spinal-cord | 15be4aea80ede6315b9bf4ea76eec17b900f31e4 | [
"MIT"
] | null | null | null | GRAS/raspberry_pi/two_muscle.cpp | KseniiaKarpova/memristive-spinal-cord | 15be4aea80ede6315b9bf4ea76eec17b900f31e4 | [
"MIT"
] | null | null | null | #define DEBUG
#include <omp.h>
#include <cstdio>
#include <cmath>
#include <utility>
#include <vector>
#include <random>
#include <chrono>
#include <string>
// for file writing
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;
unsigned int global_id = 0;
const float SIM_STEP = 0.25;
// stuff variables
const int LEG_STEPS = 1; // [step] number of full cycle steps
const int syn_outdegree = 20; // synapse number outgoing from one neuron
const int neurons_in_ip = 25; // number of neurons in interneuronal pool
const int neurons_in_moto = 25; // motoneurons number
const int neurons_in_group = 15; // number of neurons in a group
const int neurons_in_aff_ip = 25; // number of neurons in interneuronal pool
const int neurons_in_afferent = 15; // number of neurons in afferent
const unsigned short skin_stim_time = 25;
const unsigned int T_simulation = 11 * skin_stim_time * LEG_STEPS;
const unsigned int SIM_TIME_IN_STEPS = (unsigned int)(T_simulation / SIM_STEP);
class Group {
public:
Group() = default;
string group_name;
unsigned int id_start{};
unsigned int id_end{};
unsigned short group_size{};
};
// struct for human-readable initialization of connectomes
struct SynapseMetadata {
unsigned int pre_id; // [id] pre neuron
unsigned int post_id; // [id] post neuron
unsigned int synapse_delay; // [step] synaptic delay of the synapse (axonal delay is included to this delay)
short synapse_weight; // [nS] synaptic weight. Interpreted as changing conductivity of neuron membrane
SynapseMetadata(int pre_id, int post_id, float synapse_delay, short synapse_weight){
this->pre_id = pre_id;
this->post_id = post_id;
this->synapse_delay = lround(synapse_delay * (1 / SIM_STEP) + 0.5);
this->synapse_weight = synapse_weight;
}
};
// struct for human-readable initialization of connectomes
struct GroupMetadata {
Group group;
vector<float> spike_vector; // [ms] spike times
#ifdef DEBUG
unsigned short* voltage_array; // [mV] array of membrane potential
#endif
explicit GroupMetadata(Group group){
this->group = move(group);
#ifdef DEBUG
voltage_array = new unsigned short[SIM_TIME_IN_STEPS];
#endif
}
};
vector<GroupMetadata> all_groups;
vector<SynapseMetadata> all_synapses;
// form structs of neurons global ID and groups name
Group form_group(const string& group_name, int nrns_in_group = neurons_in_group) {
Group group = Group();
group.group_name = group_name; // name of a neurons group
group.id_start = global_id; // first ID in the group
group.id_end = global_id + nrns_in_group - 1; // the latest ID in the group
group.group_size = nrns_in_group; // size of the neurons group
all_groups.emplace_back(group);
global_id += nrns_in_group;
printf("Formed %s IDs [%d ... %d] = %d\n",
group_name.c_str(), global_id - nrns_in_group, global_id - 1, nrns_in_group);
return group;
}
float step_to_ms(unsigned int step) { return step * SIM_STEP; }
int ms_to_step(float ms) { return (int)(ms / SIM_STEP); }
void connect_one_to_all(const Group& pre_neurons, const Group& post_neurons, float syn_delay, float weight) {
// Seed with a real random value, if available
random_device r;
default_random_engine generator(r());
normal_distribution<float> delay_distr(syn_delay, syn_delay / 5);
normal_distribution<float> weight_distr(weight, weight / 10);
for (unsigned int pre_id = pre_neurons.id_start; pre_id <= pre_neurons.id_end; pre_id++)
for (unsigned int post_id = post_neurons.id_start; post_id <= post_neurons.id_end; post_id++)
all_synapses.emplace_back(pre_id, post_id, delay_distr(generator), weight_distr(generator));
printf("Connect %s to %s [one_to_all] (1:%d). Total: %d W=%.2f, D=%.1f\n", pre_neurons.group_name.c_str(),
post_neurons.group_name.c_str(), post_neurons.group_size, pre_neurons.group_size * post_neurons.group_size,
weight, syn_delay);
}
void connect(const Group& pre_neurons, const Group& post_neurons, float syn_delay, float syn_weight,
int outdegree= syn_outdegree,
bool no_distr= false) {
// connect neurons with uniform distribution and normal distributon for syn delay and syn_weight
random_device r;
default_random_engine generator(r());
uniform_int_distribution<int> id_distr(post_neurons.id_start, post_neurons.id_end);
normal_distribution<float> delay_distr_gen(syn_delay, syn_delay / 5);
normal_distribution<float> weight_distr_gen(syn_weight, syn_weight / 10);
for (unsigned int pre_id = pre_neurons.id_start; pre_id <= pre_neurons.id_end; pre_id++) {
for (int i = 0; i < outdegree; i++) {
int rand_post_id = id_distr(generator);
float syn_delay_distr = delay_distr_gen(generator);
float weight_distr = weight_distr_gen(generator);
if (syn_delay_distr <= 0.2)
syn_delay_distr = 0.2;
short syn_weight_distr = static_cast<short>(weight_distr);
if (no_distr)
all_synapses.emplace_back(pre_id, rand_post_id, syn_delay, syn_weight);
else
all_synapses.emplace_back(pre_id, rand_post_id, syn_delay_distr, syn_weight_distr);
}
}
printf("Connect %s to %s [fixed_outdegree] (1:%d). Total: %d W=%.2f, D=%.1f\n",
pre_neurons.group_name.c_str(), post_neurons.group_name.c_str(),
outdegree, pre_neurons.group_size * outdegree, syn_weight, syn_delay);
}
void init_network() {
/// groups of neurons
Group EES = form_group("EES");
Group E1 = form_group("E1");
Group E2 = form_group("E2");
Group E3 = form_group("E3");
Group E4 = form_group("E4");
Group E5 = form_group("E5");
Group CV1 = form_group("CV1", 1);
Group CV2 = form_group("CV2", 1);
Group CV3 = form_group("CV3", 1);
Group CV4 = form_group("CV4", 1);
Group CV5 = form_group("CV5", 1);
Group OM1_0 = form_group("OM1_0");
Group OM1_1 = form_group("OM1_1");
Group OM1_2_E = form_group("OM1_2_E");
Group OM1_2_F = form_group("OM1_2_F");
Group OM1_3 = form_group("OM1_3");
Group OM2_0 = form_group("OM2_0");
Group OM2_1 = form_group("OM2_1");
Group OM2_2_E = form_group("OM2_2_E");
Group OM2_2_F = form_group("OM2_2_F");
Group OM2_3 = form_group("OM2_3");
Group OM3_0 = form_group("OM3_0");
Group OM3_1 = form_group("OM3_1");
Group OM3_2_E = form_group("OM3_2_E");
Group OM3_2_F = form_group("OM3_2_F");
Group OM3_3 = form_group("OM3_3");
Group OM4_0 = form_group("OM4_0");
Group OM4_1 = form_group("OM4_1");
Group OM4_2_E = form_group("OM4_2_E");
Group OM4_2_F = form_group("OM4_2_F");
Group OM4_3 = form_group("OM4_3");
Group OM5_0 = form_group("OM5_0");
Group OM5_1 = form_group("OM5_1");
Group OM5_2_E = form_group("OM5_2_E");
Group OM5_2_F = form_group("OM5_2_F");
Group OM5_3 = form_group("OM5_3");
Group MN_E = form_group("MN_E", neurons_in_moto);
Group MN_F = form_group("MN_F", neurons_in_moto);
Group Ia_E_aff = form_group("Ia_E_aff", neurons_in_afferent);
Group Ia_F_aff = form_group("Ia_F_aff", neurons_in_afferent);
Group R_E = form_group("R_E");
Group R_F = form_group("R_F");
Group Ia_E_pool = form_group("Ia_E_pool", neurons_in_aff_ip);
Group Ia_F_pool = form_group("Ia_F_pool", neurons_in_aff_ip);
Group eIP_E = form_group("eIP_E", neurons_in_ip);
Group eIP_F = form_group("eIP_F", neurons_in_ip);
Group iIP_E = form_group("iIP_E", neurons_in_ip);
Group iIP_F = form_group("iIP_F", neurons_in_ip);
/// connectomes
connect(EES, E1, 1, 5000, syn_outdegree, true);
connect(E1, E2, 1, 5000, syn_outdegree, true);
connect(E2, E3, 1, 5000, syn_outdegree, true);
connect(E3, E4, 1, 5000, syn_outdegree, true);
connect(E4, E5, 1, 5000, syn_outdegree, true);
connect_one_to_all(CV1, iIP_E, 0.5, 500);
connect_one_to_all(CV2, iIP_E, 0.5, 500);
connect_one_to_all(CV3, iIP_E, 0.5, 500);
connect_one_to_all(CV4, iIP_E, 0.5, 500);
connect_one_to_all(CV5, iIP_E, 0.5, 500);
/// OM 1
// input from EES group 1
connect(E1, OM1_0, 2, 1000);
// input from sensory
connect_one_to_all(CV1, OM1_0, 0.5, 1900);
connect_one_to_all(CV2, OM1_0, 0.5, 1900);
// [inhibition]
connect_one_to_all(CV3, OM1_3, 0.25, 5000);
connect_one_to_all(CV4, OM1_3, 0.25, 5000);
connect_one_to_all(CV5, OM1_3, 0.25, 5000);
// inner connectomes
connect(OM1_0, OM1_1, 1, 2000);
connect(OM1_1, OM1_2_E, 1, 1500);
connect(OM1_1, OM1_2_F, 1, 27);
connect(OM1_1, OM1_3, 1, 400);
connect(OM1_2_E, OM1_1, 2.5, 1500);
connect(OM1_2_F, OM1_1, 2.5, 27);
connect(OM1_2_E, OM1_3, 1, 400);
connect(OM1_2_F, OM1_3, 1, 4);
connect(OM1_3, OM1_1, 2, -1000);
connect(OM1_3, OM1_2_E, 0.5, -1000);
connect(OM1_3, OM1_2_F, 2, -3);
// output to OM2
connect(OM1_2_F, OM2_2_F, 4, 30);
// output to IP
connect(OM1_2_E, eIP_E, 2, 1500, neurons_in_ip);
connect(OM1_2_F, eIP_F, 4, 5, neurons_in_ip);
/// OM 2
// input from EES group 2
connect(E2, OM2_0, 2, 680);
// input from sensory [CV]
connect_one_to_all(CV2, OM2_0, 0.5, 1900);
connect_one_to_all(CV3, OM2_0, 0.5, 1900);
// [inhibition]
connect_one_to_all(CV4, OM2_3, 1, 5000);
connect_one_to_all(CV5, OM2_3, 1, 5000);
// inner connectomes
connect(OM2_0, OM2_1, 1, 2000);
connect(OM2_1, OM2_2_E, 1, 1500);
connect(OM2_1, OM2_2_F, 1, 27);
connect(OM2_1, OM2_3, 1, 400);
connect(OM2_2_E, OM2_1, 2.5, 1500);
connect(OM2_2_F, OM2_1, 2.5, 27);
connect(OM2_2_E, OM2_3, 1, 400);
connect(OM2_2_F, OM2_3, 1, 4);
connect(OM2_3, OM2_1, 2, -1000);
connect(OM2_3, OM2_2_E, 0.5, -1000);
connect(OM2_3, OM2_2_F, 2, -3);
// output to OM3
connect(OM2_2_F, OM3_2_F, 4, 30);
// output to IP
connect(OM2_2_E, eIP_E, 2, 1500, neurons_in_ip);
connect(OM2_2_F, eIP_F, 4, 5, neurons_in_ip);
/// OM 3
// input from EES group 3
connect(E3, OM3_0, 3, 670);
// input from sensory [CV]
connect_one_to_all(CV3, OM3_0, 0.5, 1900);
connect_one_to_all(CV4, OM3_0, 0.5, 1900);
// [inhibition]
connect_one_to_all(CV5, OM3_3, 1, 5000);
// inner connectomes
connect(OM3_0, OM3_1, 1, 2000);
connect(OM3_1, OM3_2_E, 1, 1500);
connect(OM3_1, OM3_2_F, 1, 27);
connect(OM3_1, OM3_3, 1, 400);
connect(OM3_2_E, OM3_1, 2.5, 1500);
connect(OM3_2_F, OM3_1, 2.5, 27);
connect(OM3_2_E, OM3_3, 1, 400);
connect(OM3_2_F, OM3_3, 1, 4);
connect(OM3_3, OM3_1, 2, -1000);
connect(OM3_3, OM3_2_E, 0.5, -1000);
connect(OM3_3, OM3_2_F, 2, -3);
// output to OM3
connect(OM3_2_F, OM4_2_F, 4, 30);
// output to IP
connect(OM3_2_E, eIP_E, 2, 1500, neurons_in_ip);
connect(OM3_2_F, eIP_F, 4, 5, neurons_in_ip);
/// OM 4
// input from EES group 4
connect(E4, OM4_0, 3, 680);
// input from sensory [CV]
connect_one_to_all(CV4, OM4_0, 0.5, 1900);
connect_one_to_all(CV5, OM4_0, 0.5, 1900);
// inner connectomes
connect(OM4_0, OM4_1, 1, 2000);
connect(OM4_1, OM4_2_E, 1, 1500);
connect(OM4_1, OM4_2_F, 1, 27);
connect(OM4_1, OM4_3, 1, 400);
connect(OM4_2_E, OM4_1, 2.5, 1500);
connect(OM4_2_F, OM4_1, 2.5, 27);
connect(OM4_2_E, OM4_3, 1, 400);
connect(OM4_2_F, OM4_3, 1, 4);
connect(OM4_3, OM4_1, 2, -1000);
connect(OM4_3, OM4_2_E, 0.5, -1000);
connect(OM4_3, OM4_2_F, 2, -3);
// output to OM4
connect(OM4_2_F, OM5_2_F, 4, 30);
// output to IP
connect(OM4_2_E, eIP_E, 2, 1500, neurons_in_ip);
connect(OM4_2_F, eIP_F, 4, 5, neurons_in_ip);
/// OM 5
// input from EES group 5
connect(E5, OM5_0, 3, 680);
// input from sensory [CV]
connect_one_to_all(CV5, OM5_0, 0.5, 1900);
// inner connectomes
connect(OM5_0, OM5_1, 1, 2000);
connect(OM5_1, OM5_2_E, 1, 1500);
connect(OM5_1, OM5_2_F, 1, 27);
connect(OM5_1, OM5_3, 1, 400);
connect(OM5_2_E, OM5_1, 2.5, 1500);
connect(OM5_2_F, OM5_1, 2.5, 27);
connect(OM5_2_E, OM5_3, 1, 400);
connect(OM5_2_F, OM5_3, 1, 4);
connect(OM5_3, OM5_1, 2, -1000);
connect(OM5_3, OM5_2_E, 0.5, -1000);
connect(OM5_3, OM5_2_F, 2, -3);
// output to IP
connect(OM5_2_E, eIP_E, 1, 1500, neurons_in_ip);
connect(OM5_2_F, eIP_F, 4, 5, neurons_in_ip);
/// reflex arc
connect(iIP_E, eIP_F, 0.5, -10, neurons_in_ip);
connect(iIP_F, eIP_E, 0.5, -10, neurons_in_ip);
connect(iIP_E, OM1_2_F, 0.5, -1, neurons_in_ip);
connect(iIP_E, OM2_2_F, 0.5, -1, neurons_in_ip);
connect(iIP_E, OM3_2_F, 0.5, -1, neurons_in_ip);
connect(iIP_E, OM4_2_F, 0.5, -1, neurons_in_ip);
connect(EES, Ia_E_aff, 1, 2000);
connect(EES, Ia_F_aff, 1, 2000);
connect(eIP_E, MN_E, 2, 400, neurons_in_moto);
connect(eIP_F, MN_F, 5, 8, neurons_in_moto);
connect(iIP_E, Ia_E_pool, 1, 10, neurons_in_ip);
connect(iIP_F, Ia_F_pool, 1, 10, neurons_in_ip);
connect(Ia_E_pool, MN_F, 1, -4, neurons_in_ip);
connect(Ia_E_pool, Ia_F_pool, 1, -1, neurons_in_ip);
connect(Ia_F_pool, MN_E, 1, -4, neurons_in_ip);
connect(Ia_F_pool, Ia_E_pool, 1, -1, neurons_in_ip);
connect(Ia_E_aff, MN_E, 2, 2000, neurons_in_moto);
connect(Ia_F_aff, MN_F, 2, 6, neurons_in_moto);
connect(MN_E, R_E, 2, 1);
connect(MN_F, R_F, 2, 1);
connect(R_E, MN_E, 2, -5, neurons_in_moto);
connect(R_E, R_F, 2, -10);
connect(R_F, MN_F, 2, -5, neurons_in_moto);
connect(R_F, R_E, 2, -10);
}
#ifdef DEBUG
void save(int test_index, GroupMetadata &metadata, const string& folder){
if(metadata.group.group_name[0] != 'M' || metadata.group.group_name[1] != 'N')
return;
ofstream file;
string file_name = "/dat/" + to_string(test_index) + "_" + metadata.group.group_name + ".dat";
file.open(folder + file_name);
// save voltage
for (unsigned int sim_iter = 0; sim_iter < SIM_TIME_IN_STEPS; sim_iter++)
file << metadata.voltage_array[sim_iter] << " ";
file << endl;
// save g_exc
for (unsigned int sim_iter = 0; sim_iter < SIM_TIME_IN_STEPS; sim_iter++)
file << 0 << " ";
file << endl;
// save g_inh
for (unsigned int sim_iter = 0; sim_iter < SIM_TIME_IN_STEPS; sim_iter++)
file << 0 << " ";
file << endl;
// save spikes
for (float const& value: metadata.spike_vector) {
file << value << " ";
}
file.close();
cout << "Saved to: " << folder + file_name << endl;
}
void save_result(int itest) {
string current_path = getcwd(nullptr, 0);
printf("Save results to: %s \n", current_path.c_str());
for(GroupMetadata &metadata : all_groups) {
save(itest, metadata, current_path);
}
}
#endif
// get datasize of current variable type and its number
template <typename type>
unsigned int datasize(unsigned int size) {
return sizeof(type) * size;
}
// fill array with current value
template <typename type>
void init_array(type *array, unsigned int size, type value) {
for(unsigned int i = 0; i < size; i++)
array[i] = value;
}
// fill array by normal distribution
template <typename type>
void rand_normal_init_array(type *array, unsigned int size, type mean, type stddev) {
random_device r;
default_random_engine generator(r());
normal_distribution<float> distr(mean, stddev);
for(unsigned int i = 0; i < size; i++)
array[i] = (type)distr(generator);
}
void copy_data_to(GroupMetadata &metadata, const unsigned short* nrn_v_m, const bool *nrn_has_spike, const unsigned int sim_iter) {
unsigned int nrn_mean_volt = 0;
for(unsigned int tid = metadata.group.id_start; tid <= metadata.group.id_end; tid++) {
nrn_mean_volt += nrn_v_m[tid];
if (nrn_has_spike[tid])
metadata.spike_vector.push_back(step_to_ms(sim_iter) + 0.25);
}
#ifdef DEBUG
metadata.voltage_array[sim_iter] = 1.0f * nrn_mean_volt / metadata.group.group_size;
#endif
}
void simulate(int itest) {
const unsigned int neurons_number = global_id;
const unsigned int synapses_number = static_cast<int>(all_synapses.size());
chrono::time_point<chrono::system_clock> simulation_t_start, simulation_t_end;
// calculate spike frequency and C0/C1 activation time in steps
auto ees_spike_each_step = (unsigned int)(1000 / 40 / SIM_STEP);
auto steps_activation_C0 = (unsigned int)(5 * 25 / SIM_STEP);
auto steps_activation_C1 = (unsigned int)(6 * skin_stim_time / SIM_STEP);
// neuron variables
unsigned short V_m[neurons_number]; // [mV] neuron membrane potential
unsigned short L[neurons_number]; //
unsigned short V_th[neurons_number]; //
bool nrn_has_spike[neurons_number]; // neuron state - has spike or not
int nrn_ref_time[neurons_number]; // [step] neuron refractory time
int nrn_ref_time_timer[neurons_number]; // [step] neuron refractory time timer
init_array<unsigned short>(V_m, neurons_number, 28000);
init_array<bool>(nrn_has_spike, neurons_number, false); // by default neurons haven't spikes at start
rand_normal_init_array<int>(nrn_ref_time, neurons_number, (int)(3 / SIM_STEP), (int)(0.4 / SIM_STEP)); // neuron ref time, aprx interval is (1.8, 4.2)
rand_normal_init_array<unsigned short>(L, neurons_number, 500, 500 / 20); //
rand_normal_init_array<unsigned short>(V_th, neurons_number, 45000, 500); //
init_array<int>(nrn_ref_time_timer, neurons_number, 0); // by default neurons have ref_t timers as 0
// synapse variables
auto *syn_delay = (int *) malloc(datasize<int>(synapses_number));
auto *syn_delay_timer = (int *) malloc(datasize<int>(synapses_number));
auto *syn_weight = (short *) malloc(datasize<short>(synapses_number));
auto *syn_pre_nrn_id = (int *) malloc(datasize<int>(synapses_number));
auto *syn_post_nrn_id = (int *) malloc(datasize<int>(synapses_number));
init_array<int>(syn_delay_timer, synapses_number, -1);
// fill arrays of synapses
unsigned int syn_id = 0;
for(SynapseMetadata metadata : all_synapses) {
syn_pre_nrn_id[syn_id] = metadata.pre_id;
syn_post_nrn_id[syn_id] = metadata.post_id;
syn_delay[syn_id] = metadata.synapse_delay;
syn_weight[syn_id] = metadata.synapse_weight;
syn_id++;
}
all_synapses.clear();
// stuff variables for controlling C0/C1 activation
int local_iter = 0;
bool C0_activated = false; // start from extensor
bool C0_early_activated = false;
unsigned int shift_time_by_step = 0;
bool EES_activated;
bool CV1_activated;
bool CV2_activated;
bool CV3_activated;
bool CV4_activated;
bool CV5_activated;
unsigned int shifted_iter_time;
int begin_C_spiking[5] = {ms_to_step(0),
ms_to_step(skin_stim_time),
ms_to_step(2 * skin_stim_time),
ms_to_step(3 * skin_stim_time),
ms_to_step(5 * skin_stim_time)};
int end_C_spiking[5] = {ms_to_step(skin_stim_time - 0.1),
ms_to_step(2 * skin_stim_time - 0.1),
ms_to_step(3 * skin_stim_time - 0.1),
ms_to_step(5 * skin_stim_time - 0.1),
ms_to_step(6 * skin_stim_time - 0.1)};
random_device r;
default_random_engine generator(r());
uniform_real_distribution<float> standard_uniform(0, 1);
printf("START THE MAIN SIMULATION LOOP\n");
simulation_t_start = chrono::system_clock::now();
// the main simulation loop
for (unsigned int sim_iter = 0; sim_iter < SIM_TIME_IN_STEPS; sim_iter++) {
#ifdef DEBUG
for (GroupMetadata &metadata : all_groups)
copy_data_to(metadata, V_m, nrn_has_spike, sim_iter);
#endif
CV1_activated = false;
CV2_activated = false;
CV3_activated = false;
CV4_activated = false;
CV5_activated = false;
EES_activated = (sim_iter % ees_spike_each_step == 0);
// if flexor C0 activated, find the end of it and change to C1
if (C0_activated) {
if (local_iter != 0 && local_iter % steps_activation_C0 == 0) {
C0_activated = false;
local_iter = 0;
shift_time_by_step += steps_activation_C0;
}
if (local_iter != 0 && (local_iter + 400) % steps_activation_C0 == 0)
C0_early_activated = false;
// if extensor C1 activated, find the end of it and change to C0
} else {
if (local_iter != 0 && local_iter % steps_activation_C1 == 0) {
C0_activated = true;
local_iter = 0;
shift_time_by_step += steps_activation_C1;
}
if (local_iter != 0 && (local_iter + 400) % steps_activation_C1 == 0)
C0_early_activated = true;
}
shifted_iter_time = sim_iter - shift_time_by_step;
// check the CV activation
if ((begin_C_spiking[0] <= shifted_iter_time) && (shifted_iter_time < end_C_spiking[0])) CV1_activated = true;
if ((begin_C_spiking[1] <= shifted_iter_time) && (shifted_iter_time < end_C_spiking[1])) CV2_activated = true;
if ((begin_C_spiking[2] <= shifted_iter_time) && (shifted_iter_time < end_C_spiking[2])) CV3_activated = true;
if ((begin_C_spiking[3] <= shifted_iter_time) && (shifted_iter_time < end_C_spiking[3])) CV4_activated = true;
if ((begin_C_spiking[4] <= shifted_iter_time) && (shifted_iter_time < end_C_spiking[4])) CV5_activated = true;
// update local iter (warning: can be resetted at C0/C1 activation)
local_iter++;
/** ================================================= **/
/** ==================N E U R O N S================== **/
/** ================================================= **/
#pragma omp parallel for num_threads(4) default(shared)
for(unsigned int tid = 0; tid < neurons_number; tid++) {
// reset spike flag of the current neuron before calculations
nrn_has_spike[tid] = false;
// generating spikes for EES
if (tid < 15 && EES_activated) nrn_has_spike[tid] = true;
// iIP_F
if (C0_activated && C0_early_activated && 705 <= tid && tid <= 729)
nrn_has_spike[705 + static_cast<int>(neurons_in_ip * standard_uniform(generator))] = true;
// skin stimulations
if (!C0_activated) {
if (tid == 90 && CV1_activated) nrn_has_spike[tid] = true;
if (tid == 91 && CV2_activated) nrn_has_spike[tid] = true;
if (tid == 92 && CV3_activated) nrn_has_spike[tid] = true;
if (tid == 93 && CV4_activated) nrn_has_spike[tid] = true;
if (tid == 94 && CV5_activated) nrn_has_spike[tid] = true;
}
// (threshold && not in refractory period) >= -55mV
if ((V_m[tid] >= V_th[tid]) && (nrn_ref_time_timer[tid] == 0)) {
V_m[tid] = 20000;
nrn_has_spike[tid] = true;
nrn_ref_time_timer[tid] = nrn_ref_time[tid];
}
if (V_m[tid] < 27500)
V_m[tid] += L[tid];
if (V_m[tid] > 28500)
V_m[tid] -= L[tid];
if (nrn_ref_time_timer[tid] > 0)
nrn_ref_time_timer[tid]--;
}
/** ================================================= **/
/** ==================S Y N A P S E================== **/
/** ================================================= **/
int post_id;
#pragma omp parallel for num_threads(4) shared(V_m, nrn_has_spike, syn_pre_nrn_id, syn_post_nrn_id, syn_delay, syn_delay_timer, syn_weight) private(post_id)
for(unsigned int tid = 0; tid < synapses_number; tid++) {
// add synaptic delay if neuron has spike
if (syn_delay_timer[tid] == -1 && nrn_has_spike[syn_pre_nrn_id[tid]])
syn_delay_timer[tid] = syn_delay[tid];
// if synaptic delay is zero it means the time when synapse increase I by synaptic weight
if (syn_delay_timer[tid] == 0) {
post_id = syn_post_nrn_id[tid];
// post neuron ID = syn_post_nrn_id[syn_id], thread-safe (!)
#pragma omp atomic
V_m[post_id] += syn_weight[tid];
if (V_m[post_id] < 20000)
V_m[post_id] = 20000;
if (V_m[post_id] > 50000)
V_m[post_id] = 50000;
// make synapse timer a "free" for next spikes
syn_delay_timer[tid] = -1;
}
// update synapse delay timer
if (syn_delay_timer[tid] > 0)
syn_delay_timer[tid]--;
}
} // end of the simulation iteration loop
simulation_t_end = chrono::system_clock::now();
#ifdef DEBUG
save_result(itest);
#endif
auto sim_time_diff = chrono::duration_cast<chrono::milliseconds>(simulation_t_end - simulation_t_start).count();
printf("Elapsed %li ms (measured) | T_sim = %d ms\n", sim_time_diff, T_simulation);
printf("%s x%f\n", 1.0 * T_simulation / sim_time_diff > 1? "faster" : "slower", (float)T_simulation / sim_time_diff);
}
// runner
int main(int argc, char* argv[]) {
int itest = atoi(argv[1]);
init_network();
simulate(itest);
return 0;
}
| 35.968037 | 158 | 0.690195 |
32198d49dc2fa06def4ac0e909270088f01cb6bf | 26,482 | cpp | C++ | himan-plugins/source/geotiff.cpp | fmidev/himan | 481e0cf9a3d15c900e07d08cf7e22de1c50a6823 | [
"MIT"
] | 18 | 2017-04-20T18:51:41.000Z | 2022-03-23T21:12:49.000Z | himan-plugins/source/geotiff.cpp | fmidev/himan | 481e0cf9a3d15c900e07d08cf7e22de1c50a6823 | [
"MIT"
] | 5 | 2018-07-05T02:15:56.000Z | 2021-06-01T09:36:51.000Z | himan-plugins/source/geotiff.cpp | fmidev/himan | 481e0cf9a3d15c900e07d08cf7e22de1c50a6823 | [
"MIT"
] | 2 | 2020-02-18T06:32:53.000Z | 2021-03-29T15:17:09.000Z | #include "geotiff.h"
#include "cpl_conv.h" // for CPLMalloc()
#include "file_accessor.h"
#include "gdal_frmts.h"
#include "grid.h"
#include "lambert_conformal_grid.h"
#include "lambert_equal_area_grid.h"
#include "latitude_longitude_grid.h"
#include "logger.h"
#include "plugin_factory.h"
#include "producer.h"
#include "reduced_gaussian_grid.h"
#include "s3.h"
#include "stereographic_grid.h"
#include "timer.h"
#include "transverse_mercator_grid.h"
#include "util.h"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <ogr_spatialref.h>
#include <thread>
#include "plugin_factory.h"
#include "radon.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include "gdal_priv.h"
#pragma GCC diagnostic pop
using namespace himan;
using namespace himan::plugin;
struct GDALDatasetCloser
{
void operator()(GDALDataset* ds) const
{
GDALClose(ds);
}
};
typedef std::unique_ptr<GDALDataset, GDALDatasetCloser> GDALDatasetPtr;
void CheckGDALError(OGRErr errarg, const char* file, const int line);
#define GDAL_CHECK(errarg) CheckGDALError(errarg, __FILE__, __LINE__)
inline void CheckGDALError(OGRErr errarg, const char* file, const int line)
{
if (errarg != OGRERR_NONE)
{
std::cerr << "Error at " << file << "(" << line << "): " << CPLGetLastErrorMsg() << std::endl;
himan::Abort();
}
}
template <typename T>
GDALDataType TypeToGDALType();
template <>
GDALDataType TypeToGDALType<unsigned char>()
{
return GDT_Byte;
}
template <>
GDALDataType TypeToGDALType<short>()
{
return GDT_Int16;
}
template <>
GDALDataType TypeToGDALType<float>()
{
return GDT_Float32;
}
template <>
GDALDataType TypeToGDALType<double>()
{
return GDT_Float64;
}
template <typename T>
T ConvertTo(const std::string& str)
{
std::istringstream ss(str);
T num;
ss >> num;
return num;
}
static std::once_flag oflag;
void CreateDirectory(const std::string& filename)
{
namespace fs = boost::filesystem;
fs::path pathname(filename);
if (!pathname.parent_path().empty() && !fs::is_directory(pathname.parent_path()))
{
fs::create_directories(pathname.parent_path());
}
}
geotiff::geotiff()
{
call_once(oflag, [&]() {
GDALRegister_GTiff();
GDALRegister_COG();
// Check environment for AWS variables
// GDAL requires Himan uses
// * AWS_S3_ENDPOINT S3_HOSTNAME
// * AWS_ACCESS_KEY_ID S3_ACCESS_KEY_ID
// * AWS_SECRET_ACCESS_KEY S3_SECRET_ACCESS_KEY
// * AWS_SESSION_TOKEN S3_SESSION_TOKEN
//
// if latter is found, copy it to former
const std::vector<std::pair<std::string, std::string>> keys{{"S3_HOSTNAME", "AWS_S3_ENDPOINT"},
{"S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID"},
{"S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY"},
{"S3_SESSION_TOKEN", "AWS_SESSION_TOKEN"}};
for (const auto& key : keys)
{
try
{
const std::string val = util::GetEnv(key.first);
setenv(key.second.c_str(), val.c_str(), 0);
}
catch (...)
{
}
}
});
itsLogger = logger("geotiff");
}
std::pair<HPWriteStatus, file_information> geotiff::ToFile(info<double>& anInfo)
{
return ToFile<double>(anInfo);
}
void WriteAreaAndGrid(GDALDataset& ds, const himan::regular_grid& g, const producer& prod, const configuration& conf)
{
const point fp = g.Projected(g.TopLeft());
double adfGeoTransform[6] = {fp.X(), g.Di(), 0, fp.Y(), 0, -1 * g.Dj()};
GDAL_CHECK(ds.SetGeoTransform(adfGeoTransform));
OGRSpatialReference sp;
GDAL_CHECK(sp.importFromProj4(g.Proj4String().c_str()));
// If earth shape is WGS84, set datum also to WGS84, since AFAIK
// no other datum uses it as ellipsoid.
if (g.EarthShape().Name() == "WGS84")
{
sp.SetWellKnownGeogCS("WGS84");
}
const std::string geom = conf.TargetGeomName().empty() ? prod.Name() : conf.TargetGeomName();
GDAL_CHECK(sp.SetProjCS(geom.c_str()));
GDAL_CHECK(ds.SetSpatialRef(&sp));
}
template <typename T>
void WriteData(GDALDataset& ds, const info<T>& anInfo, int bandNo)
{
const int ni = static_cast<int>(anInfo.Data().SizeX());
const int nj = static_cast<int>(anInfo.Data().SizeY());
const GDALDataType dtype = TypeToGDALType<T>();
GDALRasterBand* poBand = ds.GetRasterBand(bandNo);
if (bandNo == 1)
{
// Only for first band, because otherwise:
// band 2: Setting nodata to nan on band 2, but band 1 has nodata at nan. The TIFFTAG_GDAL_NODATA only support
// one value per dataset. This value of nan will be used for all bands on re-opening
GDAL_CHECK(poBand->SetNoDataValue(anInfo.Data().MissingValue()));
}
matrix<T> values = anInfo.Data();
if (dynamic_cast<regular_grid*>(anInfo.Grid().get())->ScanningMode() != kTopLeft)
{
util::Flip<T>(values);
}
if (poBand->RasterIO(GF_Write, 0, 0, ni, nj, values.ValuesAsPOD(), ni, nj, dtype, 0, 0) != OGRERR_NONE)
{
logger logr("geotiff");
logr.Error("File write failed");
himan::Abort();
}
}
void WriteBandMetadata(GDALRasterBand* b, const forecast_type& ftype, const forecast_time& ftime, const level& lvl,
const param& par)
{
GDAL_CHECK(b->SetMetadataItem("forecast_type", static_cast<std::string>(ftype).c_str(), nullptr));
GDAL_CHECK(
b->SetMetadataItem("origin_time", ftime.OriginDateTime().String("%Y-%m-%dT%H:%M:%S+00:00").c_str(), nullptr));
GDAL_CHECK(
b->SetMetadataItem("valid_time", ftime.ValidDateTime().String("%Y-%m-%dT%H:%M:%S+00:00").c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("step", ftime.Step().String("%02h:%02M:%02S").c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("level", static_cast<std::string>(lvl).c_str(), nullptr));
GDAL_CHECK(b->SetMetadataItem("param_name", par.Name().c_str(), nullptr));
if (par.Aggregation().Type() != kUnknownAggregationType)
{
GDAL_CHECK(b->SetMetadataItem("aggregation", static_cast<std::string>(par.Aggregation()).c_str(), nullptr));
}
if (par.ProcessingType().Type() != kUnknownProcessingType)
{
GDAL_CHECK(
b->SetMetadataItem("processing_type", static_cast<std::string>(par.ProcessingType()).c_str(), nullptr));
}
}
template <typename T>
std::pair<HPWriteStatus, file_information> geotiff::ToFile(info<T>& anInfo)
{
if (anInfo.Grid()->Class() == kIrregularGrid && anInfo.Grid()->Type() != kReducedGaussian)
{
itsLogger.Error(fmt::format("Unable to write irregular grid of type {} to geotiff",
HPGridTypeToString.at(anInfo.Grid()->Type())));
throw kInvalidWriteOptions;
}
if (itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem ||
itsWriteOptions.configuration->WriteMode() != kSingleGridToAFile)
{
return std::make_pair(HPWriteStatus::kPending, file_information());
}
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
file_information finfo;
finfo.file_location = util::MakeFileName(anInfo, *itsWriteOptions.configuration);
finfo.file_type = kGeoTIFF;
finfo.storage_type = itsWriteOptions.configuration->WriteStorageType();
// We use Create() method as there is nothing to copy from
// (CreateCopy() being the alternative)
const regular_grid* g = dynamic_cast<regular_grid*>(anInfo.Grid().get());
// Enable compression
char** opts = NULL;
opts = CSLSetNameValue(opts, "COMPRESS", "DEFLATE");
const GDALDataType dtype = TypeToGDALType<T>();
CreateDirectory(finfo.file_location);
auto ds = GDALDatasetPtr(driver->Create(finfo.file_location.c_str(), static_cast<int>(anInfo.Data().SizeX()),
static_cast<int>(anInfo.Data().SizeY()), 1, dtype, opts));
WriteAreaAndGrid(*ds, *g, anInfo.Producer(), *itsWriteOptions.configuration);
GDAL_CHECK(ds->SetMetadataItem("producer_id", fmt::format("{}", anInfo.Producer().Id()).c_str(), nullptr));
WriteBandMetadata(ds->GetRasterBand(1), anInfo.ForecastType(), anInfo.Time(), anInfo.Level(), anInfo.Param());
WriteData(*ds, anInfo, 1);
itsLogger.Info(fmt::format("Wrote file '{}'", finfo.file_location));
return std::make_pair(HPWriteStatus::kFinished, finfo);
}
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<double>(info<double>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<float>(info<float>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<short>(info<short>&);
template std::pair<HPWriteStatus, file_information> geotiff::ToFile<unsigned char>(info<unsigned char>&);
template <typename T>
std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile(const std::vector<info<T>>& infos)
{
// No "pending" checking here
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
std::map<std::string, std::vector<size_t>> list;
for (size_t i = 0; i < infos.size(); i++)
{
const auto& info = infos[i];
const std::string fname = util::MakeFileName<T>(info, *itsWriteOptions.configuration);
auto& elem = list[fname];
elem.push_back(i);
}
std::vector<std::pair<HPWriteStatus, file_information>> ret(infos.size());
// If writing to s3, first write all data to a memory location
// where it can be picked up. Use gdal's /vsimem feature for this.
const std::string vrt =
(itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem) ? "/vsimem/" : "";
for (const auto& m : list)
{
const auto& first = infos[m.second[0]];
file_information finfo;
finfo.file_location = m.first;
finfo.file_type = kGeoTIFF;
finfo.storage_type = itsWriteOptions.configuration->WriteStorageType();
const regular_grid* g = dynamic_cast<regular_grid*>(first.Grid().get());
// Enable compression
char** opts = NULL;
opts = CSLSetNameValue(opts, "COMPRESS", "DEFLATE");
const GDALDataType dtype = TypeToGDALType<T>();
if (itsWriteOptions.configuration->WriteStorageType() != kS3ObjectStorageSystem)
{
CreateDirectory(finfo.file_location);
}
auto ds = GDALDatasetPtr(driver->Create(
fmt::format("{}{}", vrt, finfo.file_location).c_str(), static_cast<int>(first.Data().SizeX()),
static_cast<int>(first.Data().SizeY()), static_cast<int>(m.second.size()), dtype, opts));
if (!ds)
{
himan::Abort();
}
GDAL_CHECK(ds->SetMetadataItem("producer_id", fmt::format("{}", first.Producer().Id()).c_str(), nullptr));
WriteAreaAndGrid(*ds, *g, first.Producer(), *itsWriteOptions.configuration);
int j = 1;
for (const size_t i : m.second)
{
WriteBandMetadata(ds->GetRasterBand(j), infos[i].ForecastType(), infos[i].Time(), infos[i].Level(),
infos[i].Param());
WriteData(*ds, infos[i], j);
finfo.message_no = j++;
ret[i] = std::make_pair(HPWriteStatus::kFinished, finfo);
}
if (itsWriteOptions.configuration->WriteStorageType() == kS3ObjectStorageSystem)
{
ds->FlushCache();
// Earlier data was written to memory, now get a pointer to that memory block
// and pass it to himan::s3
VSILFILE* inmem = VSIFOpenL(fmt::format("{}/{}", vrt, finfo.file_location).c_str(), "rb");
himan::buffer buff;
// Get file size
VSIFSeekL(inmem, 0, SEEK_END);
buff.length = VSIFTellL(inmem);
VSIFSeekL(inmem, 0, SEEK_SET);
itsLogger.Trace(fmt::format("In-mem file size is {} bytes", buff.length));
buff.data = static_cast<unsigned char*>(malloc(buff.length));
// Read contents
VSIFReadL(buff.data, buff.length, 1, inmem);
s3::WriteObject(finfo.file_location, buff);
itsLogger.Info(fmt::format("Wrote file 's3://{}'", finfo.file_location));
}
else
{
itsLogger.Info(fmt::format("Wrote file '{}'", finfo.file_location));
}
}
return ret;
}
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<double>(
const std::vector<info<double>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<float>(
const std::vector<info<float>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<short>(
const std::vector<info<short>>&);
template std::vector<std::pair<HPWriteStatus, file_information>> geotiff::ToFile<unsigned char>(
const std::vector<info<unsigned char>>&);
std::unique_ptr<grid> ReadAreaAndGrid(GDALDataset* ds)
{
logger log("geotiff");
const int ni = ds->GetRasterXSize(), nj = ds->GetRasterYSize();
double adfGeoTransform[6];
if (ds->GetGeoTransform(adfGeoTransform) != CE_None)
{
log.Error("File does not contain geo transformation coefficients");
throw kFileMetaDataNotFound;
}
const double di = adfGeoTransform[1];
const double dj = fabs(adfGeoTransform[5]);
const point fp(adfGeoTransform[0], adfGeoTransform[3]);
const HPScanningMode sm = (adfGeoTransform[5] < 0) ? kTopLeft : kBottomLeft;
ASSERT(di > 0);
std::string proj = ds->GetProjectionRef();
if (proj.empty())
{
log.Fatal("File does not contain spatial metadata");
throw kFileMetaDataNotFound;
}
OGRSpatialReference spRef(proj.c_str());
const char* projptr = spRef.GetAttrValue("PROJECTION");
if (projptr != nullptr)
{
const std::string projection = spRef.GetAttrValue("PROJECTION");
if (projection == SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA)
{
return std::unique_ptr<lambert_equal_area_grid>(new lambert_equal_area_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
else if (projection == SRS_PT_TRANSVERSE_MERCATOR)
{
return std::unique_ptr<transverse_mercator_grid>(new transverse_mercator_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
else if (projection == SRS_PT_LAMBERT_CONFORMAL_CONIC_1SP || projection == SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP)
{
return std::unique_ptr<lambert_conformal_grid>(new lambert_conformal_grid(
sm, fp, ni, nj, di, dj, std::unique_ptr<OGRSpatialReference>(spRef.Clone()), true));
}
log.Error(fmt::format("Unsupported projection: {}", projection));
}
else if (spRef.IsGeographic())
{
// No projection -- latlon with some datum
// spRef.GetAttrValue("DATUM|SPHEROID|AUTHORITY")
OGRErr erra = 0, errb = 0;
const double A = spRef.GetSemiMajor(&erra);
const double B = spRef.GetSemiMinor(&errb);
earth_shape<double> es;
if (erra != OGRERR_NONE || errb != OGRERR_NONE)
{
log.Error("Unable to extract datum information from file");
}
else
{
es = earth_shape<double>(A, B);
}
return std::unique_ptr<latitude_longitude_grid>(new latitude_longitude_grid(sm, fp, ni, nj, di, dj, es));
}
throw kFileMetaDataNotFound;
}
param ReadParam(const std::map<std::string, std::string>& meta, const producer& prod, const param& par)
{
logger logr("geotiff");
std::string param_value;
for (const auto& m : meta)
{
if (m.first == "param_name")
{
param_value = m.second;
break;
}
}
if (param_value.empty())
{
return par;
}
auto r = GET_PLUGIN(radon);
auto parameter = r->RadonDB().GetParameterFromGeoTIFF(prod.Id(), param_value);
if (parameter.empty() || parameter["name"].empty())
{
logr.Trace(
fmt::format("Parameter information matching '{}' not found from table 'param_geotiff'", param_value));
return par;
}
param p(parameter["name"]);
p.Id(std::stoi(parameter["id"]));
p.InterpolationMethod(par.InterpolationMethod());
return p;
}
level ReadLevel(const std::map<std::string, std::string>& meta, const level& lvl)
{
HPLevelType type = HPLevelType::kUnknownLevel;
double value = kHPMissingValue, value2 = kHPMissingValue;
for (const auto& m : meta)
{
if (m.first == "level")
{
const auto tokens = util::Split(m.second, "/");
type = static_cast<HPLevelType>(stoi(tokens[0]));
value = stod(tokens[1]);
if (tokens.size() == 3)
{
value2 = stod(tokens[2]);
}
break;
}
}
if (type != kUnknownLevel)
{
return level(type, value, value2);
}
return lvl;
}
forecast_type ReadForecastType(const std::map<std::string, std::string>& meta, const forecast_type& ftype)
{
HPForecastType type = HPForecastType::kUnknownType;
double value = kHPMissingValue;
for (const auto& m : meta)
{
if (m.first == "forecast_type")
{
const auto tokens = util::Split(m.second, "/");
type = static_cast<HPForecastType>(stoi(tokens[1]));
value = stod(tokens[1]);
break;
}
}
if (type != kUnknownType)
{
return forecast_type(type, value);
}
return ftype;
}
void SQLTimeMaskToCTimeMask(std::string& sqlTimeMask)
{
boost::replace_all(sqlTimeMask, "YYYY", "%Y");
boost::replace_all(sqlTimeMask, "MM", "%m");
boost::replace_all(sqlTimeMask, "DD", "%d");
boost::replace_all(sqlTimeMask, "hh", "%H");
boost::replace_all(sqlTimeMask, "mm", "%M");
}
forecast_time ReadTime(const std::map<std::string, std::string>& meta, const forecast_time& ftime)
{
raw_time origintime = ftime.OriginDateTime();
raw_time validtime = ftime.ValidDateTime();
std::string origintimestr, validtimestr, mask;
for (const auto& m : meta)
{
if (m.first == "analysis_time")
{
origintimestr = m.second;
}
else if (m.first == "valid_time")
{
validtimestr = m.second;
}
else if (m.first == "time_mask")
{
mask = m.second;
}
}
if (mask.find("YYYY") != std::string::npos)
{
SQLTimeMaskToCTimeMask(mask);
}
if (!origintimestr.empty() && !mask.empty())
{
origintime = raw_time(origintimestr, mask);
}
if (!validtimestr.empty() && !mask.empty())
{
validtime = raw_time(validtimestr, mask);
}
return forecast_time(origintime, validtime);
}
std::map<std::string, std::string> ParseMetadata(char** mdata, const producer& prod)
{
std::map<std::string, std::string> ret;
if (mdata == nullptr)
{
return ret;
}
// First check keys with Himan-known 'standard' names
const std::vector<std::string> standardNames{"forecast_type", "level"};
for (const auto& keyName : standardNames)
{
const char* m = CSLFetchNameValue(mdata, keyName.c_str());
if (m != nullptr)
{
ret[keyName] = std::string(m);
}
}
std::string query =
fmt::format("SELECT attribute, key, mask FROM geotiff_metadata WHERE producer_id = {}", prod.Id());
auto r = GET_PLUGIN(radon);
r->RadonDB().Query(query);
logger log("geotiff");
while (true)
{
const auto row = r->RadonDB().FetchRow();
if (row.empty())
{
break;
}
const auto attribute = row[0];
const auto keyName = row[1];
const auto keyMask = row[2];
std::string metadata;
if (keyName.empty() == false)
{
// metadata consists of key=value pairs
const char* m = CSLFetchNameValue(mdata, keyName.c_str());
if (m == nullptr)
{
log.Trace("Did not find expected key '" + keyName + "' from metadata");
continue;
}
metadata = std::string(m);
}
else if (mdata != nullptr)
{
// no defined keys for metadata elements
// in database this means that 'key' column is empty string
metadata = std::string(*mdata);
}
else
{
continue;
}
// Try to extract information from free-form text fields
// attribute: a metadata attribute name that Himan understands, like 'analysis_time'
// keyName: name of the metadata element in geotiff file
// keyMask: optional mask for the value of the key, if only specific value needs
// to be extraced, regular expressions are used
if (keyMask.empty())
{
ret[attribute] = metadata;
}
else
{
const boost::regex re(keyMask);
boost::smatch what;
if (boost::regex_search(metadata, what, re) == false || what.size() == 0)
{
log.Warning(fmt::format("Regex did not match for attribute {}", attribute));
log.Warning(fmt::format("Regex: '{}' Metadata: '{}'", keyMask, metadata));
}
if (what.size() != 2)
{
log.Fatal(fmt::format("Regex matched too many times: {}", what.size() - 1));
himan::Abort();
}
log.Debug(fmt::format("Regex match for {}: {}", attribute, std::string(what[1])));
ret[attribute] = what[1];
}
}
return ret;
}
template <typename T>
void ReadData(GDALRasterBand* poBand, matrix<T>& mat, const std::map<std::string, std::string>& meta)
{
if (meta.find("missing_value") != meta.end())
{
mat.MissingValue(ConvertTo<T>(meta.at("missing_value")));
}
else
{
mat.MissingValue(static_cast<T>(poBand->GetNoDataValue(nullptr)));
}
ASSERT(poBand->GetXSize() == static_cast<int>(mat.SizeX()));
ASSERT(poBand->GetYSize() == static_cast<int>(mat.SizeY()));
int nXSize = poBand->GetXSize();
int nYSize = poBand->GetYSize();
if (poBand->RasterIO(GF_Read, 0, 0, nXSize, nYSize, mat.ValuesAsPOD(), nXSize, nYSize, TypeToGDALType<T>(), 0, 0) !=
CE_None)
{
throw std::runtime_error("Read failed");
}
const T offset = static_cast<T>(poBand->GetOffset(nullptr));
const T scale = static_cast<T>(poBand->GetScale(nullptr));
// Change missingvalue to our own
mat.MissingValue(MissingValue<T>());
// Apply scale and base
if (offset != 0 || scale != 1)
{
auto& data = mat.Values();
for_each(data.begin(), data.end(), [=](T& val) { val = static_cast<T>(val * scale + offset); });
}
}
std::vector<std::shared_ptr<info<double>>> geotiff::FromFile(const file_information& theInputFile,
const search_options& options, bool validate,
bool readData) const
{
return FromFile<double>(theInputFile, options, validate, readData);
}
template <typename T>
std::vector<std::shared_ptr<info<T>>> geotiff::FromFile(const file_information& theInputFile,
const search_options& options, bool validate,
bool readData) const
{
std::vector<std::shared_ptr<himan::info<T>>> infos;
auto ParseFileName = [](const file_information& finfo) {
std::string ret = finfo.file_location;
if (finfo.storage_type == kS3ObjectStorageSystem)
{
const auto pos = ret.find("s3://");
if (pos != std::string::npos)
{
ret = ret.erase(pos, 5);
}
ret = fmt::format("/vsis3_streaming/{}", ret);
}
return ret;
};
auto ds =
GDALDatasetPtr(reinterpret_cast<GDALDataset*>(GDALOpen(ParseFileName(theInputFile).c_str(), GA_ReadOnly)));
if (ds == nullptr)
{
itsLogger.Error("Failed to open dataset from " + theInputFile.file_location);
return infos;
}
auto meta = ParseMetadata(ds->GetMetadata(), options.prod); // Get full dataset metadata
if (meta.size() == 0)
{
itsLogger.Trace(
fmt::format("No elements recognized from global metadata from '{}'", theInputFile.file_location));
}
auto area = ReadAreaAndGrid(ds.get());
if (area == nullptr)
{
return infos;
}
// "first guess" metadata from file metadata
auto par = ReadParam(meta, options.prod, options.param);
auto lvl = ReadLevel(meta, options.level);
auto ftype = ReadForecastType(meta, options.ftype);
auto ftime = ReadTime(meta, options.time);
auto MakeInfoFromGeoTIFFBand = [&](GDALRasterBand* poBand) -> std::shared_ptr<info<T>> {
// Read possible metadata from band
auto bmeta = ParseMetadata(poBand->GetMetadata(), options.prod);
auto bpar = ReadParam(bmeta, options.prod, par);
auto blvl = ReadLevel(bmeta, lvl);
auto bftype = ReadForecastType(bmeta, ftype);
auto bftime = ReadTime(bmeta, ftime);
if (bpar == param() || blvl == level() || bftype == forecast_type() || bftime == forecast_time())
{
itsLogger.Warning("Failed to gather all required metadata");
itsLogger.Warning("Param: " + bpar.Name());
itsLogger.Warning("Level: " + static_cast<std::string>(blvl));
itsLogger.Warning("Time: " + bftime.OriginDateTime().String() + " step: " + bftime.Step().String("%H:%M"));
itsLogger.Warning("Forecast type: " + static_cast<std::string>(bftype));
throw kFileDataNotFound;
}
if (validate && options.time != bftime)
{
itsLogger.Warning("Time does not match: " + options.time.OriginDateTime().String() + " step " +
options.time.Step().String("%02H:%02M:%02S") + " vs " + bftime.OriginDateTime().String() +
" step " + bftime.Step().String("%02H:%02M:%02S"));
}
if (validate && options.level != blvl)
{
itsLogger.Warning("Level does not match");
}
if (validate && options.ftype != bftype)
{
itsLogger.Warning("Forecast type does not match");
}
if (validate && options.param != bpar)
{
itsLogger.Warning("param does not match: " + options.param.Name() + " vs " + bpar.Name());
}
auto anInfo = std::make_shared<info<T>>(bftype, bftime, blvl, bpar);
auto b = std::make_shared<base<T>>();
b->grid = std::shared_ptr<grid>(area->Clone());
anInfo->Create(b, true);
anInfo->Producer(options.prod);
if (readData)
{
ReadData<T>(poBand, anInfo->Data(), meta);
}
return anInfo;
};
if (theInputFile.message_no == boost::none)
{
for (int bandNo = 1; bandNo <= ds->GetRasterCount(); bandNo++)
{
itsLogger.Info("Read from file '" + theInputFile.file_location + "' band# " + std::to_string(bandNo));
GDALRasterBand* poBand = ds->GetRasterBand(bandNo);
try
{
infos.push_back(MakeInfoFromGeoTIFFBand(poBand));
}
catch (const HPExceptionType& e)
{
}
}
}
else
{
itsLogger.Info("Read from file '" + theInputFile.file_location + "' band# " +
std::to_string(theInputFile.message_no.get()));
GDALRasterBand* poBand = ds->GetRasterBand(static_cast<int>(theInputFile.message_no.get()));
try
{
infos.push_back(MakeInfoFromGeoTIFFBand(poBand));
}
catch (...)
{
}
}
return infos;
}
template std::vector<std::shared_ptr<info<double>>> geotiff::FromFile<double>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<float>>> geotiff::FromFile<float>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<short>>> geotiff::FromFile<short>(const file_information&,
const search_options&, bool, bool) const;
template std::vector<std::shared_ptr<info<unsigned char>>> geotiff::FromFile<unsigned char>(const file_information&,
const search_options&, bool,
bool) const;
| 29.489978 | 120 | 0.663998 |
321a1cd6e50b7fda1c89b6fe67bea9189add0552 | 24,431 | cpp | C++ | be/src/olap/base_expansion_handler.cpp | DiffBlue-benchmarks/baidu-palo | 27e021b0a9616a795a650026ed8c59aea7d09841 | [
"Apache-2.0"
] | 1 | 2021-07-14T07:30:48.000Z | 2021-07-14T07:30:48.000Z | be/src/olap/base_expansion_handler.cpp | DiffBlue-benchmarks/baidu-palo | 27e021b0a9616a795a650026ed8c59aea7d09841 | [
"Apache-2.0"
] | null | null | null | be/src/olap/base_expansion_handler.cpp | DiffBlue-benchmarks/baidu-palo | 27e021b0a9616a795a650026ed8c59aea7d09841 | [
"Apache-2.0"
] | 1 | 2018-06-29T06:40:03.000Z | 2018-06-29T06:40:03.000Z | // Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "olap/base_expansion_handler.h"
#include <algorithm>
#include <list>
#include <map>
#include <string>
#include <vector>
#include "olap/delete_handler.h"
#include "olap/merger.h"
#include "olap/olap_data.h"
#include "olap/olap_engine.h"
#include "olap/olap_header.h"
#include "olap/olap_index.h"
#include "olap/olap_table.h"
#include "olap/utils.h"
#include "util/palo_metrics.h"
using std::list;
using std::map;
using std::string;
using std::vector;
namespace palo {
OLAPStatus BaseExpansionHandler::init(SmartOLAPTable table, bool is_manual_trigger) {
// 表在首次查询或PUSH等操作时,会被加载到内存
// 如果表没有被加载,表明该表上目前没有任何操作,所以不进行BE操作
if (!table->is_loaded()) {
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
OLAP_LOG_TRACE("init base expansion handler. [table=%s]", table->full_name().c_str());
_table = table;
// 1. 尝试取得base expansion的锁
if (!_try_base_expansion_lock()) {
OLAP_LOG_WARNING("another base expansion is running. [table=%s]",
table->full_name().c_str());
return OLAP_ERR_BE_TRY_BE_LOCK_ERROR;
}
// 2. 检查是否满足base expansion触发策略
OLAP_LOG_TRACE("check whether satisfy base expansion policy.");
bool is_policy_satisfied = false;
vector<Version> candidate_versions;
is_policy_satisfied = _check_whether_satisfy_policy(is_manual_trigger, &candidate_versions);
// 2.1 如果不满足触发策略,则直接释放base expansion锁, 返回错误码
if (!is_policy_satisfied) {
_release_base_expansion_lock();
return OLAP_ERR_BE_NO_SUITABLE_VERSION;
}
// 2.2 如果满足触发策略,触发base expansion
// 不释放base expansion锁, 在run()完成之后再释放
if (!_validate_need_merged_versions(candidate_versions)) {
OLAP_LOG_FATAL("error! invalid need merged versions");
_release_base_expansion_lock();
return OLAP_ERR_BE_INVALID_NEED_MERGED_VERSIONS;
}
_need_merged_versions = candidate_versions;
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::run() {
OLAP_LOG_INFO("start base expansion. [table=%s; old_base_version=%d; new_base_version=%d]",
_table->full_name().c_str(),
_old_base_version.second,
_new_base_version.second);
OLAPStatus res = OLAP_SUCCESS;
OlapStopWatch stage_watch;
_table->set_base_expansion_status(BASE_EXPANSION_RUNNING, _new_base_version.second);
// 1. 计算新base的version hash
VersionHash new_base_version_hash;
res = _table->compute_all_versions_hash(_need_merged_versions, &new_base_version_hash);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to calculate new base version hash.[table=%s; new_base_version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
OLAP_LOG_TRACE("new_base_version_hash", "%ld", new_base_version_hash);
// 2. 获取生成新base需要的data sources
vector<IData*> base_data_sources;
_table->acquire_data_sources_by_versions(_need_merged_versions, &base_data_sources);
if (base_data_sources.empty()) {
OLAP_LOG_WARNING("fail to acquire need data sources. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return OLAP_ERR_BE_ACQUIRE_DATA_SOURCES_ERROR;
}
if (PaloMetrics::be_merge_delta_num() != NULL) {
PaloMetrics::be_merge_delta_num()->increment(_need_merged_versions.size());
int64_t merge_size = 0;
for (IData* i_data : base_data_sources) {
merge_size += i_data->olap_index()->data_size();
}
PaloMetrics::be_merge_size()->increment(merge_size);
}
// 保存生成base文件时候计算的selectivities
vector<uint32_t> selectivities;
// 保存生成base文件时候累积的行数
uint64_t row_count = 0;
// 3. 执行base expansion
// 执行过程可能会持续比较长时间
stage_watch.reset();
res = _do_base_expansion(new_base_version_hash,
&base_data_sources,
&selectivities,
&row_count);
// 释放不再使用的IData对象
_table->release_data_sources(&base_data_sources);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to do base version. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
OLAP_LOG_TRACE("elapsed time of doing base version", "%ldus",
stage_watch.get_elapse_time_us());
// 4. 使新生成的base生效,并删除不再需要版本对应的文件
_obtain_header_wrlock();
vector<OLAPIndex*> unused_olap_indices;
// 使得新生成的各个Version生效, 如果失败掉则需要清理掉已经生成的Version文件
res = _update_header(selectivities, row_count, &unused_olap_indices);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to update header. [table=%s; version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
_cleanup();
return res;
}
_release_header_lock();
_delete_old_files(&unused_olap_indices);
// validate that delete action is right
// if error happened, sleep 1 hour. Report a fatal log every 1 minute
if (_validate_delete_file_action() != OLAP_SUCCESS) {
int sleep_count = 0;
while (true) {
if (sleep_count >= 60) {
break;
}
++sleep_count;
OLAP_LOG_FATAL("base expansion's delete action has error.sleep 1 minute...");
sleep(60);
}
_cleanup();
return OLAP_ERR_BE_ERROR_DELETE_ACTION;
}
_table->set_base_expansion_status(BASE_EXPANSION_WAITING, -1);
_release_base_expansion_lock();
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::_exclude_not_expired_delete(
const vector<Version>& need_merged_versions,
vector<Version>* candidate_versions) {
const int64_t delete_delta_expire_time = config::delete_delta_expire_time * 60;
OLAPStatus res = OLAP_SUCCESS;
for (unsigned int index = 0; index < need_merged_versions.size(); ++index) {
Version temp = need_merged_versions[index];
int64_t file_creation_time = 0;
res = _table->version_creation_time(temp, &file_creation_time);
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("table doesn't have version. [table=%s; version=%d-%d]",
_table->full_name().c_str(), temp.first, temp.second);
return res;
}
int64_t file_existed_time = time(NULL) - file_creation_time;
// 从小版本号往大版本号查找;找到第1个没有过期的delete版本时,退出
if (_table->is_delete_data_version(temp)
&& file_existed_time < delete_delta_expire_time) {
OLAP_LOG_INFO("delete version is not expired."
"[delete_version=%d; existed_time=%ld; expired_time=%ld]",
temp.first, file_existed_time,
delete_delta_expire_time);
break;
}
candidate_versions->push_back(temp);
}
return OLAP_SUCCESS;
}
static bool version_comparator(const Version& lhs, const Version& rhs) {
return lhs.second < rhs.second;
}
bool BaseExpansionHandler::_check_whether_satisfy_policy(bool is_manual_trigger,
vector<Version>* candidate_versions) {
_obtain_header_rdlock();
int32_t cumulative_layer_point = _table->cumulative_layer_point();
if (cumulative_layer_point == -1) {
OLAP_LOG_FATAL("tablet has an unreasonable cumulative layer point. "
"[tablet='%s' cumulative_layer_point=%d]",
_table->full_name().c_str(), cumulative_layer_point);
_release_header_lock();
return false;
}
// 为了后面计算方便,我们在这里先将cumulative_layer_point减1
--cumulative_layer_point;
vector<Version> path_versions;
if (OLAP_SUCCESS != _table->select_versions_to_span(Version(0, cumulative_layer_point),
&path_versions)) {
OLAP_LOG_WARNING("fail to select shortest version path. [start=%d end=%d]",
0, cumulative_layer_point);
_release_header_lock();
return false;
}
// be_layer_point应该为cumulative_layer_point之前,倒数第2个cumulative文件的end version
int64_t base_creation_time = 0;
size_t base_size = 0;
int32_t be_layer_point = -1;
for (unsigned int index = 0; index < path_versions.size(); ++index) {
Version temp = path_versions[index];
// base文件
if (temp.first == 0) {
_old_base_version = temp;
base_size = _table->get_version_entity_by_version(temp).data_size;
base_creation_time = _table->file_version(index).creation_time();
continue;
}
if (temp.second == cumulative_layer_point) {
be_layer_point = temp.first - 1;
_latest_cumulative = temp;
_new_base_version = Version(0, be_layer_point);
}
}
// 只有1个base文件和1个delta文件
if (be_layer_point == -1) {
OLAP_LOG_TRACE("can't do base expansion: no cumulative files. "
"[table=%s; base_version=0-%d; cumulative_layer_point=%d]",
_table->full_name().c_str(),
_old_base_version.second,
cumulative_layer_point + 1);
_release_header_lock();
return false;
}
// 只有1个cumulative文件
if (be_layer_point == _old_base_version.second) {
OLAP_LOG_TRACE("can't do base expansion: only one cumulative file. "
"[table=%s; base_version=0-%d; cumulative_layer_point=%d]",
_table->full_name().c_str(),
_old_base_version.second,
cumulative_layer_point + 1);
_release_header_lock();
return false;
}
// 使用最短路径算法,选择可合并的cumulative版本
vector<Version> need_merged_versions;
if (OLAP_SUCCESS != _table->select_versions_to_span(_new_base_version,
&need_merged_versions)) {
OLAP_LOG_WARNING("fail to select shortest version path. [start=%d end=%d]",
_new_base_version.first, _new_base_version.second);
_release_header_lock();
return false;
}
std::sort(need_merged_versions.begin(), need_merged_versions.end(), version_comparator);
// 如果是手动执行START_BASE_EXPANSION命令,则不检查base expansion policy,
// 也不考虑删除版本过期问题, 只要有可以合并的cumulative,就执行base expansion
if (is_manual_trigger) {
OLAP_LOG_TRACE("manual triggle base expansion. [table=%s]", _table->full_name().c_str());
*candidate_versions = need_merged_versions;
_release_header_lock();
return true;
}
if (_exclude_not_expired_delete(need_merged_versions, candidate_versions) != OLAP_SUCCESS) {
OLAP_LOG_WARNING("failed to exclude not expired delete version.");
_release_header_lock();
return false;
}
if (candidate_versions->size() != need_merged_versions.size()) {
OLAP_LOG_INFO("reset new base version. "
"[previous_new_base_version=0-%d; new_base_version=0-%d]",
_new_base_version.second, candidate_versions->rbegin()->second);
_new_base_version = Version(0, candidate_versions->rbegin()->second);
}
// 统计可合并cumulative版本文件的总大小
size_t cumulative_total_size = 0;
for (vector<Version>::const_iterator version_iter = candidate_versions->begin();
version_iter != candidate_versions->end(); ++version_iter) {
Version temp = *version_iter;
// 跳过base文件
if (temp.first == 0) {
continue;
}
// cumulative文件
cumulative_total_size += _table->get_version_entity_by_version(temp).data_size;
}
_release_header_lock();
// 检查是否满足base expansion的触发条件
// 满足以下条件时触发base expansion: 触发条件1 || 触发条件2 || 触发条件3
// 触发条件1:cumulative文件个数超过一个阈值
const uint32_t be_policy_cumulative_files_number = config::be_policy_cumulative_files_number;
// candidate_versions中包含base文件,所以这里减1
if (candidate_versions->size() - 1 >= be_policy_cumulative_files_number) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; "
"cumualtive_files_number=%d; policy_cumulative_files_number=%d]",
_table->full_name().c_str(),
candidate_versions->size() - 1,
be_policy_cumulative_files_number);
return true;
}
// 触发条件2:所有cumulative文件的大小超过base文件大小的某一比例
const double be_policy_cumulative_base_ratio = config::be_policy_cumulative_base_ratio;
double cumulative_base_ratio = static_cast<double>(cumulative_total_size) / base_size;
if (cumulative_base_ratio > be_policy_cumulative_base_ratio) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; cumualtive_total_size=%d; "
"base_size=%d; cumulative_base_ratio=%f; policy_ratio=%f]",
_table->full_name().c_str(),
cumulative_total_size,
base_size,
cumulative_base_ratio,
be_policy_cumulative_base_ratio);
return true;
}
// 触发条件3:距离上一次进行base expansion已经超过设定的间隔时间
const uint32_t be_policy_be_interval = config::be_policy_be_interval_seconds;
int64_t interval_since_last_be = time(NULL) - base_creation_time;
if (interval_since_last_be > be_policy_be_interval) {
OLAP_LOG_INFO("satisfy the base expansion policy. [table=%s; "
"interval_since_last_be=%ld; policy_interval=%ld]",
_table->full_name().c_str(),
interval_since_last_be, be_policy_be_interval);
return true;
}
OLAP_LOG_TRACE(
"don't satisfy the base expansion policy."
"[cumulative_files_number=%d; cumulative_base_ratio=%f; interval_since_last_be=%ld]",
candidate_versions->size() - 1,
cumulative_base_ratio,
interval_since_last_be);
return false;
}
OLAPStatus BaseExpansionHandler::_do_base_expansion(VersionHash new_base_version_hash,
vector<IData*>* base_data_sources,
vector<uint32_t>* selectivities,
uint64_t* row_count) {
// 1. 生成新base文件对应的olap index
OLAPIndex* new_base = new (std::nothrow) OLAPIndex(_table.get(),
_new_base_version,
new_base_version_hash,
false,
0, 0);
if (new_base == NULL) {
OLAP_LOG_WARNING("fail to new OLAPIndex.");
return OLAP_ERR_MALLOC_ERROR;
}
OLAP_LOG_INFO("start merge new base. [table='%s' version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
// 2. 执行base expansion的merge
// 注意:无论是行列存,还是列存,在执行merge时都使用Merger类,不能使用MassiveMerger。
// 原因:MassiveMerger中的base文件不是通过Reader读取的,所以会导致删除条件失效,
// 无法达到删除数据的目的
// 想法:如果一定要使用MassiveMerger,这里可以提供一种方案
// 1. 在此处加一个检查,检测此次BE是否包含删除条件, 即检查Reader中
// ReaderParams的delete_handler
// 2. 如果包含删除条件,则不使用MassiveMerger,使用Merger
// 3. 如果不包含删除条件,则可以使用MassiveMerger
uint64_t merged_rows = 0;
uint64_t filted_rows = 0;
OLAPStatus res = OLAP_SUCCESS;
if (_table->data_file_type() == OLAP_DATA_FILE
|| _table->data_file_type() == COLUMN_ORIENTED_FILE) {
_table->obtain_header_rdlock();
bool use_simple_merge = true;
if (_table->delete_data_conditions_size() > 0) {
use_simple_merge = false;
}
_table->release_header_lock();
Merger merger(_table, new_base, READER_BASE_EXPANSION);
res = merger.merge(
*base_data_sources, use_simple_merge, &merged_rows, &filted_rows);
if (res == OLAP_SUCCESS) {
*row_count = merger.row_count();
*selectivities = merger.selectivities();
}
} else {
OLAP_LOG_WARNING("unknown data file type. [type=%s]",
DataFileType_Name(_table->data_file_type()).c_str());
res = OLAP_ERR_DATA_FILE_TYPE_ERROR;
}
// 3. 如果merge失败,执行清理工作,返回错误码退出
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to make new base version. [table='%s' version='%d.%d' res=%d]",
_table->full_name().c_str(),
_new_base_version.first,
_new_base_version.second,
res);
new_base->delete_all_files();
SAFE_DELETE(new_base);
return OLAP_ERR_BE_MERGE_ERROR;
}
// 4. 如果merge成功,则将新base文件对应的olap index载入
_new_olap_indices.push_back(new_base);
OLAP_LOG_TRACE("merge new base success, start load index. [table='%s' version=%d]",
_table->full_name().c_str(),
_new_base_version.second);
res = new_base->load();
if (res != OLAP_SUCCESS) {
OLAP_LOG_WARNING("fail to load index. [version='%d-%d' version_hash=%ld table='%s']",
new_base->version().first,
new_base->version().second,
new_base->version_hash(),
_table->full_name().c_str());
return res;
}
// Check row num changes
uint64_t source_rows = 0;
for (IData* i_data : *base_data_sources) {
source_rows += i_data->olap_index()->num_rows();
}
bool row_nums_check = config::row_nums_check;
if (row_nums_check) {
if (source_rows != new_base->num_rows() + merged_rows + filted_rows) {
OLAP_LOG_FATAL("fail to check row num! "
"[source_rows=%lu merged_rows=%lu filted_rows=%lu new_index_rows=%lu]",
source_rows, merged_rows, filted_rows, new_base->num_rows());
return OLAP_ERR_CHECK_LINES_ERROR;
}
} else {
OLAP_LOG_INFO("all row nums. "
"[source_rows=%lu merged_rows=%lu filted_rows=%lu new_index_rows=%lu]",
source_rows, merged_rows, filted_rows, new_base->num_rows());
}
return OLAP_SUCCESS;
}
OLAPStatus BaseExpansionHandler::_update_header(const vector<uint32_t>& selectivities,
uint64_t row_count,
vector<OLAPIndex*>* unused_olap_indices) {
vector<Version> unused_versions;
_get_unused_versions(&unused_versions);
OLAPStatus res = OLAP_SUCCESS;
// 由于在replace_data_sources中可能会发生很小概率的非事务性失败, 因此这里定位FATAL错误
res = _table->replace_data_sources(&unused_versions,
&_new_olap_indices,
unused_olap_indices);
if (res != OLAP_SUCCESS) {
OLAP_LOG_FATAL("fail to replace data sources. "
"[res=%d table=%s; new_base=%d; old_base=%d]",
_table->full_name().c_str(),
_new_base_version.second,
_old_base_version.second);
return res;
}
_table->set_selectivities(selectivities);
OLAP_LOG_INFO("BE remove delete conditions. [removed_version=%d]", _new_base_version.second);
// Base Expansion完成之后,需要删除header中版本号小于等于新base文件版本号的删除条件
DeleteConditionHandler cond_handler;
cond_handler.delete_cond(_table, _new_base_version.second, true);
// 如果保存Header失败, 所有新增的信息会在下次启动时丢失, 属于严重错误
// 暂时没办法做很好的处理,报FATAL
res = _table->save_header();
if (res != OLAP_SUCCESS) {
OLAP_LOG_FATAL("fail to save header. "
"[res=%d table=%s; new_base=%d; old_base=%d]",
_table->full_name().c_str(),
_new_base_version.second,
_old_base_version.second);
return OLAP_ERR_BE_SAVE_HEADER_ERROR;
}
_new_olap_indices.clear();
return OLAP_SUCCESS;
}
void BaseExpansionHandler::_delete_old_files(vector<OLAPIndex*>* unused_indices) {
if (!unused_indices->empty()) {
OLAPUnusedIndex* unused_index = OLAPUnusedIndex::get_instance();
for (vector<OLAPIndex*>::iterator it = unused_indices->begin();
it != unused_indices->end(); ++it) {
unused_index->add_unused_index(*it);
}
}
}
void BaseExpansionHandler::_cleanup() {
// 清理掉已生成的版本文件
for (vector<OLAPIndex*>::iterator it = _new_olap_indices.begin();
it != _new_olap_indices.end(); ++it) {
(*it)->delete_all_files();
SAFE_DELETE(*it);
}
_new_olap_indices.clear();
// 释放打开的锁
_release_header_lock();
_release_base_expansion_lock();
_table->set_base_expansion_status(BASE_EXPANSION_WAITING, -1);
}
bool BaseExpansionHandler::_validate_need_merged_versions(
const vector<Version>& candidate_versions) {
if (candidate_versions.size() <= 1) {
OLAP_LOG_WARNING("unenough versions need to be merged. [size=%lu]",
candidate_versions.size());
return false;
}
// 1. validate versions in candidate_versions are continuous
// Skip the first element
for (unsigned int index = 1; index < candidate_versions.size(); ++index) {
Version previous_version = candidate_versions[index - 1];
Version current_version = candidate_versions[index];
if (current_version.first != previous_version.second + 1) {
OLAP_LOG_WARNING("wrong need merged version. "
"previous_version=%d-%d; current_version=%d-%d",
previous_version.first, previous_version.second,
current_version.first, current_version.second);
return false;
}
}
// 2. validate m_new_base_version is OK
if (_new_base_version.first != 0
|| _new_base_version.first != candidate_versions.begin()->first
|| _new_base_version.second != candidate_versions.rbegin()->second) {
OLAP_LOG_WARNING("new_base_version is wrong. "
"[new_base_version=%d-%d; vector_version=%d-%d]",
_new_base_version.first, _new_base_version.second,
candidate_versions.begin()->first,
candidate_versions.rbegin()->second);
return false;
}
OLAP_LOG_TRACE("valid need merged version");
return true;
}
OLAPStatus BaseExpansionHandler::_validate_delete_file_action() {
// 1. acquire the latest version to make sure all is right after deleting files
_obtain_header_rdlock();
const FileVersionMessage* latest_version = _table->latest_version();
Version test_version = Version(0, latest_version->end_version());
vector<IData*> test_sources;
_table->acquire_data_sources(test_version, &test_sources);
if (test_sources.size() == 0) {
OLAP_LOG_INFO("acquire data sources failed. version=%d-%d",
test_version.first, test_version.second);
_release_header_lock();
return OLAP_ERR_BE_ERROR_DELETE_ACTION;
}
_table->release_data_sources(&test_sources);
OLAP_LOG_TRACE("delete file action is OK");
_release_header_lock();
return OLAP_SUCCESS;
}
} // namespace palo
| 38.595577 | 99 | 0.620237 |
321c3ffcbfc764ede04835b683800520a8bdff0b | 404 | cpp | C++ | state_mach.cpp | davitkalantaryan/fork-cpp-raft | f8d08a645ba541d42c6f2db54137fbfa53b5908d | [
"BSD-3-Clause"
] | 20 | 2015-01-19T02:12:50.000Z | 2020-12-09T17:02:42.000Z | state_mach.cpp | davitkalantaryan/fork-cpp-raft | f8d08a645ba541d42c6f2db54137fbfa53b5908d | [
"BSD-3-Clause"
] | 1 | 2015-12-15T11:28:19.000Z | 2015-12-15T11:28:19.000Z | state_mach.cpp | davitkalantaryan/fork-cpp-raft | f8d08a645ba541d42c6f2db54137fbfa53b5908d | [
"BSD-3-Clause"
] | 9 | 2015-08-20T15:35:17.000Z | 2020-07-17T02:26:35.000Z | #include "state_mach.h"
using namespace Raft;
State::State() {
}
State::~State() {
}
bool State::is_follower() {
return d_state == RAFT_STATE_FOLLOWER;
}
bool State::is_leader() {
return d_state == RAFT_STATE_LEADER;
}
bool State::is_candidate() {
return d_state == RAFT_STATE_CANDIDATE;
}
void State::set(RAFT_STATE state) { d_state = state; }
RAFT_STATE State::get() { return d_state; }
| 14.962963 | 54 | 0.693069 |
321e52d806270a22769c244eecdbf204b18e506a | 1,539 | cpp | C++ | samples/webserver.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 16 | 2016-03-16T22:16:18.000Z | 2021-04-05T04:46:38.000Z | samples/webserver.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 11 | 2016-03-16T22:02:26.000Z | 2021-04-04T02:20:51.000Z | samples/webserver.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 5 | 2016-03-22T14:03:34.000Z | 2021-01-06T18:08:46.000Z | #include <iostream>
#include <native/native.hpp>
using namespace native;
using namespace http;
int main() {
std::shared_ptr<Loop> loop = Loop::Create();
std::shared_ptr<Server> server = Server::Create(loop);
server->get("/", [](std::shared_ptr<ServerConnection> connection) -> Future<void> {
// some initial work on the main thread
std::weak_ptr<ServerConnection> connectionWeak = connection;
ServerResponse &res = connection->getResponse();
res.setStatus(200);
res.setHeader("Content-Type", "text/plain");
// wait... I have some async work too. I will update you when I'm done.
return worker([]() {
// Some work on the thread pool to keep the main thread free
std::chrono::milliseconds time(2000);
std::this_thread::sleep_for(time);
})
.then([]() {
// and some work on the main thread to sync data and avoid race condition
std::chrono::milliseconds time(100);
std::this_thread::sleep_for(time);
})
.finally([connectionWeak]() {
// in the end send the response.
connectionWeak.lock()->getResponse().end("C++ FTW\n");
});
});
server->onError([](const Error &err) { std::cout << "error name: " << err.name(); });
if (!server->listen("0.0.0.0", 8080)) {
std::cout << "cannot start server. Check the port 8080 if it is free.\n";
return 1; // Failed to run server.
}
std::cout << "Server running at http://0.0.0.0:8080/" << std::endl;
return run();
}
| 34.2 | 87 | 0.606888 |
321ea55f66bcb059d8b71afc93e24621cc8442e6 | 5,572 | cpp | C++ | OpenCup/e.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | OpenCup/e.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | OpenCup/e.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | /*
* * * * * * * * * * * * * * * * * *
*
* @author: Xingjian Bai
* @date: 2020-10-11 10:31:31
* @description:
* /Users/jackbai/Desktop/OI/OpenCup/e.cpp
*
* @notes:
* g++ -fsanitize=address -ftrapv e.cpp
* * * * * * * * * * * * * * * * * */
#include <bits/stdc++.h>
#define F first
#define S second
#define MP make_pair
#define TIME (double)clock()/CLOCKS_PER_SEC
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
const int MOD = 1000000007;
const int INF = 1e9;
const ld eps = 1e-8;
#define FOR(i,a,b) for (int i = (a); i < (b); i ++)
#define F0R(i,a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b) - 1; i >= a; i --)
#define R0F(i, a) ROF(i, 0, a)
#define trav(a, x) for (auto& a: x)
#define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl
const int maxn = 1e6;
int n, m;
ll fans = 0;
vector <int> adj[maxn];
ll dg[maxn], dg2[maxn], sdg[maxn];
int a3[maxn], a3i[maxn];
priority_queue <pii> a3q;
namespace SegTree{
typedef struct node {
int st, ed;
node *l, *r;
ll mx, num_mx, lz;
ll mx2, num_mx2;
node () {}
node (int stt, int edd, node *L, node *R, ll mxx) {
st = stt, ed = edd, l = L, r = R, mx = mxx, num_mx = 1, mx2 = -INF, num_mx2 = 0, lz = 0;
}
} *pnode;
void update (pnode r) {
if (!r || !r->l)
return ;
r->mx = max (r->l->mx, r->r->mx);
r->mx2 = -INF;
if (r->l->mx != r->mx) r->mx2 = max (r->mx2, r->l->mx);
if (r->r->mx != r->mx) r->mx2 = max (r->mx2, r->r->mx);
if (r->l->mx2 != r->mx) r->mx2 = max (r->mx2, r->l->mx2);
if (r->r->mx2 != r->mx) r->mx2 = max (r->mx2, r->r->mx2);
r->num_mx = 0;
r->num_mx2 = 0;
if (r->l->mx == r->mx) r->num_mx += r->l->num_mx;
if (r->r->mx == r->mx) r->num_mx += r->r->num_mx;
if (r->l->mx2 == r->mx) r->num_mx += r->l->num_mx2;
if (r->r->mx2 == r->mx) r->num_mx += r->r->num_mx2;
if (r->l->mx == r->mx2) r->num_mx2 += r->l->num_mx;
if (r->r->mx == r->mx2) r->num_mx2 += r->r->num_mx;
if (r->l->mx2 == r->mx2) r->num_mx2 += r->l->num_mx2;
if (r->r->mx2 == r->mx2) r->num_mx2 += r->r->num_mx2;
}
pnode build (int st, int ed) {
if (st == ed) {
pnode ne = new node (st, ed, 0, 0, sdg[st]);
return ne;
}
int mid = (st + ed) >> 1;
pnode ne = new node (st, ed, build (st, mid), build (mid + 1, ed), 0);
update (ne);
return ne;
}
void down (pnode r) {
if (!r || !r->l)
return ;
if (r->lz) {
r->l->mx += r->lz;
r->r->mx += r->lz;
r->l->mx2 += r->lz;
r->r->mx2 += r->lz;
r->l->lz += r->lz;
r->r->lz += r->lz;
r->lz = 0;
}
}
void modify (pnode r, int st, int ed, ll v) {
if (st <= r->st && r->ed <= ed) {
r->mx += v;
r->mx2 += v;
r->lz += v;
return ;
}
down (r);
if (st <= r->l->ed) modify (r->l, st, ed, v);
if (r->r->st <= ed) modify (r->r, st, ed, v);
update (r);
}
ll count_zero(pnode r, int st, int ed, ll v) {
// cout << r->st << " " << r->ed << " " << st << " " << ed << " " << v << endl;
// cout << "info: " << r->mx << " " << r->num_mx << " " << r->mx2 << " " << r->num_mx2 << endl;
if (st <= r->st && r->ed <= ed) {
if (r->mx == v) return r->num_mx;
if (r->mx2 == v) return r->num_mx2;
return 0;
}
down (r);
ll ans = 0;
if (st <= r->l->ed) ans += count_zero (r->l, st, ed, v);
if (r->r->st <= ed) ans += count_zero (r->r, st, ed, v);
return ans;
}
void order (pnode r) {
// cout << r->st << " " << r->ed << " : " << r->mx << " " << r->mx2 << " " << r->num_mx << " " << r->num_mx2 << endl;
if (r->st == r->ed) {
cout << r->st << " : " << r->mx << endl;
return ;
}
down(r);
order(r->l);
order(r->r);
}
} using namespace SegTree;
pnode root;
void dg_minus(int x, ll dt) {
dg2[x] -= dt;
modify (root, x, n, -dt);
}
ll find_sdg (int st, int ed, ll val) {
return count_zero(root, st, ed, val);
}
int main() {
scanf("%d %d", &n, &m);
F0R(i, m) {
int x, y;
scanf("%d %d", &x, &y);
adj[x].push_back(y);
adj[y].push_back(x);
dg[x] ++, dg[y] ++;
dg2[max(x, y)] ++;
}
FOR(i, 1, n + 1) {
sort(adj[i].begin(), adj[i].end());
if (adj[i].size() >= 3) {
a3[i] = adj[i][2], a3i[i] = 2;
a3q.push(MP(-max(i, a3[i]), i));
}
else {
a3[i] = n + 1, a3i[i] = adj[i].size();
a3q.push(MP(-(n + 1), i));
}
sdg[i] = sdg[i - 1] + dg2[i];
}
FOR(i, 1, n + 1)
sdg[i] -= i;
root = build(1, n);
FOR(i, 1, n + 1) {
order(root);
// cout << "begin" << endl;
//find the largest r such that for all i from l to r, dg[i] <= 2
int bound, bid;
bool cont = true;
do {
pii tp = a3q.top();
bound = -tp.F, bid = tp.S;
if (bound == n + 1) break;
if (bid >= i && bound == max(bid, a3[bid])) break;
a3q.pop();
} while (true);
bound = min (bound, n + 1);
// cout << "bound: " << bound << endl;
//find the number of i from l to bound-1 such that sdg[i]-2*i==-2*l;
ll pans = find_sdg(i, bound - 1, -i);
cout << "find " << -i << " in " << i << " " << bound - 1 << endl;
fans += pans;
cout << "ans " << i << " : " << pans << endl;
//delete i's neithbors' a3
F0R(j, adj[i].size()) {
int to = adj[i][j];
if (to < i)
continue ;
if (a3i[to] == adj[to].size())
continue ;
a3i[to] ++;
if (a3i[to] == adj[to].size()) {
a3[to] = n + 1;
a3q.push(MP(-(n + 1), i));
}
else {
a3[to] = adj[to][a3i[to]];
a3q.push(MP(-max(to, a3[to]), to));
}
}
//delete i's neighbors's dg
F0R(j, adj[i].size()) {
int to = adj[i][j];
if (to > i)
dg_minus(to, 1);
}
}
printf("%lld\n", fans);
// cerr << TIME << endl;
return 0;
} | 25.559633 | 119 | 0.470747 |
32234a55fff0457a3399490a0db7f51162085257 | 437 | cc | C++ | platform/client_native_pixmap_factory_qt.cc | tworaz/ozone_qt | a015069d3d68cfe0826e76977c974baa1f459834 | [
"MIT"
] | null | null | null | platform/client_native_pixmap_factory_qt.cc | tworaz/ozone_qt | a015069d3d68cfe0826e76977c974baa1f459834 | [
"MIT"
] | null | null | null | platform/client_native_pixmap_factory_qt.cc | tworaz/ozone_qt | a015069d3d68cfe0826e76977c974baa1f459834 | [
"MIT"
] | null | null | null | // Copyright 2015 Piotr Tworek. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone_qt/platform/client_native_pixmap_factory_qt.h"
#include "ui/ozone/common/stub_client_native_pixmap_factory.h"
namespace ui {
ClientNativePixmapFactory* CreateClientNativePixmapFactoryQt() {
return CreateStubClientNativePixmapFactory();
}
} // namespace ui
| 27.3125 | 73 | 0.796339 |
322399a6ddafb4e2f67c58e3d8b574741c2d0f87 | 847 | cpp | C++ | pvxmatching/utils/rbitmap.cpp | igarashi/matchingwithvcmap | b1bc5441d7b45622edf58f0597f478c07ee6db75 | [
"MIT"
] | null | null | null | pvxmatching/utils/rbitmap.cpp | igarashi/matchingwithvcmap | b1bc5441d7b45622edf58f0597f478c07ee6db75 | [
"MIT"
] | null | null | null | pvxmatching/utils/rbitmap.cpp | igarashi/matchingwithvcmap | b1bc5441d7b45622edf58f0597f478c07ee6db75 | [
"MIT"
] | null | null | null | //
// Created by Yuki Igarashi on 2017/05/23.
//
#include "rbitmap.hpp"
namespace utils {
RBitmap::RBitmap(int size) : size_(size) {
if (size > MAX_BIT_SIZE)
throw "Exception: size exceed MAX_BIT_SIZE while creating bitmap. (Use longer int as Bitmap instead.)";
}
void RBitmap::set_value(int symbol, size_t caseId) {
temp_bitmap_[symbol].set(caseId);
temp_default_bitmap_.set(caseId);
}
void RBitmap::compile() {
auto default_mask = temp_default_bitmap_;
default_mask ^= ((1 << size_) - 1);
default_mask_ = default_mask.to_ulong();
for (auto symbol : temp_bitmap_) {
bitmap_[symbol.first] = default_mask_ | symbol.second.to_ulong();
}
}
RBitmap::Bitmap RBitmap::get_filter(int value) const {
auto exists = bitmap_.find(value);
if (exists != bitmap_.end())
return exists->second;
return default_mask_;
}
}
| 22.891892 | 107 | 0.702479 |
322990c1350e8b84464e785bf64d9154bb92ecf7 | 503 | hpp | C++ | src/Common/src/PolynomialFit.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 15 | 2018-04-20T19:16:50.000Z | 2022-02-11T04:11:41.000Z | src/Common/src/PolynomialFit.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 31 | 2016-04-05T20:56:28.000Z | 2022-03-31T22:02:46.000Z | src/Common/src/PolynomialFit.hpp | LBNL-ETA/Windows-CalcEngine | c81528f25ffb79989fcb15b03f00b7c18da138c4 | [
"BSD-3-Clause-LBNL"
] | 6 | 2018-04-20T19:38:58.000Z | 2020-04-06T00:30:47.000Z | #ifndef POLYNOMIALFIT_CPOLYFIT_HPP
#define POLYNOMIALFIT_CPOLYFIT_HPP
#include <vector>
namespace FenestrationCommon
{
class PolynomialFit
{
public:
explicit PolynomialFit(std::size_t const t_Order);
// Get polynomial fit for given coefficients
std::vector<double> getCoefficients(std::vector<std::pair<double, double>> t_Table) const;
private:
std::size_t m_Order;
};
} // namespace FenestrationCommon
#endif // POLYNOMIALFIT_CPOLYFIT_HPP
| 20.958333 | 98 | 0.709742 |
322badbed3ba644ba9ceadae77b86c940bd1ede1 | 8,995 | cpp | C++ | src/pow.cpp | JinCoin/Jincoin | 97c773bae2aaf7d34f3e553944ab7a604cdd6f4d | [
"MIT"
] | 4 | 2018-12-21T03:03:56.000Z | 2021-11-23T18:01:55.000Z | src/pow.cpp | JinCoin/Jincoin | 97c773bae2aaf7d34f3e553944ab7a604cdd6f4d | [
"MIT"
] | null | null | null | src/pow.cpp | JinCoin/Jincoin | 97c773bae2aaf7d34f3e553944ab7a604cdd6f4d | [
"MIT"
] | 4 | 2018-03-24T19:07:26.000Z | 2020-07-07T18:39:44.000Z | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include <cmath>
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
unsigned int static CalculateNextWorkRequired_V1(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params)
{
/* current difficulty formula - kimoto gravity well */
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
double PastRateAdjustmentRatio = double(1);
arith_uint256 PastDifficultyAverage;
arith_uint256 PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
else //JIN: workaround were to overcome the overflow issue when changing from CBigNum to arith_uint256
if (arith_uint256().SetCompact(BlockReading->nBits) >= PastDifficultyAveragePrev)
PastDifficultyAverage = ((arith_uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
else
PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - arith_uint256().SetCompact(BlockReading->nBits)) / i);
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
arith_uint256 bnNew(PastDifficultyAverage);
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
// LogPrintf("Difficulty Retarget - Kimoto Gravity Well\n");
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
// debug print (commented out due to spamming logs when the loop above breaks)
// printf("Difficulty Retarget - Kimoto Gravity Well\n");
// printf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio);
// printf("Before: %08x %s\n", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());
// printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
// arith_uint256 bnNew;
// bnNew.SetCompact(pindexLast->nBits);
// static arith_uint256 bnStartDifficulty(~uint256(0) >> 27);
static const arith_uint256 bnStartDifficulty = UintToArith256(uint256S("0000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
const CBlockIndex *BlockLastSolved = pindexLast;
// int nHeight = pindexLast->nHeight + 1;
static const arith_uint256 bnGenesisDifficulty = UintToArith256(uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
// printf("Block: %i\n", pindexLast->nHeight);
// printf("Block: %08x %s\n", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());
if (pindexLast->nHeight == 160)
// printf("Start Difficulty Block 160 - Without Kimoto Gravity Well\n");
// printf("Block: %08x %s\n", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());
// printf("After 27: %08x %s\n", bnStartDifficulty.GetCompact(), bnStartDifficulty.ToString().c_str());
// printf("Genesis: %08x %s\n", bnGenesisDifficulty.GetCompact(), bnGenesisDifficulty.ToString().c_str());
return bnStartDifficulty.GetCompact();
static const int64_t BlocksTargetSpacing = 79; // 79 seconds
unsigned int TimeDaySeconds = 60 * 60 * 24;
int64_t PastSecondsMin = TimeDaySeconds * (79.0/60.0) * 0.1;
int64_t PastSecondsMax = TimeDaySeconds * (79.0/60.0) * 2.8;
uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing;
uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing;
return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params);
}
// TODO LED TMP temporary public interface for passing the build of test/pow_tests.cpp only
// TODO LED TMP this code should be removed and test/pow_test.cpp changed to call
// TODO LED TMP our interface to PoW --> GetNextWorkRequired()
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
return CalculateNextWorkRequired_V1(pindexLast, nFirstBlockTime, params);
}
| 54.515152 | 207 | 0.615453 |
7a8aae924191335e0c0e561f5f39f1d8269ca4ad | 1,982 | cpp | C++ | CrossApp/renderer/CCPrimitive.cpp | kingBook/cross-2.1.5 | de4e910bd2de55d79ab3aa105d3c2f99ffa60219 | [
"MIT"
] | 794 | 2015-01-01T04:59:48.000Z | 2022-03-09T03:31:13.000Z | CrossApp/renderer/CCPrimitive.cpp | kingBook/cross-2.1.5 | de4e910bd2de55d79ab3aa105d3c2f99ffa60219 | [
"MIT"
] | 83 | 2015-01-04T06:00:35.000Z | 2021-05-20T08:48:38.000Z | CrossApp/renderer/CCPrimitive.cpp | kingBook/cross-2.1.5 | de4e910bd2de55d79ab3aa105d3c2f99ffa60219 | [
"MIT"
] | 598 | 2015-01-02T02:38:13.000Z | 2022-03-09T03:31:37.000Z |
#include "renderer/CCPrimitive.h"
#include "renderer/CCVertexIndexBuffer.h"
NS_CC_BEGIN
Primitive* Primitive::create(VertexData* verts, IndexBuffer* indices, int type)
{
auto result = new (std::nothrow) Primitive();
if( result && result->init(verts, indices, type))
{
result->autorelease();
return result;
}
CC_SAFE_DELETE(result);
return nullptr;
}
const VertexData* Primitive::getVertexData() const
{
return _verts;
}
const IndexBuffer* Primitive::getIndexData() const
{
return _indices;
}
Primitive::Primitive()
: _verts(nullptr)
, _indices(nullptr)
, _type(GL_POINTS)
, _start(0)
, _count(0)
{
}
Primitive::~Primitive()
{
CC_SAFE_RELEASE_NULL(_verts);
CC_SAFE_RELEASE_NULL(_indices);
}
bool Primitive::init(VertexData* verts, IndexBuffer* indices, int type)
{
if( nullptr == verts ) return false;
if(verts != _verts)
{
CC_SAFE_RELEASE(_verts);
CC_SAFE_RETAIN(verts);
_verts = verts;
}
if(indices != _indices)
{
CC_SAFE_RETAIN(indices);
CC_SAFE_RELEASE(_indices);
_indices = indices;
}
_type = type;
return true;
}
void Primitive::draw()
{
if(_verts)
{
_verts->use();
if(_indices!= nullptr)
{
GLenum type = (_indices->getType() == IndexBuffer::IndexType::INDEX_TYPE_SHORT_16) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices->getVBO());
size_t offset = _start * _indices->getSizePerIndex();
glDrawElements((GLenum)_type, _count, type, (GLvoid*)offset);
}
else
{
glDrawArrays((GLenum)_type, _start, _count);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void Primitive::setStart(int start)
{
_start = start;
}
void Primitive::setCount(int count)
{
_count = count;
}
NS_CC_END
| 19.623762 | 133 | 0.624622 |
7a9172749bb79019588820fc40c1676f16d2bd0e | 12,308 | cpp | C++ | test/yulPhaser/Population.cpp | MrChico/solidity | 5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08 | [
"MIT"
] | null | null | null | test/yulPhaser/Population.cpp | MrChico/solidity | 5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08 | [
"MIT"
] | null | null | null | test/yulPhaser/Population.cpp | MrChico/solidity | 5b4ea1eb895d5edc9a24ee5c6f96d8580eceec08 | [
"MIT"
] | null | null | null | /*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#include <test/yulPhaser/TestHelpers.h>
#include <tools/yulPhaser/Chromosome.h>
#include <tools/yulPhaser/PairSelections.h>
#include <tools/yulPhaser/Population.h>
#include <tools/yulPhaser/Program.h>
#include <tools/yulPhaser/Selections.h>
#include <libyul/optimiser/BlockFlattener.h>
#include <libyul/optimiser/SSAReverser.h>
#include <libyul/optimiser/StructuralSimplifier.h>
#include <libyul/optimiser/UnusedPruner.h>
#include <liblangutil/CharStream.h>
#include <boost/test/unit_test.hpp>
#include <cmath>
#include <optional>
#include <string>
#include <sstream>
using namespace std;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace boost::unit_test::framework;
namespace solidity::phaser::test
{
class PopulationFixture
{
protected:
shared_ptr<FitnessMetric> m_fitnessMetric = make_shared<ChromosomeLengthMetric>();
};
BOOST_AUTO_TEST_SUITE(Phaser)
BOOST_AUTO_TEST_SUITE(PopulationTest)
BOOST_AUTO_TEST_CASE(isFitter_should_use_fitness_as_the_main_criterion)
{
BOOST_TEST(isFitter(Individual(Chromosome("a"), 5), Individual(Chromosome("a"), 10)));
BOOST_TEST(!isFitter(Individual(Chromosome("a"), 10), Individual(Chromosome("a"), 5)));
BOOST_TEST(isFitter(Individual(Chromosome("aaa"), 5), Individual(Chromosome("aaaaa"), 10)));
BOOST_TEST(!isFitter(Individual(Chromosome("aaaaa"), 10), Individual(Chromosome("aaa"), 5)));
BOOST_TEST(isFitter(Individual(Chromosome("aaaaa"), 5), Individual(Chromosome("aaa"), 10)));
BOOST_TEST(!isFitter(Individual(Chromosome("aaa"), 10), Individual(Chromosome("aaaaa"), 5)));
}
BOOST_AUTO_TEST_CASE(isFitter_should_use_alphabetical_order_when_fitness_is_the_same)
{
BOOST_TEST(isFitter(Individual(Chromosome("a"), 3), Individual(Chromosome("c"), 3)));
BOOST_TEST(!isFitter(Individual(Chromosome("c"), 3), Individual(Chromosome("a"), 3)));
BOOST_TEST(isFitter(Individual(Chromosome("a"), 3), Individual(Chromosome("aa"), 3)));
BOOST_TEST(!isFitter(Individual(Chromosome("aa"), 3), Individual(Chromosome("a"), 3)));
BOOST_TEST(isFitter(Individual(Chromosome("T"), 3), Individual(Chromosome("a"), 3)));
BOOST_TEST(!isFitter(Individual(Chromosome("a"), 3), Individual(Chromosome("T"), 3)));
}
BOOST_AUTO_TEST_CASE(isFitter_should_return_false_for_identical_individuals)
{
BOOST_TEST(!isFitter(Individual(Chromosome("a"), 3), Individual(Chromosome("a"), 3)));
BOOST_TEST(!isFitter(Individual(Chromosome("acT"), 0), Individual(Chromosome("acT"), 0)));
}
BOOST_FIXTURE_TEST_CASE(constructor_should_copy_chromosomes_compute_fitness_and_sort_chromosomes, PopulationFixture)
{
vector<Chromosome> chromosomes = {
Chromosome::makeRandom(5),
Chromosome::makeRandom(15),
Chromosome::makeRandom(10),
};
Population population(m_fitnessMetric, chromosomes);
vector<Individual> const& individuals = population.individuals();
BOOST_TEST(individuals.size() == 3);
BOOST_TEST(individuals[0].fitness == 5);
BOOST_TEST(individuals[1].fitness == 10);
BOOST_TEST(individuals[2].fitness == 15);
BOOST_TEST(individuals[0].chromosome == chromosomes[0]);
BOOST_TEST(individuals[1].chromosome == chromosomes[2]);
BOOST_TEST(individuals[2].chromosome == chromosomes[1]);
}
BOOST_FIXTURE_TEST_CASE(makeRandom_should_get_chromosome_lengths_from_specified_generator, PopulationFixture)
{
size_t chromosomeCount = 30;
size_t maxLength = 5;
assert(chromosomeCount % maxLength == 0);
auto nextLength = [counter = 0, maxLength]() mutable { return counter++ % maxLength; };
auto population = Population::makeRandom(m_fitnessMetric, chromosomeCount, nextLength);
// We can't rely on the order since the population sorts its chromosomes immediately but
// we can check the number of occurrences of each length.
for (size_t length = 0; length < maxLength; ++length)
BOOST_TEST(
count_if(
population.individuals().begin(),
population.individuals().end(),
[&length](auto const& individual) { return individual.chromosome.length() == length; }
) == chromosomeCount / maxLength
);
}
BOOST_FIXTURE_TEST_CASE(makeRandom_should_get_chromosome_lengths_from_specified_range, PopulationFixture)
{
auto population = Population::makeRandom(m_fitnessMetric, 100, 5, 10);
BOOST_TEST(all_of(
population.individuals().begin(),
population.individuals().end(),
[](auto const& individual){ return 5 <= individual.chromosome.length() && individual.chromosome.length() <= 10; }
));
}
BOOST_FIXTURE_TEST_CASE(makeRandom_should_use_random_chromosome_length, PopulationFixture)
{
SimulationRNG::reset(1);
constexpr int populationSize = 200;
constexpr int minLength = 5;
constexpr int maxLength = 10;
constexpr double relativeTolerance = 0.05;
auto population = Population::makeRandom(m_fitnessMetric, populationSize, minLength, maxLength);
vector<size_t> samples = chromosomeLengths(population);
const double expectedValue = (maxLength + minLength) / 2.0;
const double variance = ((maxLength - minLength + 1) * (maxLength - minLength + 1) - 1) / 12.0;
BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
}
BOOST_FIXTURE_TEST_CASE(makeRandom_should_return_population_with_random_chromosomes, PopulationFixture)
{
SimulationRNG::reset(1);
constexpr int populationSize = 100;
constexpr int chromosomeLength = 30;
constexpr double relativeTolerance = 0.01;
map<string, size_t> stepIndices = enumerateOptmisationSteps();
auto population = Population::makeRandom(m_fitnessMetric, populationSize, chromosomeLength, chromosomeLength);
vector<size_t> samples;
for (auto& individual: population.individuals())
for (auto& step: individual.chromosome.optimisationSteps())
samples.push_back(stepIndices.at(step));
const double expectedValue = (stepIndices.size() - 1) / 2.0;
const double variance = (stepIndices.size() * stepIndices.size() - 1) / 12.0;
BOOST_TEST(abs(mean(samples) - expectedValue) < expectedValue * relativeTolerance);
BOOST_TEST(abs(meanSquaredError(samples, expectedValue) - variance) < variance * relativeTolerance);
}
BOOST_FIXTURE_TEST_CASE(makeRandom_should_compute_fitness, PopulationFixture)
{
auto population = Population::makeRandom(m_fitnessMetric, 3, 5, 10);
BOOST_TEST(population.individuals()[0].fitness == m_fitnessMetric->evaluate(population.individuals()[0].chromosome));
BOOST_TEST(population.individuals()[1].fitness == m_fitnessMetric->evaluate(population.individuals()[1].chromosome));
BOOST_TEST(population.individuals()[2].fitness == m_fitnessMetric->evaluate(population.individuals()[2].chromosome));
}
BOOST_FIXTURE_TEST_CASE(plus_operator_should_add_two_populations, PopulationFixture)
{
BOOST_CHECK_EQUAL(
Population(m_fitnessMetric, {Chromosome("ac"), Chromosome("cx")}) +
Population(m_fitnessMetric, {Chromosome("g"), Chromosome("h"), Chromosome("iI")}),
Population(m_fitnessMetric, {Chromosome("ac"), Chromosome("cx"), Chromosome("g"), Chromosome("h"), Chromosome("iI")})
);
}
BOOST_FIXTURE_TEST_CASE(select_should_return_population_containing_individuals_indicated_by_selection, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("a"), Chromosome("c"), Chromosome("g"), Chromosome("h")});
RangeSelection selection(0.25, 0.75);
assert(selection.materialise(population.individuals().size()) == (vector<size_t>{1, 2}));
BOOST_TEST(
population.select(selection) ==
Population(m_fitnessMetric, {population.individuals()[1].chromosome, population.individuals()[2].chromosome})
);
}
BOOST_FIXTURE_TEST_CASE(select_should_include_duplicates_if_selection_contains_duplicates, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("a"), Chromosome("c")});
MosaicSelection selection({0, 1}, 2.0);
assert(selection.materialise(population.individuals().size()) == (vector<size_t>{0, 1, 0, 1}));
BOOST_TEST(population.select(selection) == Population(m_fitnessMetric, {
population.individuals()[0].chromosome,
population.individuals()[1].chromosome,
population.individuals()[0].chromosome,
population.individuals()[1].chromosome,
}));
}
BOOST_FIXTURE_TEST_CASE(select_should_return_empty_population_if_selection_is_empty, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("a"), Chromosome("c")});
RangeSelection selection(0.0, 0.0);
assert(selection.materialise(population.individuals().size()).empty());
BOOST_TEST(population.select(selection).individuals().empty());
}
BOOST_FIXTURE_TEST_CASE(mutate_should_return_population_containing_individuals_indicated_by_selection_with_mutation_applied, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("cc"), Chromosome("gg"), Chromosome("hh")});
RangeSelection selection(0.25, 0.75);
assert(selection.materialise(population.individuals().size()) == (vector<size_t>{1, 2}));
Population expectedPopulation(m_fitnessMetric, {Chromosome("fc"), Chromosome("fg")});
BOOST_TEST(population.mutate(selection, geneSubstitution(0, BlockFlattener::name)) == expectedPopulation);
}
BOOST_FIXTURE_TEST_CASE(mutate_should_include_duplicates_if_selection_contains_duplicates, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("aa")});
RangeSelection selection(0.0, 1.0);
assert(selection.materialise(population.individuals().size()) == (vector<size_t>{0, 1}));
BOOST_TEST(
population.mutate(selection, geneSubstitution(0, BlockFlattener::name)) ==
Population(m_fitnessMetric, {Chromosome("fa"), Chromosome("fa")})
);
}
BOOST_FIXTURE_TEST_CASE(mutate_should_return_empty_population_if_selection_is_empty, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("cc")});
RangeSelection selection(0.0, 0.0);
assert(selection.materialise(population.individuals().size()).empty());
BOOST_TEST(population.mutate(selection, geneSubstitution(0, BlockFlattener::name)).individuals().empty());
}
BOOST_FIXTURE_TEST_CASE(crossover_should_return_population_containing_individuals_indicated_by_selection_with_crossover_applied, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("cc"), Chromosome("gg"), Chromosome("hh")});
PairMosaicSelection selection({{0, 1}, {2, 1}}, 1.0);
assert(selection.materialise(population.individuals().size()) == (vector<tuple<size_t, size_t>>{{0, 1}, {2, 1}, {0, 1}, {2, 1}}));
Population expectedPopulation(m_fitnessMetric, {Chromosome("ac"), Chromosome("ac"), Chromosome("gc"), Chromosome("gc")});
BOOST_TEST(population.crossover(selection, fixedPointCrossover(0.5)) == expectedPopulation);
}
BOOST_FIXTURE_TEST_CASE(crossover_should_include_duplicates_if_selection_contains_duplicates, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("aa")});
PairMosaicSelection selection({{0, 0}, {1, 1}}, 2.0);
assert(selection.materialise(population.individuals().size()) == (vector<tuple<size_t, size_t>>{{0, 0}, {1, 1}, {0, 0}, {1, 1}}));
BOOST_TEST(
population.crossover(selection, fixedPointCrossover(0.5)) ==
Population(m_fitnessMetric, {Chromosome("aa"), Chromosome("aa"), Chromosome("aa"), Chromosome("aa")})
);
}
BOOST_FIXTURE_TEST_CASE(crossover_should_return_empty_population_if_selection_is_empty, PopulationFixture)
{
Population population(m_fitnessMetric, {Chromosome("aa"), Chromosome("cc")});
PairMosaicSelection selection({}, 0.0);
assert(selection.materialise(population.individuals().size()).empty());
BOOST_TEST(population.crossover(selection, fixedPointCrossover(0.5)).individuals().empty());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
}
| 41.16388 | 147 | 0.772262 |
7a92578132cd9170dd4baece915ccdaab616239c | 730 | cpp | C++ | TCP_ServerClient/AsyncTCPServer_Factory.cpp | aliyavuzkahveci/tcp_serverclient | c37111e21069670972f0fcd08584710af42f591a | [
"MIT"
] | null | null | null | TCP_ServerClient/AsyncTCPServer_Factory.cpp | aliyavuzkahveci/tcp_serverclient | c37111e21069670972f0fcd08584710af42f591a | [
"MIT"
] | null | null | null | TCP_ServerClient/AsyncTCPServer_Factory.cpp | aliyavuzkahveci/tcp_serverclient | c37111e21069670972f0fcd08584710af42f591a | [
"MIT"
] | null | null | null | #include "AsyncTCPServer_Factory.h"
#include "AsyncTCPServer_Impl.h"
namespace AsyncTCP
{
AsyncTCPServer_Factory_Ptr AsyncTCPServer_Factory::m_instance = nullptr;
AsyncTCPServer_Factory_Ptr& AsyncTCPServer_Factory::getInstance()
{
if (m_instance == nullptr)
m_instance = std::unique_ptr<AsyncTCPServer_Factory>(new AsyncTCPServer_Factory());
return m_instance;
}
AsyncTCPServer_Factory::AsyncTCPServer_Factory()
{
}
AsyncTCPServer_Factory::~AsyncTCPServer_Factory()
{
}
AsyncTCPServer_Ptr AsyncTCPServer_Factory::createAsyncTCPServer(
AsyncTCPServer_Subscriber_Ptr subscriberPtr, short port)
{
return AsyncTCPServer_Ptr(new AsyncTCPServer_Impl(subscriberPtr, port));
}
}
| 24.333333 | 87 | 0.773973 |
7a9a54ee622437b984766c046bb2611a0d0565df | 16,941 | cpp | C++ | src/helpers/ExtraHelpers.cpp | mdhooge/qt-handlebars | e950052e0e758413ee09a9c91499481a3ea51b11 | [
"MIT"
] | 1 | 2022-01-11T19:57:39.000Z | 2022-01-11T19:57:39.000Z | src/helpers/ExtraHelpers.cpp | mdhooge/qt-handlebars | e950052e0e758413ee09a9c91499481a3ea51b11 | [
"MIT"
] | null | null | null | src/helpers/ExtraHelpers.cpp | mdhooge/qt-handlebars | e950052e0e758413ee09a9c91499481a3ea51b11 | [
"MIT"
] | 2 | 2016-11-17T12:35:03.000Z | 2022-01-11T19:57:19.000Z | #include "ExtraHelpers.h"
#include <QChar>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QObject>
#include <QTextStream>
#include "HandlebarsParser.h"
namespace Handlebars {
const escape_fn
fn_noEscape,
fn_htmlEscape { [] (const QString& str ) { return str.toHtmlEscaped(); } };
void registerAllHelpers( Parser & parser ) {
registerBitwiseHelpers( parser );
registerBooleanHelpers( parser );
registerFileHelpers( parser );
registerIntegerHelpers( parser );
registerPropertyHelpers( parser );
registerStringHelpers( parser );
}
// ###
// ### Bit-wise Helpers
// ###
static QVariant
integerTypes_bit( const QString& tmplate, int bits )
{
if( bits <= 8 )
return tmplate.arg( "8" );
if( bits <= 16 )
return tmplate.arg( "16" );
if( bits <= 32 )
return tmplate.arg( "32" );
return tmplate.arg( "64" );
}
void
registerBitwiseHelpers( Parser & parser )
{
parser.registerHelper(
"bit-mask", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
int shift = 64 - params.value( 0 ).toInt();
uint64_t mask { UINT64_MAX >> shift };
QString out( "0x" );
out.append( QString::number( mask, 16 ).toUpper() );
return out;
} );
parser.registerHelper(
"int_fast", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
if( params.size() != 2 )
return QVariant(); // RTFM
int bits = params.at( 1 ).toInt();
if( params.at( 0 ).toString().toUpper() == "BYTE" )
bits *= 8;
return integerTypes_bit( "int_fast%1_t", bits );
} );
parser.registerHelper(
"int_least", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
if( params.size() != 2 )
return QVariant(); // RTFM
int bits = params.at( 1 ).toInt();
if( params.at( 0 ).toString().toUpper() == "BYTE" )
bits *= 8;
return integerTypes_bit( "int_least%1_t", bits );
} );
parser.registerHelper(
"uint_fast", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
if( params.size() != 2 )
return QVariant(); // RTFM
int bits = params.at( 1 ).toInt();
if( params.at( 0 ).toString().toUpper() == "BYTE" )
bits *= 8;
return integerTypes_bit( "uint_fast%1_t", bits );
} );
parser.registerHelper(
"uint_least", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
if( params.size() != 2 )
return QVariant(); // RTFM
int bits = params.at( 1 ).toInt();
if( params.at( 0 ).toString().toUpper() == "BYTE" )
bits *= 8;
return integerTypes_bit( "uint_least%1_t", bits );
} );
}
// ###
// ### Boolean Helpers
// ###
void
registerBooleanHelpers( Parser & parser )
{
parser.registerHelper(
"==", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) == params.value( 1 ); } );
parser.registerHelper(
"!=", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) != params.value( 1 ); } );
parser.registerHelper(
"<", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) < params.value( 1 ); } );
parser.registerHelper(
"<=", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) <= params.value( 1 ); } );
parser.registerHelper(
">", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) > params.value( 1 ); } );
parser.registerHelper(
">=", [] ( const RenderingContext &, const helper_params & params, const helper_options & )
{ return params.value( 0 ) >= params.value( 1 ); } );
parser.registerHelper(
"AND", [] (
const RenderingContext & c,
const helper_params & params,
const helper_options & )
{
bool r = true;
for( auto v : params ) {
r = r && c.propertyAsBool( v );
if( ! r ) break;
}
return r;
} );
parser.registerHelper(
"NOT", [] ( const RenderingContext & c, const helper_params & params, const helper_options & )
{ return ! c.propertyAsBool( params.value( 0 )); } );
parser.registerHelper(
"OR", [] (
const RenderingContext & c,
const helper_params & params,
const helper_options & )
{
bool r = false;
for( auto v : params ) {
r = r || c.propertyAsBool( v );
if( r ) break;
}
return r;
} );
}
// ###
// ### File Helpers
// ###
/**
* Concatenate all params to create file path & name
*/
static QString
pathConcatenate( const helper_params & params )
{
QString filepath;
for( auto element : params )
filepath += element.toString();
return filepath;
}
/**
* Recursively copy content of a folder to another folder.
*
* - source must be an existing folder.
*/
static void
copyRecursively( const QString& source, const QString& target )
{
QDir sourceDir( source );
QDir targetDir( target );
// Create target folder if needed
if( ! targetDir.exists() )
targetDir.mkpath( "." );
// Loop & copy
auto list = sourceDir.entryInfoList( QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Readable );
for( int i = 0; i < list.size(); ++i )
{
// Create paths
auto fileInfo = list.at( i );
QString
filename( fileInfo.fileName() ),
sourcePath( sourceDir.filePath( filename )),
targetPath( targetDir.filePath( filename ));
// Copy
if( fileInfo.isDir() )
copyRecursively( sourcePath, targetPath );
else
QFile::copy( sourcePath, targetPath );
}
}
void
registerFileHelpers( Parser & parser )
{
parser.registerHelper(
"cd", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
QDir::setCurrent( pathConcatenate( params ));
return QVariant();
} );
parser.registerHelper(
"copy_into-current-folder_from", [] (
const RenderingContext & context,
const helper_params & params,
const helper_options & options)
{
// Check source
QString source( pathConcatenate( params ));
QFileInfo sourceFileInfo( source );
if( ! sourceFileInfo.exists() ) {
context.warning(
QString( "Handlebars.helper.copy: Source \"%1\" doesn't exist." ).arg( source ));
return QVariant();
}
// "contentOnly" option
bool contentOnly = options.value( "contentOnly" ).toBool();
// Copy file or folder
if ( sourceFileInfo.isDir() ) {
QString targetPath( contentOnly ? "." : sourceFileInfo.fileName() );
copyRecursively( source, targetPath );
}
else
QFile::copy( source, sourceFileInfo.fileName() );
return QVariant();
} );
parser.registerHelper(
"mkdir", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & )
{
QDir::current().mkpath( pathConcatenate( params ));
return QVariant();
} );
parser.registerHelper(
"temp_path", [] (
const RenderingContext &,
const helper_params &,
const helper_options & )
{
return QVariant( QDir::tempPath() );
} );
parser.registerBlockHelper(
"create_file", [] (
RenderingContext & context,
const helper_params & params,
const helper_options & options,
const NodeList & truthy,
const NodeList &
)
{
if( params.size() == 0 )
return; // RTFM
// Compute file path & name
QString filepath( pathConcatenate( params ));
// If property "output_folder" exists, use it to compute a relative path (for log messages)
QString relative_filepath( filepath );
QVariant output_folder( context.getProperty( "output_folder" ));
if( output_folder.isValid() ) {
QDir output_dir( output_folder.toString() );
relative_filepath = output_dir.relativeFilePath(
QDir::current().absoluteFilePath( filepath ));
}
// Open file
QFile file( filepath );
if( ! file.open( QIODevice::WriteOnly )) {
context.warning( QString( "Handlebars.helper.create_file(%1): error #%2" )
.arg( relative_filepath )
.arg( file.error() ));
return;
}
context.info( QString( "Handlebars.helper.create_file(%1)" ).arg( relative_filepath ));
// Create context with file info
QFileInfo fi( filepath );
QVariantHash infos;
infos.insert( "@basename", fi.baseName() );
infos.insert( "@filename", fi.fileName() );
infos.insert( "@filepath", fi.filePath() );
infos.insert( "@filepath_absolute", fi.canonicalFilePath() );
if( output_folder.isValid() )
infos.insert( "@filepath_relative", relative_filepath );
context.pushPropertiesContext( infos );
// If options were given, add them to the context
if( ! options.isEmpty() )
context.pushPropertiesContext( options );
// Create file value
QTextStream stream( & file );
context.render( truthy, & stream );
file.close();
// Remove temporary contexts
if( ! options.isEmpty() )
context.popPropertiesContext();
context.popPropertiesContext();
} );
}
// ###
// ### Integer Helpers
// ###
void
registerIntegerHelpers( Parser & parser )
{
parser.registerHelper(
"range", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & ) -> QVariant
{
if( params.size() < 2 )
return QVariant(); // RTFM
// Retrieve parameters
int i = params.at( 0 ).toInt();
int end = params.at( 1 ).toInt();
int incr = ( params.size() > 2 )
? params.at( 2 ).toInt()
: ( i <= end ) ? 1 : -1;
// Loop
QVariantList range;
for(; (incr>0) ? i<=end : i>=end; i+=incr )
range.append( i );
return range;
} );
}
// ###
// ### Property Helpers
// ###
/**
* Loops over a <Container<QVariant>>
*
* The container is obtained from the "anonymous" QVariant.
*/
template< template<typename> class C >
static QVariant
objectsWithProperty(
const QVariant& q_input,
const helper_params & params
)
{
C< QVariant > input( q_input.value< C< QVariant > > () );
C< QVariant > output;
for( QVariant q_var : input ) {
QObject* object( q_var.value<QObject*>() );
if( object != nullptr )
for( auto propertyName : params )
if( object->property( propertyName.toByteArray().constData() ).toBool() ) {
output.append( q_var );
break;
}
}
return output;
}
/**
* Loops over a <Container< QString, QVariant >>
*
* The container is obtained from the "anonymous" QVariant.
*/
template< template<typename,typename> class C >
static QVariant
objectsWithProperty(
const QVariant& q_input,
const helper_params & params
)
{
C< QString,QVariant > input( q_input.value< C< QString,QVariant > > () );
C< QString,QVariant > output;
for( auto i = input.constBegin(), end = input.constEnd(); i != end; ++i ) {
QVariant q_var( *i );
QObject* object( q_var.value<QObject*>() );
if( object != nullptr )
for( auto propertyName : params )
if( object->property( propertyName.toByteArray().constData() ).toBool() ) {
output.insert( i.key(), i.value() );
break;
}
}
return output;
}
void
registerPropertyHelpers( Parser & parser )
{
parser.registerHelper(
"objects-with-property", [] (
const RenderingContext &,
const helper_params & c_params,
const helper_options & ) -> QVariant
{
if( c_params.size() < 2 )
return QVariant(); // RTFM
// Find type of container
auto params = c_params;
auto container( params.takeFirst() );
auto type( QMetaType::Type( container.type() ));
switch( type )
{
case QMetaType::QVariantHash:
return objectsWithProperty <QHash> ( container, params );
break;
case QMetaType::QVariantList:
return objectsWithProperty <QList> ( container, params );
break;
case QMetaType::QVariantMap:
return objectsWithProperty <QMap> ( container, params );
break;
default:
return QVariant();
break;
}
} );
parser.registerHelper(
"container-value", [] (
const RenderingContext &,
const helper_params & params,
const helper_options & ) -> QVariant
{
if( params.size() < 2 )
return QVariant(); // RTFM
auto container = params.at( 0 );
auto key = params.at( 1 ).toString();
return RenderingContext::findPropertyInContext( key, container );
} );
parser.registerBlockHelper(
"set_property", [] (
RenderingContext & context,
const helper_params & params,
const helper_options & options,
const NodeList & truthy,
const NodeList &
)
{
if( params.size() < 1 ) return; // RTFM
auto name = params.at( 0 ).toString();
// Check if property already exists and "only-if" is set to "new"
if( options.value( "only-if" ).toString() == "new" && context.hasProperty( name ))
return;
QVariant value;
if( params.size() == 2 )
value = params.at( 1 );
else {
// If options were given, add them to the context
if( ! options.isEmpty() )
context.pushPropertiesContext( options );
// Use temporary output to collect inner block
QString content;
QTextStream stream( & content, QIODevice::WriteOnly );
// Create property value
context.render( truthy, & stream );
// Remove any options
if( ! options.isEmpty() )
context.popPropertiesContext();
value = content;
}
// Insert property into context (SIDE-EFFECT!)
context.addProperty( name, value );
} );
}
// ###
// ### String Helpers
// ###
void
registerStringHelpers( Parser & parser )
{
parser.registerHelper(
"camelize", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & )
{
QString in( p.value( 0 ).toString() );
QString out;
out.reserve( in.size() );
//
bool upper = true;
for( QChar c : in ) {
if( c.isLetterOrNumber() ) {
out += upper ? c.toUpper() : c;
upper = false;
} else
upper = true;
}
//
if( out.isEmpty() || ! out[0].isLetter() )
out.prepend( '_' );
//
return out;
} );
// date [<format> =]
parser.registerHelper(
"date", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & )
{
auto format = p.value( 0 ).toString();
if( format.isEmpty() ) format = "yyyy-MM-ddTHH:mmt";
return QDateTime::currentDateTime().toString( format );
} );
parser.registerHelper(
"hex", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & opt )
{
qint64 value = p.value( 0 ).toLongLong();
int width = opt.value( "width", 0 ).toInt();
QString fillS = opt.value( "fill" ).toString();
QChar fill = fillS.size() > 0 ? fillS.at( 0 ) : ' ';
return QVariant( QString( "%1" ).arg( value, width, 16, fill ));
} );
parser.registerHelper(
"link", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & opt )
{
QStringList attrs;
for( auto i = opt.begin(), end = opt.end(); i != end; ++i )
attrs.append( QString( "%1=\"%2\"" ).arg( i.key() ).arg( i.value().toString() ));
return QVariant( QString( "<a %1>%2</a>" )
.arg( attrs.join( ' ' ))
.arg( p.value( 0 ).toString() ));
} );
parser.registerHelper(
"print", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & )
{
QString out;
QTextStream stream( & out, QIODevice::WriteOnly );
for( auto i = p.begin(), end = p.end() ;;)
{
stream << i->typeName() << '(' << i->toString() << ')';
if( ++i == end )
break;
stream << ' ';
}
return QVariant( out );
} );
parser.registerHelper(
"upper", [] (
const RenderingContext &,
const helper_params & p,
const helper_options & )
{
return QVariant( p.value( 0 ).toString().toUpper() );
} );
}
}// namespace Handlebars
| 25.90367 | 106 | 0.581725 |
7a9c02bc21da5bd673f3a972a10d7862f117a9b4 | 1,524 | hpp | C++ | libs/ledger/include/ledger/tx_status_http_interface.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 3 | 2019-07-11T08:49:27.000Z | 2021-09-07T16:49:15.000Z | libs/ledger/include/ledger/tx_status_http_interface.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/ledger/include/ledger/tx_status_http_interface.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 2 | 2019-07-13T12:45:22.000Z | 2021-03-12T08:48:57.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "http/module.hpp"
namespace fetch {
namespace ledger {
class TransactionStatusCache;
class TxStatusHttpInterface : public http::HTTPModule
{
public:
// Construction / Destruction
explicit TxStatusHttpInterface(TransactionStatusCache &status_cache);
TxStatusHttpInterface(TxStatusHttpInterface const &) = delete;
TxStatusHttpInterface(TxStatusHttpInterface &&) = delete;
~TxStatusHttpInterface() = default;
// Operators
TxStatusHttpInterface &operator=(TxStatusHttpInterface const &) = delete;
TxStatusHttpInterface &operator=(TxStatusHttpInterface &&) = delete;
private:
TransactionStatusCache &status_cache_;
};
} // namespace ledger
} // namespace fetch
| 33.130435 | 80 | 0.654199 |
7a9ea246aeb7df0f5298e76b12ecffced085fafa | 3,983 | cpp | C++ | src/main/cpp/ofxOboeAndroidSoundPlayer.cpp | danoli3/ofxOboe | 61b628c48c18c44a4f21a695549fa95286d86779 | [
"MIT"
] | 1 | 2021-11-05T08:33:34.000Z | 2021-11-05T08:33:34.000Z | src/main/cpp/ofxOboeAndroidSoundPlayer.cpp | danoli3/ofxOboe | 61b628c48c18c44a4f21a695549fa95286d86779 | [
"MIT"
] | null | null | null | src/main/cpp/ofxOboeAndroidSoundPlayer.cpp | danoli3/ofxOboe | 61b628c48c18c44a4f21a695549fa95286d86779 | [
"MIT"
] | null | null | null | //
// Created by Dan Rosser on 10/9/21.
//
#include "ofxOboeAndroidSoundPlayer.h"
bool ofxOboeAndroidSoundPlayer::load(const std::filesystem::path& fileName, bool stream) {
AudioProperties targetProperties {
.channelCount = ofxOboe::getChannelCount(),
.sampleRate = ofxOboe::getSampleRate()
};
filePath = fileName.c_str();
std::shared_ptr<ofxOboeAssetDataSource> trackSource {
ofxOboeAssetDataSource::newFromCompressedAsset(ofxOboe::getAssetManager(), fileName.c_str(), targetProperties, AASSET_MODE_UNKNOWN)
};
if (trackSource == nullptr){
ofLogError("ofxOboe") << "Could not load source data for track:" << fileName;
return false;
}
track = std::make_unique<ofxOboePlayer>(trackSource);
if(track != nullptr) {
track->setPlaying(false);
track->setLooping(isLooping);
ofxOboe::mixer.addTrack(track.get());
} else
return false;
return true;
}
void ofxOboeAndroidSoundPlayer::unload() {
if(track) {
track->setPlaying(false);
track.reset();
track.release();
track = nullptr;
state = ofxOboeAndroidSoundState::UNLOADED;
}
}
void ofxOboeAndroidSoundPlayer::play() {
if(track)
track->setPlaying(true);
}
void ofxOboeAndroidSoundPlayer::stop() {
if(track) {
track->setPlaying(false);
}
}
void ofxOboeAndroidSoundPlayer::setVolume(float vol) {
if(track) {
track->setVolume(vol);
}
}
void ofxOboeAndroidSoundPlayer::setPan(float vol) {
}
void ofxOboeAndroidSoundPlayer::setSpeed(float spd) {
}
void ofxOboeAndroidSoundPlayer::setPaused(bool bP) {
if(track) {
track->setPlaying(false);
}
}
void ofxOboeAndroidSoundPlayer::setLoop(bool bLp) {
if(track) {
track->setLooping(bLp);
}
}
void ofxOboeAndroidSoundPlayer::setMultiPlay(bool bMp) {
}
void ofxOboeAndroidSoundPlayer::setPosition(float pct) {
if(track) {
track->setPlayHead((int)pct);
}
}
void ofxOboeAndroidSoundPlayer::setPositionMS(int ms) {
if(track) {
track->setPlayHead(ms);
}
}
float ofxOboeAndroidSoundPlayer::getPosition() const {
return 1.0f;
}
int ofxOboeAndroidSoundPlayer::getPositionMS() const {
return 0;
}
bool ofxOboeAndroidSoundPlayer::isPlaying() const {
if(track) {
return track->getPlaying();
}
return false;
}
float ofxOboeAndroidSoundPlayer::getSpeed() const {
return 1.0f;
}
float ofxOboeAndroidSoundPlayer::getPan() const {
return 1.0f;
}
bool ofxOboeAndroidSoundPlayer::isPaused() const {
return false;
}
float ofxOboeAndroidSoundPlayer::getVolume() const {
return 1.0f;
}
bool ofxOboeAndroidSoundPlayer::isLoaded() const {
if(track) {
return true;
}
return false;
}
void ofxOboeAndroidSoundPlayer::audioIn(ofSoundBuffer&) const {
}
void ofxOboeAndroidSoundPlayer::audioOut(ofSoundBuffer&) const {
}
ofxOboeAndroidSoundPlayer::~ofxOboeAndroidSoundPlayer() {
}
oboe::DataCallbackResult
ofxOboeAndroidSoundPlayer::onAudioReady(AudioStream *oboeStream, void *audioData,
int32_t numFrames) {
// auto *outputBuffer = static_cast<float *>(audioData);
//
// int64_t nextClapEventMs;
//
// for (int i = 0; i < numFrames; ++i) {
//
// songPositionMS = convertFramesToMillis(
// currentFrame,
// ofxOboe::getSampleRate());
//
//
// ofxOboe::mixer.renderAudio(outputBuffer+(oboeStream->getChannelCount()*i), 1);
// currentFrame++;
// }
return DataCallbackResult::Continue;
}
void ofxOboeAndroidSoundPlayer::onErrorAfterClose(AudioStream *oboeStream, Result error) {
if (error == Result::ErrorDisconnected){
state = ofxOboeAndroidSoundState::FAILED;
currentFrame = 0;
songPositionMS = 0;
lastUpdateTime = 0;
//start();
} else {
//LOGE("Stream error: %s", convertToText(error));
}
}
| 23.850299 | 143 | 0.656038 |