blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a10019a4fdb18f4e3c5b2467bc6e7ec79409ceba | 4c19506e8a61967c9de1a84d9b39e90f87776a1a | /MatrixInv.cc | 6133f767d87327c52786968b4112246da0a833c5 | [] | no_license | asantra/SusyPhoton | 588541d735e85f53d98388ac83adbfa4edc72177 | b6f44b50f484e62f655442043a80d97146367dd6 | refs/heads/master | 2021-01-17T09:33:31.516282 | 2015-02-06T19:01:48 | 2015-02-06T19:01:48 | 19,005,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,019 | cc | #include <iostream>
#include <cmath>
#define EPS 0.000000001
#define MAXIT 200000
using namespace std;
/* Using Jacobi iteration method */
void Jacobi(int n, float a[4][4], float b[4], float x[4], int *count, int *status){
int key;
float sum, x0[4];
for(int i=0;i<4;i++)
x0[i] = b[i] / a[i][i];
*count = 1;
begin:
key = 0;
for(int i=0;i<4;i++){
sum = b[i];
for(int j=0;j<4;j++){
if(i==j)continue;
sum = sum - a[i][j] * x0[j];
}
x[i] = sum / a[i][i];
if(key == 0){
/* Testing for accuracy */
if(std::abs ((x[i]-x0[i]) / x[i]) > EPS ) key = 1;
}
}
/* Testing for convergence */
if(key == 1){
if(*count == MAXIT){
*status = 2;
return;
}
else{
*status = 1;
for (int i=0;i<4;i++)
x0[i] = x[i];
}
*count = *count+1;
goto begin;
}
return;
}
int main(){
int Npp, Npf,Nfp, Nff;
float ep1, ep2, f1, f2;
float Nyy, Nyj, Njy, Njj;
float a[4][4], b[4], x[4];
int n, count, status;
/* getting the input values */
cout << "How many linear equations?"; cin >> n;
cout << "Enter the values:" << endl;
cout << "Npp: "; cin >> Npp;
cout << "Npf: "; cin >> Npf;
cout << "Nfp: "; cin >> Nfp;
cout << "Nff: "; cin >> Nff;
cout << "ep1: "; cin >> ep1;
cout << "ep2: "; cin >> ep2;
cout << "f1: "; cin >> f1;
cout << "f2: "; cin >> f2;
cout << "The equation to solve:" << endl;
cout << Npp << "=" << ep1*ep2 << "*Nyy+" << ep1*f2 << "*Nyj+" << f1*ep2 << "*Njy+" << f1*f2 << "*Njj" << endl;
cout << Npf << "=" << ep1*(1-ep2) << "*Nyy+" << ep1*(1-f2) << "*Nyj+" << (1-f1)*ep2 << "*Njy+" << f1*(1-f2) << "*Njj" << endl;
cout << Nfp << "=" << (1-ep1)*ep2 << "*Nyy+" << (1-ep1)*f2 << "*Nyj+" << (1-f1)*ep2 << "*Njy+" << (1-f1)*f2 << "*Njj" << endl;
cout << Nff << "=" << (1-ep1)*(1-ep2) << "*Nyy+" << (1-ep1)*(1-f2) << "*Nyj+" << (1-f1)*(1-ep2) << "*Njy+" << (1-f1)*(1-f2) << "*Njj" << endl;
/* putting the values inside the arrays , remember ax=b */
a[0][0] = ep1*ep2; a[0][1] = ep1*f2; a[0][2] = f1*ep2; a[0][3] = f1*f2;
a[1][0] = ep1*(1-ep2); a[1][1] = ep1*(1-f2); a[1][2] = (1-f1)*ep2; a[1][3] = f1*(1-f2);
a[2][0] = (1-ep1)*ep2; a[2][1] = (1-ep1)*f2; a[2][2] = (1-f1)*ep2; a[2][3] = (1-f1)*f2;
a[3][0] = (1-ep1)*(1-ep2); a[3][1] = (1-ep1)*(1-f2); a[3][2] = (1-f1)*(1-ep2); a[3][3] = (1-f1)*(1-f2);
b[0] = Npp; b[1] = Npf; b[2] = Nfp; b[3] = Nff;
Jacobi(n,a,b,x, &count, &status);
if(status == 2){
cout << "no convergence in " << MAXIT << " iterations." << endl;
}
else{
cout << "Solution in " << count << " iterations:"<< endl;
cout << "Nyy =" << x[0] << endl;
cout << "Nyj =" << x[1] << endl;
cout << "Njy =" << x[2] << endl;
cout << "Njj =" << x[3] << endl;
cout << "estimated purity:" << x[0]/(x[0]+x[1]+x[2]+x[3]) << endl;
}
}
| [
"santra.arka@gmail.com"
] | santra.arka@gmail.com |
f4ee79d501f60219857d991dfe230738ab7f7adc | 764835e76e3bff2e730fe4e5e6da0e2fd143cc24 | /01Sept2016/src/llt.cc | 38ec4ae079e21debf462ccbfb4255b2a6e1adba7 | [] | no_license | amandipde/HiggsWH | 2a409441ecb1559081af87ee4c09ad76c150af8f | 9e293577824e5248ae8668392e15a7cf3ca1867a | refs/heads/master | 2020-03-21T20:36:16.308220 | 2017-03-02T11:32:44 | 2017-03-02T11:32:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cc | #include <iostream>
#include <string>
#include <vector>
#include "TROOT.h"
#include "TStopwatch.h"
#include "LLT.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Usage: " << argv[0] << " jobFile " << endl;
exit(0);
}
string jobFile(argv[1]);
// Create analysis object
LLT myana;
// Read job input
int nFiles = 0;
bool succeed = myana.readJob(jobFile, nFiles);
if (!succeed) exit(1);
if (myana.getEntries() <= 0) {
cerr << "No events present in the input chain, exiting ...!" << endl;
exit(2);
}
gROOT->SetBatch(kTRUE);
// Now go
TStopwatch timer;
cout << "Start event loop now with <" << nFiles << "> file(s)" << endl;
timer.Start();
myana.eventLoop();
timer.Stop();
cout << "Realtime/CpuTime = " << timer.RealTime() << "/" << timer.CpuTime() << endl;
return 0;
}
| [
"atanu.modak@cern.ch mailto:atanu.modak@cern.ch"
] | atanu.modak@cern.ch mailto:atanu.modak@cern.ch |
3441616b32d74e5be01f91c65ccc09b388a872a3 | d4371dc01d02fd5c21ced58683ae4f982a38110b | /code/modules/core-tests/src/ecs/ComponentManagerTests.cpp | f5a284fbfdda6a28cd4f9624b864009eb93ce003 | [
"MIT"
] | permissive | Eregerog/Modulith | a2aeb030444a4c1197fd7b7403b5b8c769f35a3b | ce6c153d28c64f24654ac7a2247bfe4992096090 | refs/heads/main | 2023-01-21T14:21:43.702785 | 2023-01-15T09:22:44 | 2023-01-15T09:22:44 | 318,228,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,866 | cpp | /**
* \brief
* \author Daniel Götz
*/
#include "Core.h"
#include "catch.hpp"
#include "ECSTestUtils.h"
#include <ecs/EntityManager.h>
SCENARIO("Components can be copied from and to std::any"){
auto componentManager = CreateComponentManager();
GIVEN("A component with data and no RAII / Destructors"){
auto info = componentManager->GetInfoOf(typeid(NumberData));
REQUIRE(info.IsSerializable());
auto* data = new NumberData(12);
REQUIRE(data->Number == 12);
WHEN("A new number data is copied into data"){
info.CopyFromAnyToPointer(NumberData(13), data);
THEN("The data's number changes"){
REQUIRE(data->Number == 13);
}
AND_WHEN("The data is copied back into a std::any"){
auto asAny = info.CopyFromPointerToAny(data);
auto number = std::any_cast<NumberData>(asAny);
THEN("The any contains the number that was set"){
REQUIRE(number.Number == 13);
}
}
}
delete data;
}
GIVEN("A component with a shared pointer"){
auto info = componentManager->GetInfoOf(typeid(FirstSharedResourceData));
REQUIRE(info.IsSerializable());
auto firstSharedPtr = std::make_shared<int>(666);
auto* data = new FirstSharedResourceData(firstSharedPtr);
REQUIRE(firstSharedPtr.use_count() == 2);
WHEN("New data is copied into the pointer"){
auto secondSharedPtr = std::make_shared<int>(1337);
REQUIRE(secondSharedPtr.use_count() == 1);
info.CopyFromAnyToPointer(FirstSharedResourceData(secondSharedPtr), data);
THEN("The use count of the old shared pointer and new pointer are changed accordingly"){
REQUIRE(firstSharedPtr.use_count() == 1);
REQUIRE(secondSharedPtr.use_count() == 2);
}
AND_WHEN("The data is copied into a std::any"){
{
auto asAny = info.CopyFromPointerToAny(data);
auto resourceData = std::any_cast<FirstSharedResourceData>(asAny);
asAny.reset();
THEN("The use count and value inside the resource data are correct") {
REQUIRE(secondSharedPtr.use_count() == 3);
REQUIRE(*resourceData.Resource == 1337);
REQUIRE(resourceData.Resource == secondSharedPtr);
}
}
AND_WHEN("The copied values go out-of-scope"){
THEN("The resource count is back to what is was before"){
REQUIRE(secondSharedPtr.use_count() == 2);
}
}
}
}
delete data;
}
}
| [
"danielgoetz3@gmx.de"
] | danielgoetz3@gmx.de |
06879f9d1b1a9a183cf047fce356f5ea88c23161 | 84aa2ebaead83898f15c48fc434acb5fb5d338d3 | /common/yaml/test/yaml_read_archive_test.cc | 646593ea2e13713bc4297e1f060474f0bd21f152 | [
"BSD-3-Clause"
] | permissive | mamurtaza88/drake | ebc1f8d51599c138d37f86505ed83846c5c2509a | 6ebdccec71336b7cbe6dcf894988719219074c54 | refs/heads/main | 2023-03-18T03:47:44.572623 | 2022-12-17T21:45:43 | 2022-12-17T21:45:43 | 579,491,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,512 | cc | #include "drake/common/yaml/yaml_read_archive.h"
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "drake/common/name_value.h"
#include "drake/common/nice_type_name.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/common/yaml/test/example_structs.h"
// TODO(jwnimmer-tri) All of these regexps would be better off using the
// std::regex::basic grammar, where () and {} are not special characters.
namespace drake {
namespace yaml {
namespace test {
namespace {
// TODO(jwnimmer-tri) Add a test case for reading NonPodVectorStruct.
// TODO(jwnimmer-tri) Add a test case for reading OuterWithBlankInner.
// TODO(jwnimmer-tri) Add a test case for reading StringStruct.
// TODO(jwnimmer-tri) Add a test case for reading UnorderedMapStruct.
// A test fixture with common helpers.
class YamlReadArchiveTest
: public ::testing::TestWithParam<YamlReadArchive::Options> {
public:
// Loads a single "doc: { ... }" map from `contents` and returns the nested
// map (i.e., just the "{ ... }" part, not the "doc" part). It is an error
// for the "{ ... }" part not to be a map node.
static YAML::Node Load(const std::string& contents) {
const YAML::Node loaded = YAML::Load(contents);
if (loaded.Type() != YAML::NodeType::Map) {
throw std::invalid_argument("Bad contents parse " + contents);
}
const YAML::Node doc = loaded["doc"];
if (doc.Type() != YAML::NodeType::Map) {
throw std::invalid_argument("Bad doc parse " + contents);
}
return doc;
}
// Loads a single "{ value: something }" map node. If the argument is the
// empty string, the result is a map from "value" to Null (not an empty map,
// nor Null itself, etc.)
static YAML::Node LoadSingleValue(const std::string& value) {
return Load("doc:\n value: " + value + "\n");
}
// Parses root into a Serializable and returns the result of the parse.
// Any exceptions raised are reported as errors.
template <typename Serializable>
static Serializable AcceptNoThrow(const YAML::Node& root) {
SCOPED_TRACE("for type " + NiceTypeName::Get<Serializable>());
Serializable result{};
bool raised = false;
std::string what;
try {
YamlReadArchive(root, GetParam()).Accept(&result);
} catch (const std::exception& e) {
raised = true;
what = e.what();
}
EXPECT_FALSE(raised);
EXPECT_EQ(what, "");
return result;
}
// Parses root into a Serializable and discards the result.
// This is usually used to check that an exception is raised.
template <typename Serializable>
static void AcceptIntoDummy(const YAML::Node& root) {
Serializable dummy{};
YamlReadArchive(root, GetParam()).Accept(&dummy);
}
// Parses root into a Serializable and returns the result of the parse.
// If allow_cpp_with_no_yaml is set, then any exceptions are errors.
// If allow_cpp_with_no_yaml is not set, then lack of exception is an error.
template <typename Serializable>
static Serializable AcceptEmptyDoc() {
SCOPED_TRACE("for type " + NiceTypeName::Get<Serializable>());
const YAML::Node root = Load("doc: {}");
Serializable result{};
bool raised = false;
std::string what;
try {
YamlReadArchive(root, GetParam()).Accept(&result);
} catch (const std::exception& e) {
raised = true;
what = e.what();
}
if (GetParam().allow_cpp_with_no_yaml) {
EXPECT_FALSE(raised);
EXPECT_EQ(what, "");
} else {
EXPECT_TRUE(raised);
EXPECT_THAT(what, testing::MatchesRegex(
".*missing entry for [^ ]* value.*"));
}
return result;
}
};
TEST_P(YamlReadArchiveTest, Double) {
const auto test = [](const std::string& value, double expected) {
const auto& x = AcceptNoThrow<DoubleStruct>(LoadSingleValue(value));
EXPECT_EQ(x.value, expected);
};
test("0", 0.0);
test("1", 1.0);
test("-1", -1.0);
test("0.0", 0.0);
test("1.2", 1.2);
test("-1.2", -1.2);
test("3e4", 3e4);
test("3e-4", 3e-4);
test("5.6e7", 5.6e7);
test("5.6e-7", 5.6e-7);
test("-5.6e7", -5.6e7);
test("-5.6e-7", -5.6e-7);
test("3E4", 3e4);
test("3E-4", 3e-4);
test("5.6E7", 5.6e7);
test("5.6E-7", 5.6e-7);
test("-5.6E7", -5.6e7);
test("-5.6E-7", -5.6e-7);
}
TEST_P(YamlReadArchiveTest, DoubleMissing) {
const auto& x = AcceptEmptyDoc<DoubleStruct>();
EXPECT_EQ(x.value, kNominalDouble);
}
TEST_P(YamlReadArchiveTest, StdArray) {
const auto test = [](const std::string& value,
const std::array<double, 3>& expected) {
const auto& x = AcceptNoThrow<ArrayStruct>(LoadSingleValue(value));
EXPECT_EQ(x.value, expected);
};
test("[1.0, 2.0, 3.0]", {1.0, 2.0, 3.0});
}
TEST_P(YamlReadArchiveTest, StdArrayMissing) {
const auto& x = AcceptEmptyDoc<ArrayStruct>();
EXPECT_EQ(x.value[0], kNominalDouble);
EXPECT_EQ(x.value[1], kNominalDouble);
EXPECT_EQ(x.value[2], kNominalDouble);
}
TEST_P(YamlReadArchiveTest, StdVector) {
const auto test = [](const std::string& value,
const std::vector<double>& expected) {
const auto& x = AcceptNoThrow<VectorStruct>(LoadSingleValue(value));
EXPECT_EQ(x.value, expected);
};
test("[1.0, 2.0, 3.0]", {1.0, 2.0, 3.0});
}
TEST_P(YamlReadArchiveTest, StdVectorMissing) {
const auto& x = AcceptEmptyDoc<VectorStruct>();
ASSERT_EQ(x.value.size(), 1);
EXPECT_EQ(x.value[0], kNominalDouble);
}
TEST_P(YamlReadArchiveTest, StdMap) {
const auto test = [](const std::string& doc,
const std::map<std::string, double>& expected) {
const auto& x = AcceptNoThrow<MapStruct>(Load(doc));
std::map<std::string, double> adjusted_expected = expected;
if (GetParam().retain_map_defaults) {
adjusted_expected["kNominalDouble"] = kNominalDouble;
}
EXPECT_EQ(x.value, adjusted_expected) << doc;
};
test("doc:\n value:\n foo: 0.0\n bar: 1.0\n",
{{"foo", 0.0}, {"bar", 1.0}});
}
TEST_P(YamlReadArchiveTest, BigStdMapAppend) {
if (!GetParam().allow_cpp_with_no_yaml) {
// The parser would raise an uninteresting exception in this case.
return;
}
std::string doc = R"""(
doc:
value:
bar:
outer_value: 3.0
inner_struct:
inner_value: 4.0
)""";
const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc));
if (GetParam().retain_map_defaults) {
EXPECT_EQ(x.value.size(), 2);
EXPECT_EQ(x.value.at("foo").outer_value, 1.0);
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0);
} else {
EXPECT_EQ(x.value.size(), 1);
}
EXPECT_EQ(x.value.at("bar").outer_value, 3.0);
EXPECT_EQ(x.value.at("bar").inner_struct.inner_value, 4.0);
}
TEST_P(YamlReadArchiveTest, BigStdMapMergeNewOuterValue) {
if (!GetParam().allow_cpp_with_no_yaml) {
// The parser would raise an uninteresting exception in this case.
return;
}
std::string doc = R"""(
doc:
value:
foo:
outer_value: 3.0
)""";
const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc));
EXPECT_EQ(x.value.size(), 1);
EXPECT_EQ(x.value.at("foo").outer_value, 3.0);
if (GetParam().retain_map_defaults) {
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0);
} else {
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, kNominalDouble);
}
}
TEST_P(YamlReadArchiveTest, BigStdMapMergeNewInnerValue) {
if (!GetParam().allow_cpp_with_no_yaml) {
// The parser would raise an uninteresting exception in this case.
return;
}
std::string doc = R"""(
doc:
value:
foo:
inner_struct:
inner_value: 4.0
)""";
const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc));
EXPECT_EQ(x.value.size(), 1);
if (GetParam().retain_map_defaults) {
EXPECT_EQ(x.value.at("foo").outer_value, 1.0);
} else {
EXPECT_EQ(x.value.at("foo").outer_value, kNominalDouble);
}
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 4.0);
}
TEST_P(YamlReadArchiveTest, BigStdMapMergeEmpty) {
if (!GetParam().allow_cpp_with_no_yaml) {
// The parser would raise an uninteresting exception in this case.
return;
}
std::string doc = R"""(
doc:
value:
foo: {}
)""";
const auto& x = AcceptNoThrow<BigMapStruct>(Load(doc));
EXPECT_EQ(x.value.size(), 1);
if (GetParam().retain_map_defaults) {
EXPECT_EQ(x.value.at("foo").outer_value, 1.0);
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, 2.0);
} else {
EXPECT_EQ(x.value.at("foo").outer_value, kNominalDouble);
EXPECT_EQ(x.value.at("foo").inner_struct.inner_value, kNominalDouble);
}
}
TEST_P(YamlReadArchiveTest, StdMapMissing) {
const auto& x = AcceptEmptyDoc<MapStruct>();
ASSERT_EQ(x.value.size(), 1);
EXPECT_EQ(x.value.at("kNominalDouble"), kNominalDouble);
}
TEST_P(YamlReadArchiveTest, StdMapWithMergeKeys) {
const auto test = [](const std::string& doc,
const std::map<std::string, double>& expected) {
const auto& x = AcceptNoThrow<MapStruct>(Load(doc));
std::map<std::string, double> adjusted_expected = expected;
if (GetParam().retain_map_defaults) {
adjusted_expected["kNominalDouble"] = kNominalDouble;
}
EXPECT_EQ(x.value, adjusted_expected) << doc;
};
// Use merge keys to populate some keys.
test(R"""(
_template: &template
foo: 1.0
doc:
value:
<< : *template
bar: 2.0
)""", {{"foo", 1.0}, {"bar", 2.0}});
// A pre-existing value should win, though.
test(R"""(
_template: &template
foo: 3.0
doc:
value:
<< : *template
foo: 1.0
bar: 2.0
)""", {{"foo", 1.0}, {"bar", 2.0}});
// A list of merges should also work.
test(R"""(
_template: &template
- foo: 1.0
- baz: 3.0
doc:
value:
<< : *template
bar: 2.0
)""", {{"foo", 1.0}, {"bar", 2.0}, {"baz", 3.0}});
}
TEST_P(YamlReadArchiveTest, StdMapWithBadMergeKey) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<MapStruct>(Load(R"""(
_template: &template 99.0
doc:
value:
<< : *template
bar: 2.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has invalid merge key type \\(Scalar\\)\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<MapStruct>(Load(R"""(
_template: &template
doc:
value:
<< : *template
bar: 2.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has invalid merge key type \\(Null\\).");
}
TEST_P(YamlReadArchiveTest, Optional) {
const auto test_with_default = [](const std::string& doc,
const std::optional<double>& expected) {
const auto& x = AcceptNoThrow<OptionalStruct>(Load(doc));
if (expected.has_value()) {
ASSERT_TRUE(x.value.has_value()) << *expected;
EXPECT_EQ(x.value.value(), expected.value()) << *expected;
} else {
EXPECT_FALSE(x.value.has_value());
}
};
const auto test_no_default = [](const std::string& doc,
const std::optional<double>& expected) {
const auto& x = AcceptNoThrow<OptionalStructNoDefault>(Load(doc));
if (expected.has_value()) {
ASSERT_TRUE(x.value.has_value()) << *expected;
EXPECT_EQ(x.value.value(), expected.value()) << *expected;
} else {
EXPECT_FALSE(x.value.has_value());
}
};
/*
If the YAML data provided a value for the optional key, then we should
always take that value (1-4). If the YAML data provided an explicit null for
the optional key, then we should always take that null (5-8). If the YAML
data did not mention the key (9-12), the situation is more subtle. In the
case where allow_cpp_with_no_yaml is false, then every C++ member field must
match up with YAML -- with the caveat that optional members can be omitted;
in that case, an absent YAML node must interpreted as nullopt so that C++
and YAML remain congruent (9, 11). In the case where allow_cpp_with_no_yaml
is true, we should only be changing C++ values when the yaml data mentions
the key; unmentioned values should stay undisturbed; in that case, a missing
key should have no effect (10, 12); only an explicit null key (7, 8) should
evidence a change.
# | yaml | store | acwny || want
===+========+=======+=======++========
1 | Scalar | False | False || Scalar
2 | Scalar | False | True || Scalar
3 | Scalar | True | False || Scalar
4 | Scalar | True | True || Scalar
5 | Null | False | False || False
6 | Null | False | True || False
7 | Null | True | False || False
8 | Null | True | True || False
9 | Absent | False | False || False
10 | Absent | False | True || False
11 | Absent | True | False || False
12 | Absent | True | True || True
yaml = node type present in yaml file
store = nvp.value().has_value() initial condition
acwny = Options.allow_cpp_with_no_yaml
want = nvp.value() desired final condition
*/
test_no_default("doc:\n value: 1.0", 1.0); // # 1, 2
test_with_default("doc:\n value: 1.0", 1.0); // # 3, 4
test_no_default("doc:\n value:", std::nullopt); // # 5, 6
test_with_default("doc:\n value:", std::nullopt); // # 7, 8
test_no_default("doc: {}", std::nullopt); // # 9, 10
if (GetParam().allow_cpp_with_no_yaml) {
test_with_default("doc: {}", kNominalDouble); // # 12
} else {
test_with_default("doc: {}", std::nullopt); // # 11
}
if (GetParam().allow_yaml_with_no_cpp) {
test_no_default("doc:\n foo: bar\n value: 1.0", 1.0); // # 1, 2
test_with_default("doc:\n foo: bar\n value: 1.0", 1.0); // # 3, 4
test_no_default("doc:\n foo: bar\n value:", std::nullopt); // # 5, 6
test_with_default("doc:\n foo: bar\n value:", std::nullopt); // # 7, 8
test_no_default("doc:\n foo: bar", std::nullopt); // # 9, 10
if (GetParam().allow_cpp_with_no_yaml) {
test_with_default("doc:\n foo: bar", kNominalDouble); // # 12
} else {
test_with_default("doc:\n foo: bar", std::nullopt); // # 11
}
}
}
TEST_P(YamlReadArchiveTest, Variant) {
const auto test = [](const std::string& doc,
const Variant4& expected) {
const auto& x = AcceptNoThrow<VariantStruct>(Load(doc));
EXPECT_EQ(x.value, expected) << doc;
};
test("doc:\n value: !!str foo", "foo");
test("doc:\n value: !!float 1.0", 1.0);
test("doc:\n value: !DoubleStruct { value: 1.0 }", DoubleStruct{1.0});
}
TEST_P(YamlReadArchiveTest, VariantMissing) {
const auto& x = AcceptEmptyDoc<VariantStruct>();
EXPECT_EQ(std::get<double>(x.value), kNominalDouble);
}
TEST_P(YamlReadArchiveTest, EigenVector) {
const auto test = [](const std::string& value,
const Eigen::VectorXd& expected) {
const auto& vec = AcceptNoThrow<EigenVecStruct>(LoadSingleValue(value));
const auto& vec3 = AcceptNoThrow<EigenVec3Struct>(LoadSingleValue(value));
EXPECT_TRUE(drake::CompareMatrices(vec.value, expected));
EXPECT_TRUE(drake::CompareMatrices(vec3.value, expected));
};
test("[1.0, 2.0, 3.0]", Eigen::Vector3d(1.0, 2.0, 3.0));
}
TEST_P(YamlReadArchiveTest, EigenVectorX) {
const auto test = [](const std::string& value,
const Eigen::VectorXd& expected) {
const auto& x = AcceptNoThrow<EigenVecStruct>(LoadSingleValue(value));
EXPECT_TRUE(drake::CompareMatrices(x.value, expected));
};
test("[]", Eigen::VectorXd());
test("[1.0]", Eigen::Matrix<double, 1, 1>(1.0));
}
TEST_P(YamlReadArchiveTest, EigenMatrix) {
using Matrix34d = Eigen::Matrix<double, 3, 4>;
const auto test = [](const std::string& doc,
const Eigen::MatrixXd& expected) {
const auto& mat = AcceptNoThrow<EigenMatrixStruct>(Load(doc));
const auto& mat34 = AcceptNoThrow<EigenMatrix34Struct>(Load(doc));
EXPECT_TRUE(drake::CompareMatrices(mat.value, expected));
EXPECT_TRUE(drake::CompareMatrices(mat34.value, expected));
};
test(R"""(
doc:
value:
- [0.0, 1.0, 2.0, 3.0]
- [4.0, 5.0, 6.0, 7.0]
- [8.0, 9.0, 10.0, 11.0]
)""", (Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished());
}
TEST_P(YamlReadArchiveTest, EigenMatrixUpTo6) {
using Matrix34d = Eigen::Matrix<double, 3, 4>;
const auto test = [](const std::string& doc,
const Matrix34d& expected) {
const auto& mat = AcceptNoThrow<EigenMatrixUpTo6Struct>(Load(doc));
EXPECT_TRUE(drake::CompareMatrices(mat.value, expected));
};
test(R"""(
doc:
value:
- [0.0, 1.0, 2.0, 3.0]
- [4.0, 5.0, 6.0, 7.0]
- [8.0, 9.0, 10.0, 11.0]
)""", (Matrix34d{} << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).finished());
}
TEST_P(YamlReadArchiveTest, EigenMatrix00) {
const auto test = [](const std::string& doc) {
const auto& mat = AcceptNoThrow<EigenMatrixStruct>(Load(doc));
const auto& mat00 = AcceptNoThrow<EigenMatrix00Struct>(Load(doc));
const Eigen::MatrixXd empty;
EXPECT_TRUE(drake::CompareMatrices(mat.value, empty));
EXPECT_TRUE(drake::CompareMatrices(mat00.value, empty));
};
test(R"""(
doc:
value: []
)""");
test(R"""(
doc:
value: [[]]
)""");
}
TEST_P(YamlReadArchiveTest, EigenMissing) {
const auto& vx = AcceptEmptyDoc<EigenVecStruct>();
const auto& vn = AcceptEmptyDoc<EigenVec3Struct>();
const auto& mx = AcceptEmptyDoc<EigenMatrixStruct>();
const auto& mn = AcceptEmptyDoc<EigenMatrix34Struct>();
ASSERT_EQ(vx.value.size(), 1);
ASSERT_EQ(mx.value.size(), 1);
EXPECT_EQ(vx.value(0), kNominalDouble);
EXPECT_EQ(vn.value(0), kNominalDouble);
EXPECT_EQ(mx.value(0, 0), kNominalDouble);
EXPECT_EQ(mn.value(0, 0), kNominalDouble);
}
TEST_P(YamlReadArchiveTest, Nested) {
const auto& x = AcceptNoThrow<OuterStruct>(Load(R"""(
doc:
outer_value: 1.0
inner_struct:
inner_value: 2.0
)"""));
EXPECT_EQ(x.outer_value, 1.0);
EXPECT_EQ(x.inner_struct.inner_value, 2.0);
}
TEST_P(YamlReadArchiveTest, NestedWithMergeKeys) {
const auto test = [](const std::string& orig_doc) {
std::string doc = orig_doc;
if (!GetParam().allow_yaml_with_no_cpp) {
doc = std::regex_replace(
orig_doc, std::regex(" *ignored_key: ignored_value"), "");
}
SCOPED_TRACE("With doc = " + doc);
const auto& x = AcceptNoThrow<OuterStruct>(Load(doc));
EXPECT_EQ(x.outer_value, 1.0);
EXPECT_EQ(x.inner_struct.inner_value, 2.0);
};
// Use merge keys to populate InnerStruct.
test(R"""(
_template: &template
inner_value: 2.0
ignored_key: ignored_value
doc:
inner_struct:
<< : *template
outer_value: 1.0
)""");
// Use merge keys to populate InnerStruct, though to no effect because the
// existing value wins.
test(R"""(
_template: &template
inner_value: 3.0
ignored_key: ignored_value
doc:
inner_struct:
<< : *template
inner_value: 2.0
outer_value: 1.0
)""");
// Use merge keys to populate OuterStruct.
test(R"""(
_template: &template
inner_struct:
inner_value: 2.0
ignored_key: ignored_value
doc:
<< : *template
outer_value: 1.0
)""");
// Use array of merge keys to populate OuterStruct.
// First array with a value wins.
test(R"""(
_template: &template
- inner_struct:
inner_value: 2.0
ignored_key: ignored_value
- inner_struct:
inner_value: 3.0
doc:
<< : *template
outer_value: 1.0
)""");
}
TEST_P(YamlReadArchiveTest, NestedWithBadMergeKey) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
_template: &template 99.0
doc:
inner_struct:
<< : *template
outer_value: 1.0
)""")),
"YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" has invalid merge key type \\(Scalar\\)\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
_template: &template
doc:
inner_struct:
<< : *template
outer_value: 1.0
)""")),
"YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" has invalid merge key type \\(Null\\)\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
_template: &template
- inner_value
- 2.0
doc:
<< : *template
outer_value: 1.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{outer_value\\}\\)"
" has invalid merge key type \\(Sequence-of-non-Mapping\\)\\.");
}
// This finds nothing when a scalar was wanted, because the name had a typo.
TEST_P(YamlReadArchiveTest, VisitScalarFoundNothing) {
// This has a "_TYPO" in a field name.
const YAML::Node node = Load(R"""(
doc:
outer_value: 1.0
inner_struct:
inner_value_TYPO: 2.0
)""");
if (GetParam().allow_cpp_with_no_yaml &&
GetParam().allow_yaml_with_no_cpp) {
const auto& x = AcceptNoThrow<OuterStruct>(node);
EXPECT_EQ(x.outer_value, 1.0);
EXPECT_EQ(x.inner_struct.inner_value, kNominalDouble);
} else if (GetParam().allow_cpp_with_no_yaml) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(node),
"YAML node of type Mapping"
" \\(with size 1 and keys \\{inner_value_TYPO\\}\\)"
" key inner_value_TYPO did not match any visited value entry for <root>"
" while accepting YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" while visiting [^ ]*InnerStruct inner_struct\\.");
} else {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(node),
"YAML node of type Mapping"
" \\(with size 1 and keys \\{inner_value_TYPO\\}\\)"
" is missing entry for double inner_value"
" while accepting YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" while visiting [^ ]*InnerStruct inner_struct\\.");
}
}
// This finds an array when a scalar was wanted.
TEST_P(YamlReadArchiveTest, VisitScalarFoundArray) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
doc:
outer_value: 1.0
inner_struct:
inner_value: [2.0, 3.0]
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{inner_value\\}\\)"
" has non-Scalar \\(Sequence\\) entry for double inner_value"
" while accepting YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" while visiting [^ ]*InnerStruct inner_struct\\.");
}
// This finds a struct when a scalar was wanted.
TEST_P(YamlReadArchiveTest, VisitScalarFoundStruct) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
doc:
outer_value: 1.0
inner_struct:
inner_value:
key: 2.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{inner_value\\}\\)"
" has non-Scalar \\(Mapping\\) entry for double inner_value"
" while accepting YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" while visiting [^ ]*InnerStruct inner_struct\\.");
}
// This finds nothing when a std::array was wanted.
TEST_P(YamlReadArchiveTest, VisitArrayFoundNothing) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<ArrayStruct>(LoadSingleValue("")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for std::array<.*> value\\.");
}
// This finds a scalar when a std::array was wanted.
TEST_P(YamlReadArchiveTest, VisitArrayFoundScalar) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<ArrayStruct>(LoadSingleValue("1.0")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for std::array<.*> value\\.");
}
// This finds a sub-structure when a std::array was wanted.
TEST_P(YamlReadArchiveTest, VisitArrayFoundStruct) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<ArrayStruct>(Load(R"""(
doc:
value:
inner_value: 1.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Mapping\\) entry for std::array<.*> value\\.");
}
// This finds nothing when a std::vector was wanted.
TEST_P(YamlReadArchiveTest, VisitVectorFoundNothing) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VectorStruct>(LoadSingleValue("")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for std::vector<.*> value\\.");
}
// This finds a scalar when a std::vector was wanted.
TEST_P(YamlReadArchiveTest, VisitVectorFoundScalar) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VectorStruct>(LoadSingleValue("1.0")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for std::vector<.*> value\\.");
}
// This finds a sub-structure when a std::vector was wanted.
TEST_P(YamlReadArchiveTest, VisitVectorFoundStruct) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VectorStruct>(Load(R"""(
doc:
value:
inner_value: 1.0
)""")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Mapping\\) entry for std::vector<.*> value\\.");
}
// This finds a sequence when an optional<double> was wanted.
TEST_P(YamlReadArchiveTest, VisitOptionalScalarFoundSequence) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OptionalStruct>(LoadSingleValue("[1.0]")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Scalar \\(Sequence\\) entry for std::optional<double>"
" value\\.");
}
// This finds various untagged things when a variant was wanted.
TEST_P(YamlReadArchiveTest, VisitVariantFoundNoTag) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VariantWrappingStruct>(
Load("doc:\n inner:\n value:")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Scalar \\(Null\\) entry for std::string value"
" while accepting YAML node of type Mapping \\(with size 1 and keys"
" \\{inner\\}\\) while visiting drake::yaml::test::VariantStruct inner.");
// std::string values should load correctly even without a YAML type tag.
const auto& str = AcceptNoThrow<VariantWrappingStruct>(
Load("doc:\n inner:\n value: foo"));
EXPECT_EQ(str.inner.value, Variant4("foo"));
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VariantWrappingStruct>(
Load("doc:\n inner:\n value: [foo, bar]")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Scalar \\(Sequence\\) entry for std::string value"
" while accepting YAML node of type Mapping \\(with size 1 and keys"
" \\{inner\\}\\) while visiting drake::yaml::test::VariantStruct inner.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VariantWrappingStruct>(
Load("doc:\n inner:\n value: {foo: bar}")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Scalar \\(Mapping\\) entry for std::string value\\"
" while accepting YAML node of type Mapping \\(with size 1 and keys"
" \\{inner\\}\\) while visiting drake::yaml::test::VariantStruct inner.");
}
// This finds an unknown tag when a variant was wanted.
TEST_P(YamlReadArchiveTest, VisitVariantFoundUnknownTag) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<VariantStruct>(Load("doc:\n value: !UnknownTag foo")),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\) "
"has unsupported type tag !UnknownTag "
"while selecting a variant<> entry for "
"std::variant<std::string,double,drake::yaml::test::DoubleStruct,"
"drake::yaml::test::EigenStruct<-1,1,-1,1>> value.");
}
// This finds nothing when an Eigen::Vector or Eigen::Matrix was wanted.
TEST_P(YamlReadArchiveTest, VisitEigenFoundNothing) {
const std::string value;
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenVecStruct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for Eigen::VectorXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenVec3Struct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for Eigen::Vector3d value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for Eigen::MatrixXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Null\\) entry for Eigen::Matrix.*3,4.* value\\.");
}
// This finds a scalar when an Eigen::Vector or Eigen::Matrix was wanted.
TEST_P(YamlReadArchiveTest, VisitEigenFoundScalar) {
const std::string value{"1.0"};
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenVecStruct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for Eigen::VectorXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenVec3Struct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for Eigen::Vector3d value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for Eigen::MatrixXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has non-Sequence \\(Scalar\\) entry for Eigen::Matrix.* value\\.");
}
// This finds a one-dimensional Sequence when a 2-d Eigen::Matrix was wanted.
TEST_P(YamlReadArchiveTest, VisitEigenMatrixFoundOneDimensional) {
const std::string value{"[1.0, 2.0, 3.0, 4.0]"};
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrixStruct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" is Sequence-of-Scalar \\(not Sequence-of-Sequence\\)"
" entry for Eigen::MatrixXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrix34Struct>(LoadSingleValue(value)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" is Sequence-of-Scalar \\(not Sequence-of-Sequence\\)"
" entry for Eigen::Matrix.* value\\.");
}
// This finds a non-square (4+4+3) matrix, when an Eigen::Matrix was wanted.
TEST_P(YamlReadArchiveTest, VisitEigenMatrixFoundNonSquare) {
const std::string doc(R"""(
doc:
value:
- [0.0, 1.0, 2.0, 3.0]
- [4.0, 5.0, 6.0, 7.0]
- [8.0, 9.0, 0.0]
)""");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrixStruct>(Load(doc)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has inconsistent cols dimensions entry for Eigen::MatrixXd value\\.");
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<EigenMatrix34Struct>(Load(doc)),
"YAML node of type Mapping \\(with size 1 and keys \\{value\\}\\)"
" has inconsistent cols dimensions entry for Eigen::Matrix.* value\\.");
}
// This finds nothing when a sub-structure was wanted.
TEST_P(YamlReadArchiveTest, VisitStructFoundNothing) {
const YAML::Node node = Load(R"""(
doc:
outer_value: 1.0
)""");
if (GetParam().allow_cpp_with_no_yaml) {
const auto& x = AcceptNoThrow<OuterStruct>(node);
EXPECT_EQ(x.outer_value, 1.0);
EXPECT_EQ(x.inner_struct.inner_value, kNominalDouble);
} else {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(node),
"YAML node of type Mapping \\(with size 1 and keys \\{outer_value\\}\\)"
" is missing entry for [^ ]*InnerStruct inner_struct\\.");
}
}
// This finds a scalar when a sub-structure was wanted.
TEST_P(YamlReadArchiveTest, VisitStructFoundScalar) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
doc:
outer_value: 1.0
inner_struct: 2.0
)""")),
"YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" has non-Mapping \\(Scalar\\) entry for"
" [^ ]*InnerStruct inner_struct\\.");
}
// This finds an array when a sub-structure was wanted.
TEST_P(YamlReadArchiveTest, VisitStructFoundArray) {
DRAKE_EXPECT_THROWS_MESSAGE(
AcceptIntoDummy<OuterStruct>(Load(R"""(
doc:
outer_value: 1.0
inner_struct: [2.0, 3.0]
)""")),
"YAML node of type Mapping"
" \\(with size 2 and keys \\{inner_struct, outer_value\\}\\)"
" has non-Mapping \\(Sequence\\) entry for"
" [^ ]*InnerStruct inner_struct\\.");
}
std::vector<YamlReadArchive::Options> MakeAllPossibleOptions() {
std::vector<YamlReadArchive::Options> all;
for (const bool i : {false, true}) {
for (const bool j : {false, true}) {
for (const bool k : {false, true}) {
all.push_back(YamlReadArchive::Options{i, j, k});
}
}
}
return all;
}
INSTANTIATE_TEST_SUITE_P(
AllOptions, YamlReadArchiveTest,
::testing::ValuesIn(MakeAllPossibleOptions()));
} // namespace
} // namespace test
} // namespace yaml
} // namespace drake
| [
"mamurtaza@live.com"
] | mamurtaza@live.com |
d5de5de4c0fe0281f63790c9f372c89478d25579 | cd378f83f04edaf4c6b14d041e746a1140abbe8b | /210317_WinAPI/RightMove.cpp | e30ee331720587929baff062b0d605cc2ba958d1 | [] | no_license | soapunny/Strikers1945 | bd812bd6339e490b2a95ba9adbbb86b548c51bf0 | ef6259b9dca087d64a79724c89a3478356a47dd3 | refs/heads/main | 2023-04-10T03:04:10.101571 | 2021-04-23T00:33:17 | 2021-04-23T00:33:17 | 358,157,660 | 0 | 0 | null | 2021-04-22T22:05:46 | 2021-04-15T06:52:28 | C++ | UTF-8 | C++ | false | false | 211 | cpp | #include "RightMove.h"
void RightMove::DoMove(FPOINT* pos, float* angle)
{
float elapsedTime = TimerManager::GetSingleton()->getElapsedTime();
//if (pos->y < 400)
{
pos->x += moveSpeed * elapsedTime;;
}
}
| [
"soapunny@gmail.com"
] | soapunny@gmail.com |
6a0510e39fe73cbc3f1e2cb3d81a7cdd4f1a2115 | cb5feef76e521e5c5b82a35ea6a0b92a337ba3d7 | /tfs_0.2.14/src/creature.cpp | ceafd4b223ec0458462ba59967f2018a2b2861bc | [] | no_license | Armada-Azteca/ArmadaAztecaServer | 8a41adf79ce89c6919507ae664f71b4e1e9a4f0e | 2513c168583676264addda2106918ae6591ff1a7 | refs/heads/master | 2023-05-25T02:26:57.551274 | 2023-05-24T17:31:52 | 2023-05-24T17:31:52 | 3,155,919 | 8 | 7 | null | 2023-05-17T21:38:06 | 2012-01-11T17:51:57 | C++ | UTF-8 | C++ | false | false | 41,494 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "creature.h"
#include "game.h"
#include "player.h"
#include "npc.h"
#include "monster.h"
#include "container.h"
#include "condition.h"
#include "combat.h"
#include "configmanager.h"
#include <string>
#include <vector>
#include <algorithm>
#if defined __EXCEPTION_TRACER__
#include "exception.h"
#endif
OTSYS_THREAD_LOCKVAR AutoID::autoIDLock;
uint32_t AutoID::count = 1000;
AutoID::list_type AutoID::list;
extern Game g_game;
extern ConfigManager g_config;
extern CreatureEvents* g_creatureEvents;
Creature::Creature() :
isInternalRemoved(false)
{
id = 0;
_tile = NULL;
direction = SOUTH;
master = NULL;
lootDrop = true;
skillLoss = true;
health = 1000;
healthMax = 1000;
mana = 0;
manaMax = 0;
lastStep = 0;
lastStepCost = 1;
baseSpeed = 220;
varSpeed = 0;
masterRadius = -1;
masterPos.x = 0;
masterPos.y = 0;
masterPos.z = 0;
followCreature = NULL;
hasFollowPath = false;
eventWalk = 0;
cancelNextWalk = false;
forceUpdateFollowPath = false;
isMapLoaded = false;
isUpdatingPath = false;
memset(localMapCache, 0, sizeof(localMapCache));
attackedCreature = NULL;
_lastHitCreature = NULL;
_mostDamageCreature = NULL;
lastHitUnjustified = false;
mostDamageUnjustified = false;
lastHitCreature = 0;
blockCount = 0;
blockTicks = 0;
walkUpdateTicks = 0;
checkCreatureVectorIndex = -1;
creatureCheck = false;
scriptEventsBitField = 0;
hiddenHealth = false;
onIdleStatus();
}
Creature::~Creature()
{
std::list<Creature*>::iterator cit;
for(cit = summons.begin(); cit != summons.end(); ++cit)
{
(*cit)->setAttackedCreature(NULL);
(*cit)->setMaster(NULL);
(*cit)->releaseThing2();
}
summons.clear();
for(ConditionList::iterator it = conditions.begin(); it != conditions.end(); ++it)
{
(*it)->endCondition(this, CONDITIONEND_CLEANUP);
delete *it;
}
conditions.clear();
attackedCreature = NULL;
//std::cout << "Creature destructor " << this->getID() << std::endl;
}
bool Creature::canSee(const Position& myPos, const Position& pos, uint32_t viewRangeX, uint32_t viewRangeY)
{
if(myPos.z <= 7)
{
//we are on ground level or above (7 -> 0)
//view is from 7 -> 0
if(pos.z > 7)
return false;
}
else if(myPos.z >= 8)
{
//we are underground (8 -> 15)
//view is +/- 2 from the floor we stand on
if(std::abs(myPos.z - pos.z) > 2)
return false;
}
int offsetz = myPos.z - pos.z;
if(((uint32_t)pos.x >= myPos.x - viewRangeX + offsetz) && ((uint32_t)pos.x <= myPos.x + viewRangeX + offsetz) &&
((uint32_t)pos.y >= myPos.y - viewRangeY + offsetz) && ((uint32_t)pos.y <= myPos.y + viewRangeY + offsetz))
return true;
return false;
}
bool Creature::canSee(const Position& pos) const
{
return canSee(getPosition(), pos, Map::maxViewportX, Map::maxViewportY);
}
bool Creature::canSeeCreature(const Creature* creature) const
{
if(!canSeeInvisibility() && creature->isInvisible())
return false;
return true;
}
int64_t Creature::getTimeSinceLastMove() const
{
if(lastStep)
return OTSYS_TIME() - lastStep;
return 0x7FFFFFFFFFFFFFFFLL;
}
int32_t Creature::getWalkDelay(Direction dir) const
{
if(lastStep != 0)
{
int64_t ct = OTSYS_TIME();
int64_t stepDuration = getStepDuration(dir);
return stepDuration - (ct - lastStep);
}
return 0;
}
int32_t Creature::getWalkDelay() const
{
//Used for auto-walking
if(lastStep != 0)
{
int64_t ct = OTSYS_TIME();
int64_t stepDuration = getStepDuration() * lastStepCost;
return stepDuration - (ct - lastStep);
}
return 0;
}
void Creature::onThink(uint32_t interval)
{
if(!isMapLoaded && useCacheMap())
{
isMapLoaded = true;
updateMapCache();
}
if(followCreature && getMaster() != followCreature && !canSeeCreature(followCreature))
onCreatureDisappear(followCreature, false);
if(attackedCreature && getMaster() != attackedCreature && !canSeeCreature(attackedCreature))
onCreatureDisappear(attackedCreature, false);
blockTicks += interval;
if(blockTicks >= 1000)
{
blockCount = std::min((uint32_t)blockCount + 1, (uint32_t)2);
blockTicks = 0;
}
if(followCreature)
{
walkUpdateTicks += interval;
if(forceUpdateFollowPath || walkUpdateTicks >= 2000)
{
walkUpdateTicks = 0;
forceUpdateFollowPath = false;
isUpdatingPath = true;
}
}
if(isUpdatingPath)
{
isUpdatingPath = false;
goToFollowCreature();
}
//scripting event - onThink
CreatureEventList thinkEvents = getCreatureEvents(CREATURE_EVENT_THINK);
for(CreatureEventList::const_iterator it = thinkEvents.begin(), end = thinkEvents.end(); it != end; ++it)
(*it)->executeOnThink(this, interval);
}
void Creature::onAttacking(uint32_t interval)
{
if(attackedCreature)
{
onAttacked();
attackedCreature->onAttacked();
if(g_game.isSightClear(getPosition(), attackedCreature->getPosition(), true))
doAttacking(interval);
}
}
void Creature::onIdleStatus()
{
if(getHealth() > 0)
{
healMap.clear();
damageMap.clear();
}
}
void Creature::onWalk()
{
if(getWalkDelay() <= 0)
{
Direction dir;
uint32_t flags = FLAG_IGNOREFIELDDAMAGE;
if(getNextStep(dir, flags))
{
ReturnValue ret = g_game.internalMoveCreature(this, dir, flags);
if(ret != RET_NOERROR)
{
if(Player* player = getPlayer())
{
player->sendCancelMessage(ret);
player->sendCancelWalk();
}
forceUpdateFollowPath = true;
}
}
else
{
if(listWalkDir.empty())
onWalkComplete();
stopEventWalk();
}
}
if(cancelNextWalk)
{
listWalkDir.clear();
onWalkAborted();
cancelNextWalk = false;
}
if(eventWalk != 0)
{
eventWalk = 0;
addEventWalk();
}
}
void Creature::onWalk(Direction& dir)
{
if(hasCondition(CONDITION_DRUNK))
{
uint32_t r = random_range(0, 16);
if(r <= 4)
{
switch(r)
{
case 0: dir = NORTH; break;
case 1: dir = WEST; break;
case 3: dir = SOUTH; break;
case 4: dir = EAST; break;
default:
break;
}
g_game.internalCreatureSay(this, SPEAK_MONSTER_SAY, "Hicks!", false);
}
}
}
bool Creature::getNextStep(Direction& dir, uint32_t& flags)
{
if(!listWalkDir.empty())
{
dir = listWalkDir.front();
listWalkDir.pop_front();
onWalk(dir);
return true;
}
return false;
}
bool Creature::startAutoWalk(std::list<Direction>& listDir)
{
if(getPlayer() && getPlayer()->getNoMove())
{
getPlayer()->sendCancelWalk();
return false;
}
listWalkDir = listDir;
addEventWalk(listDir.size() == 1);
return true;
}
void Creature::addEventWalk(bool firstStep)
{
cancelNextWalk = false;
if(getStepSpeed() <= 0)
return;
if(eventWalk == 0)
{
int64_t ticks = getEventStepTicks(firstStep);
if(ticks > 0)
{
// Take first step right away, but still queue the next
if(ticks == 1)
g_game.checkCreatureWalk(getID());
eventWalk = g_scheduler.addEvent(createSchedulerTask(
std::max((int64_t)SCHEDULER_MINTICKS, ticks), boost::bind(&Game::checkCreatureWalk, &g_game, getID())));
}
}
}
void Creature::stopEventWalk()
{
if(eventWalk != 0)
{
g_scheduler.stopEvent(eventWalk);
eventWalk = 0;
}
}
void Creature::updateMapCache()
{
Tile* tile;
const Position& myPos = getPosition();
Position pos(0, 0, myPos.z);
for(int32_t y = -((mapWalkHeight - 1) / 2); y <= ((mapWalkHeight - 1) / 2); ++y)
{
for(int32_t x = -((mapWalkWidth - 1) / 2); x <= ((mapWalkWidth - 1) / 2); ++x)
{
pos.x = myPos.x + x;
pos.y = myPos.y + y;
tile = g_game.getTile(pos.x, pos.y, myPos.z);
updateTileCache(tile, pos);
}
}
}
#ifdef __DEBUG__
void Creature::validateMapCache()
{
const Position& myPos = getPosition();
for(int32_t y = -((mapWalkHeight - 1) / 2); y <= ((mapWalkHeight - 1) / 2); ++y)
{
for(int32_t x = -((mapWalkWidth - 1) / 2); x <= ((mapWalkWidth - 1) / 2); ++x)
getWalkCache(Position(myPos.x + x, myPos.y + y, myPos.z));
}
}
#endif
void Creature::updateTileCache(const Tile* tile, int32_t dx, int32_t dy)
{
if((std::abs(dx) <= (mapWalkWidth - 1) / 2) &&
(std::abs(dy) <= (mapWalkHeight - 1) / 2))
{
int32_t x = (mapWalkWidth - 1) / 2 + dx;
int32_t y = (mapWalkHeight - 1) / 2 + dy;
localMapCache[y][x] = (tile && tile->__queryAdd(0, this, 1,
FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RET_NOERROR);
}
#ifdef __DEBUG__
else
std::cout << "Creature::updateTileCache out of range." << std::endl;
#endif
}
void Creature::updateTileCache(const Tile* tile, const Position& pos)
{
const Position& myPos = getPosition();
if(pos.z == myPos.z)
{
int32_t dx = pos.x - myPos.x;
int32_t dy = pos.y - myPos.y;
updateTileCache(tile, dx, dy);
}
}
int32_t Creature::getWalkCache(const Position& pos) const
{
if(!useCacheMap())
return 2;
const Position& myPos = getPosition();
if(myPos.z != pos.z)
return 0;
if(pos == myPos)
return 1;
int32_t dx = pos.x - myPos.x;
int32_t dy = pos.y - myPos.y;
if((std::abs(dx) <= (mapWalkWidth - 1) / 2) &&
(std::abs(dy) <= (mapWalkHeight - 1) / 2))
{
int32_t x = (mapWalkWidth - 1) / 2 + dx;
int32_t y = (mapWalkHeight - 1) / 2 + dy;
#ifdef __DEBUG__
//testing
Tile* tile = g_game.getTile(pos.x, pos.y, pos.z);
if(tile && (tile->__queryAdd(0, this, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RET_NOERROR))
{
if(!localMapCache[y][x])
std::cout << "Wrong cache value" << std::endl;
}
else
{
if(localMapCache[y][x])
std::cout << "Wrong cache value" << std::endl;
}
#endif
if(localMapCache[y][x])
return 1;
else
return 0;
}
//out of range
return 2;
}
void Creature::onAddTileItem(const Tile* tile, const Position& pos, const Item* item)
{
if(isMapLoaded)
{
if(pos.z == getPosition().z)
updateTileCache(tile, pos);
}
}
void Creature::onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem,
const ItemType& oldType, const Item* newItem, const ItemType& newType)
{
if(isMapLoaded)
{
if(oldType.blockSolid || oldType.blockPathFind || newType.blockPathFind || newType.blockSolid)
{
if(pos.z == getPosition().z)
updateTileCache(tile, pos);
}
}
}
void Creature::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType,
const Item* item)
{
if(isMapLoaded)
{
if(iType.blockSolid || iType.blockPathFind || iType.isGroundTile())
{
if(pos.z == getPosition().z)
updateTileCache(tile, pos);
}
}
}
void Creature::onUpdateTile(const Tile* tile, const Position& pos)
{
//
}
void Creature::onCreatureAppear(const Creature* creature, bool isLogin)
{
if(creature == this)
{
if(useCacheMap())
{
isMapLoaded = true;
updateMapCache();
}
if(isLogin)
setLastPosition(getPosition());
}
else if(isMapLoaded)
{
if(creature->getPosition().z == getPosition().z)
updateTileCache(creature->getTile(), creature->getPosition());
}
}
void Creature::onCreatureDisappear(const Creature* creature, uint32_t stackpos, bool isLogout)
{
onCreatureDisappear(creature, true);
if(creature == this)
{
if(getMaster() && !getMaster()->isRemoved())
getMaster()->removeSummon(this);
}
else if(isMapLoaded)
{
if(creature->getPosition().z == getPosition().z)
updateTileCache(creature->getTile(), creature->getPosition());
}
}
void Creature::onCreatureDisappear(const Creature* creature, bool isLogout)
{
if(attackedCreature == creature)
{
setAttackedCreature(NULL);
onAttackedCreatureDisappear(isLogout);
}
if(followCreature == creature)
{
setFollowCreature(NULL);
onFollowCreatureDisappear(isLogout);
}
}
void Creature::onChangeZone(ZoneType_t zone)
{
if(attackedCreature)
{
if(zone == ZONE_PROTECTION)
onCreatureDisappear(attackedCreature, false);
}
}
void Creature::onAttackedCreatureChangeZone(ZoneType_t zone)
{
if(zone == ZONE_PROTECTION)
onCreatureDisappear(attackedCreature, false);
}
void Creature::onCreatureMove(const Creature* creature, const Tile* newTile, const Position& newPos,
const Tile* oldTile, const Position& oldPos, bool teleport)
{
if(creature == this)
{
lastStep = OTSYS_TIME();
lastStepCost = 1;
if(!teleport)
{
if(oldPos.z != newPos.z)
{
//floor change extra cost
lastStepCost = 1;
}
else if(std::abs(newPos.x - oldPos.x) >=1 && std::abs(newPos.y - oldPos.y) >= 1)
{
//diagonal extra cost
lastStepCost = 3;
}
}
else
stopEventWalk();
if(!summons.empty())
{
//check if any of our summons is out of range (+/- 2 floors or 30 tiles away)
std::list<Creature*> despawnList;
std::list<Creature*>::iterator cit;
for(cit = summons.begin(); cit != summons.end(); ++cit)
{
const Position pos = (*cit)->getPosition();
if((std::abs(pos.z - newPos.z) > 2) ||
(std::max(std::abs((newPos.x) - pos.x), std::abs((newPos.y - 1) - pos.y)) > 30))
{
despawnList.push_back((*cit));
}
}
for(cit = despawnList.begin(); cit != despawnList.end(); ++cit)
g_game.removeCreature((*cit), true);
}
if(newTile->getZone() != oldTile->getZone())
onChangeZone(getZone());
//update map cache
if(isMapLoaded)
{
if(teleport || oldPos.z != newPos.z)
updateMapCache();
else
{
Tile* tile;
const Position& myPos = getPosition();
Position pos;
if(oldPos.y > newPos.y) //north
{
//shift y south
for(int32_t y = mapWalkHeight - 1 - 1; y >= 0; --y)
memcpy(localMapCache[y + 1], localMapCache[y], sizeof(localMapCache[y]));
//update 0
for(int32_t x = -((mapWalkWidth - 1) / 2); x <= ((mapWalkWidth - 1) / 2); ++x)
{
tile = g_game.getTile(myPos.x + x, myPos.y - ((mapWalkHeight - 1) / 2), myPos.z);
updateTileCache(tile, x, -((mapWalkHeight - 1) / 2));
}
}
else if(oldPos.y < newPos.y) // south
{
//shift y north
for(int32_t y = 0; y <= mapWalkHeight - 1 - 1; ++y)
memcpy(localMapCache[y], localMapCache[y + 1], sizeof(localMapCache[y]));
//update mapWalkHeight - 1
for(int32_t x = -((mapWalkWidth - 1) / 2); x <= ((mapWalkWidth - 1) / 2); ++x)
{
tile = g_game.getTile(myPos.x + x, myPos.y + ((mapWalkHeight - 1) / 2), myPos.z);
updateTileCache(tile, x, (mapWalkHeight - 1) / 2);
}
}
if(oldPos.x < newPos.x) // east
{
//shift y west
int32_t starty = 0;
int32_t endy = mapWalkHeight - 1;
int32_t dy = (oldPos.y - newPos.y);
if(dy < 0)
endy = endy + dy;
else if(dy > 0)
starty = starty + dy;
for(int32_t y = starty; y <= endy; ++y)
{
for(int32_t x = 0; x <= mapWalkWidth - 1 - 1; ++x)
localMapCache[y][x] = localMapCache[y][x + 1];
}
//update mapWalkWidth - 1
for(int32_t y = -((mapWalkHeight - 1) / 2); y <= ((mapWalkHeight - 1) / 2); ++y)
{
tile = g_game.getTile(myPos.x + ((mapWalkWidth - 1) / 2), myPos.y + y, myPos.z);
updateTileCache(tile, (mapWalkWidth - 1) / 2, y);
}
}
else if(oldPos.x > newPos.x) // west
{
//shift y east
int32_t starty = 0;
int32_t endy = mapWalkHeight - 1;
int32_t dy = (oldPos.y - newPos.y);
if(dy < 0)
endy = endy + dy;
else if(dy > 0)
starty = starty + dy;
for(int32_t y = starty; y <= endy; ++y)
{
for(int32_t x = mapWalkWidth - 1 - 1; x >= 0; --x)
localMapCache[y][x + 1] = localMapCache[y][x];
}
//update 0
for(int32_t y = -((mapWalkHeight - 1) / 2); y <= ((mapWalkHeight - 1) / 2); ++y)
{
tile = g_game.getTile(myPos.x - ((mapWalkWidth - 1) / 2), myPos.y + y, myPos.z);
updateTileCache(tile, -((mapWalkWidth - 1) / 2), y);
}
}
updateTileCache(oldTile, oldPos);
#ifdef __DEBUG__
validateMapCache();
#endif
}
}
}
else
{
if(isMapLoaded)
{
const Position& myPos = getPosition();
if(newPos.z == myPos.z)
updateTileCache(newTile, newPos);
if(oldPos.z == myPos.z)
updateTileCache(oldTile, oldPos);
}
}
if(creature == followCreature || (creature == this && followCreature))
{
if(hasFollowPath)
{
isUpdatingPath = true;
g_dispatcher.addTask(createTask(
boost::bind(&Game::updateCreatureWalk, &g_game, getID())));
}
if(newPos.z != oldPos.z || !canSee(followCreature->getPosition()))
onCreatureDisappear(followCreature, false);
}
if(creature == attackedCreature || (creature == this && attackedCreature))
{
if(newPos.z != oldPos.z || !canSee(attackedCreature->getPosition()))
onCreatureDisappear(attackedCreature, false);
else
{
if(hasExtraSwing())
{
//our target is moving lets see if we can get in hit
g_dispatcher.addTask(createTask(
boost::bind(&Game::checkCreatureAttack, &g_game, getID())));
}
if(newTile->getZone() != oldTile->getZone())
onAttackedCreatureChangeZone(attackedCreature->getZone());
}
}
}
void Creature::onCreatureChangeVisible(const Creature* creature, bool visible)
{
//
}
void Creature::onDeath()
{
Creature* mostDamageCreatureMaster = NULL;
Creature* lastHitCreatureMaster = NULL;
if(getKillers(&_lastHitCreature, &_mostDamageCreature))
{
if(_lastHitCreature)
{
lastHitUnjustified = _lastHitCreature->onKilledCreature(this);
lastHitCreatureMaster = _lastHitCreature->getMaster();
}
if(_mostDamageCreature)
{
mostDamageCreatureMaster = _mostDamageCreature->getMaster();
bool isNotLastHitMaster = (_mostDamageCreature != lastHitCreatureMaster);
bool isNotMostDamageMaster = (_lastHitCreature != mostDamageCreatureMaster);
bool isNotSameMaster = lastHitCreatureMaster == NULL || (mostDamageCreatureMaster != lastHitCreatureMaster);
if(_mostDamageCreature != _lastHitCreature && isNotLastHitMaster && isNotMostDamageMaster && isNotSameMaster)
mostDamageUnjustified = _mostDamageCreature->onKilledCreature(this, false);
}
}
for(CountMap::iterator it = damageMap.begin(); it != damageMap.end(); ++it)
{
if(Creature* attacker = g_game.getCreatureByID((*it).first))
attacker->onAttackedCreatureKilled(this);
}
death();
dropCorpse();
if(getMaster())
getMaster()->removeSummon(this);
}
void Creature::dropCorpse()
{
if(!lootDrop && getMonster() && !(master && master->getPlayer()))
{
//scripting event - onDeath
CreatureEventList deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH);
for(CreatureEventList::const_iterator it = deathEvents.begin(); it != deathEvents.end(); ++it)
(*it)->executeOnDeath(this, NULL, _lastHitCreature, _mostDamageCreature, lastHitUnjustified, mostDamageUnjustified);
g_game.addMagicEffect(getPosition(), NM_ME_POFF);
g_game.removeCreature(this, false);
return;
}
Item* splash = NULL;
switch(getRace())
{
case RACE_VENOM:
splash = Item::CreateItem(ITEM_FULLSPLASH, FLUID_GREEN);
break;
case RACE_BLOOD:
splash = Item::CreateItem(ITEM_FULLSPLASH, FLUID_BLOOD);
break;
default:
break;
}
Tile* tile = getTile();
if(splash)
{
g_game.internalAddItem(tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT);
g_game.startDecay(splash);
}
Item* corpse = getCorpse();
if(corpse)
{
g_game.internalAddItem(tile, corpse, INDEX_WHEREEVER, FLAG_NOLIMIT);
g_game.startDecay(corpse);
}
//scripting event - onDeath
CreatureEventList deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH);
for(CreatureEventList::const_iterator it = deathEvents.begin(); it != deathEvents.end(); ++it)
(*it)->executeOnDeath(this, corpse, _lastHitCreature, _mostDamageCreature, lastHitUnjustified, mostDamageUnjustified);
if(corpse)
dropLoot(corpse->getContainer());
g_game.removeCreature(this, false);
}
bool Creature::getKillers(Creature** _lastHitCreature, Creature** _mostDamageCreature)
{
*_lastHitCreature = g_game.getCreatureByID(lastHitCreature);
int32_t mostDamage = 0;
CountBlock_t cb;
for(CountMap::iterator it = damageMap.begin(); it != damageMap.end(); ++it)
{
cb = it->second;
if((cb.total > mostDamage && (OTSYS_TIME() - cb.ticks <= g_game.getInFightTicks())))
{
if((*_mostDamageCreature = g_game.getCreatureByID((*it).first)))
mostDamage = cb.total;
}
}
return (*_lastHitCreature || *_mostDamageCreature);
}
bool Creature::hasBeenAttacked(uint32_t attackerId)
{
CountMap::iterator it = damageMap.find(attackerId);
if(it != damageMap.end())
return (OTSYS_TIME() - it->second.ticks <= g_game.getInFightTicks());
return false;
}
Item* Creature::getCorpse()
{
Item* corpse = Item::CreateItem(getLookCorpse());
return corpse;
}
void Creature::changeHealth(int32_t healthChange)
{
if(healthChange > 0)
health += std::min(healthChange, getMaxHealth() - health);
else
health = std::max((int32_t)0, health + healthChange);
g_game.addCreatureHealth(this);
}
void Creature::changeMana(int32_t manaChange)
{
if(manaChange > 0)
mana += std::min(manaChange, getMaxMana() - mana);
else
mana = std::max((int32_t)0, mana + manaChange);
}
void Creature::drainHealth(Creature* attacker, CombatType_t combatType, int32_t damage)
{
changeHealth(-damage);
if(attacker)
attacker->onAttackedCreatureDrainHealth(this, damage);
}
void Creature::drainMana(Creature* attacker, int32_t manaLoss)
{
onAttacked();
changeMana(-manaLoss);
}
BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage,
bool checkDefense /* = false */, bool checkArmor /* = false */)
{
BlockType_t blockType = BLOCK_NONE;
if(isImmune(combatType))
{
damage = 0;
blockType = BLOCK_IMMUNITY;
}
else if(checkDefense || checkArmor)
{
bool hasDefense = false;
if(blockCount > 0)
{
--blockCount;
hasDefense = true;
}
if(checkDefense && hasDefense)
{
int32_t maxDefense = getDefense();
int32_t minDefense = maxDefense / 2;
damage -= random_range(minDefense, maxDefense);
if(damage <= 0)
{
damage = 0;
blockType = BLOCK_DEFENSE;
checkArmor = false;
}
}
if(checkArmor)
{
int32_t armorValue = getArmor();
int32_t minArmorReduction = 0;
int32_t maxArmorReduction = 0;
if(armorValue > 1)
{
minArmorReduction = (int32_t)std::ceil(armorValue * 0.475);
maxArmorReduction = (int32_t)std::ceil(((armorValue * 0.475) - 1) + minArmorReduction);
}
else if(armorValue == 1)
{
minArmorReduction = 1;
maxArmorReduction = 1;
}
damage -= random_range(minArmorReduction, maxArmorReduction);
if(damage <= 0)
{
damage = 0;
blockType = BLOCK_ARMOR;
}
}
if(hasDefense && blockType != BLOCK_NONE)
onBlockHit(blockType);
}
if(attacker)
{
attacker->onAttackedCreature(this);
attacker->onAttackedCreatureBlockHit(this, blockType);
}
onAttacked();
return blockType;
}
bool Creature::setAttackedCreature(Creature* creature)
{
if(creature)
{
const Position& creaturePos = creature->getPosition();
if(creaturePos.z != getPosition().z || !canSee(creaturePos))
{
attackedCreature = NULL;
return false;
}
}
attackedCreature = creature;
if(attackedCreature)
{
onAttackedCreature(attackedCreature);
attackedCreature->onAttacked();
}
std::list<Creature*>::iterator cit;
for(cit = summons.begin(); cit != summons.end(); ++cit)
(*cit)->setAttackedCreature(creature);
return true;
}
void Creature::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const
{
fpp.fullPathSearch = !hasFollowPath;
fpp.clearSight = true;
fpp.maxSearchDist = 12;
fpp.minTargetDist = 1;
fpp.maxTargetDist = 1;
}
void Creature::goToFollowCreature()
{
if(followCreature)
{
FindPathParams fpp;
getPathSearchParams(followCreature, fpp);
if(g_game.getPathToEx(this, followCreature->getPosition(), listWalkDir, fpp))
{
hasFollowPath = true;
startAutoWalk(listWalkDir);
}
else
hasFollowPath = false;
}
onFollowCreatureComplete(followCreature);
}
bool Creature::setFollowCreature(Creature* creature, bool fullPathSearch /*= false*/)
{
if(creature)
{
if(followCreature == creature)
return true;
const Position& creaturePos = creature->getPosition();
if(creaturePos.z != getPosition().z || !canSee(creaturePos))
{
followCreature = NULL;
return false;
}
if(!listWalkDir.empty())
{
listWalkDir.clear();
onWalkAborted();
}
hasFollowPath = false;
forceUpdateFollowPath = false;
followCreature = creature;
isUpdatingPath = true;
}
else
{
isUpdatingPath = false;
followCreature = NULL;
}
onFollowCreature(creature);
return true;
}
double Creature::getDamageRatio(Creature* attacker) const
{
int32_t totalDamage = 0;
int32_t attackerDamage = 0;
CountBlock_t cb;
for(CountMap::const_iterator it = damageMap.begin(); it != damageMap.end(); ++it)
{
cb = it->second;
totalDamage += cb.total;
if(it->first == attacker->getID())
attackerDamage += cb.total;
}
return ((double)attackerDamage / totalDamage);
}
uint64_t Creature::getGainedExperience(Creature* attacker) const
{
uint64_t lostExperience = getLostExperience();
return attacker->getPlayer() ? ((uint64_t)std::floor(getDamageRatio(attacker) * lostExperience * g_game.getExperienceStage(attacker->getPlayer()->getLevel()))) : ((uint64_t)std::floor(getDamageRatio(attacker) * lostExperience * g_config.getNumber(ConfigManager::RATE_EXPERIENCE)));
}
bool Creature::addDamagePoints(Creature* attacker, int32_t damagePoints)
{
if(damagePoints > 0)
{
uint32_t attackerId = (attacker ? attacker->getID() : 0);
CountMap::iterator it = damageMap.find(attackerId);
if(it == damageMap.end())
{
CountBlock_t cb;
cb.ticks = OTSYS_TIME();
cb.total = damagePoints;
damageMap[attackerId] = cb;
}
else
{
it->second.total += damagePoints;
it->second.ticks = OTSYS_TIME();
}
lastHitCreature = attackerId;
}
return true;
}
void Creature::addHealPoints(Creature* caster, int32_t healthPoints)
{
if(healthPoints > 0)
{
uint32_t casterId = (caster ? caster->getID() : 0);
CountMap::iterator it = healMap.find(casterId);
if(it == healMap.end())
{
CountBlock_t cb;
cb.ticks = OTSYS_TIME();
cb.total = healthPoints;
healMap[casterId] = cb;
}
else
{
it->second.total += healthPoints;
it->second.ticks = OTSYS_TIME();
}
}
}
void Creature::onAddCondition(ConditionType_t type)
{
if(type == CONDITION_PARALYZE && hasCondition(CONDITION_HASTE))
removeCondition(CONDITION_HASTE);
else if(type == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE))
removeCondition(CONDITION_PARALYZE);
}
void Creature::onAddCombatCondition(ConditionType_t type)
{
//
}
void Creature::onEndCondition(ConditionType_t type)
{
//
}
void Creature::onTickCondition(ConditionType_t type, bool& bRemove)
{
if(const MagicField* field = getTile()->getFieldItem())
{
switch(type)
{
case CONDITION_FIRE: bRemove = (field->getCombatType() != COMBAT_FIREDAMAGE); break;
case CONDITION_ENERGY: bRemove = (field->getCombatType() != COMBAT_ENERGYDAMAGE); break;
case CONDITION_POISON: bRemove = (field->getCombatType() != COMBAT_EARTHDAMAGE); break;
case CONDITION_FREEZING: bRemove = (field->getCombatType() != COMBAT_ICEDAMAGE); break;
case CONDITION_DAZZLED: bRemove = (field->getCombatType() != COMBAT_HOLYDAMAGE); break;
case CONDITION_CURSED: bRemove = (field->getCombatType() != COMBAT_DEATHDAMAGE); break;
case CONDITION_DROWN: bRemove = (field->getCombatType() != COMBAT_DROWNDAMAGE); break;
case CONDITION_BLEEDING: bRemove = (field->getCombatType() != COMBAT_PHYSICALDAMAGE); break;
default: break;
}
}
}
void Creature::onCombatRemoveCondition(const Creature* attacker, Condition* condition)
{
removeCondition(condition);
}
void Creature::onAttackedCreature(Creature* target)
{
//
}
void Creature::onAttacked()
{
//
}
void Creature::onAttackedCreatureDrainHealth(Creature* target, int32_t points)
{
target->addDamagePoints(this, points);
if(getMaster() && getMaster()->getPlayer())
{
std::ostringstream ss;
ss << "Your " << asLowerCaseString(getName()) << " deals " << points << " to " << target->getNameDescription() << ".";
getMaster()->getPlayer()->sendTextMessage(MSG_EVENT_DEFAULT, ss.str());
}
}
void Creature::onTargetCreatureGainHealth(Creature* target, int32_t points)
{
target->addHealPoints(this, points);
}
void Creature::onAttackedCreatureKilled(Creature* target)
{
if(target != this)
{
uint64_t gainExp = target->getGainedExperience(this);
onGainExperience(gainExp, target);
}
}
bool Creature::onKilledCreature(Creature* target, bool lastHit/* = true*/)
{
if(getMaster())
getMaster()->onKilledCreature(target);
//scripting event - onKill
CreatureEventList killEvents = getCreatureEvents(CREATURE_EVENT_KILL);
for(CreatureEventList::const_iterator it = killEvents.begin(); it != killEvents.end(); ++it)
(*it)->executeOnKill(this, target);
return false;
}
void Creature::onGainExperience(uint64_t gainExp, Creature* target)
{
if(gainExp > 0)
{
if(getMaster())
{
gainExp = gainExp / 2;
getMaster()->onGainExperience(gainExp, target);
}
const Position& targetPos = getPosition();
Player* thisPlayer = getPlayer();
if(thisPlayer)
{
std::ostringstream ss;
ss << "You gained " << gainExp << " experience points.";
thisPlayer->sendExperienceMessage(MSG_EXPERIENCE, ss.str(), targetPos, gainExp, TEXTCOLOR_WHITE_EXP);
}
std::ostringstream ssExp;
ssExp << getNameDescription() << " gained " << gainExp << " experience points.";
std::string strExp = ssExp.str();
Player* tmpPlayer = NULL;
SpectatorVec list;
g_game.getSpectators(list, targetPos);
for(SpectatorVec::const_iterator it = list.begin(), end = list.end(); it != end; ++it)
{
if((tmpPlayer = (*it)->getPlayer()))
{
if(tmpPlayer != thisPlayer)
tmpPlayer->sendExperienceMessage(MSG_EXPERIENCE_OTHERS, strExp, targetPos, gainExp, TEXTCOLOR_WHITE_EXP);
}
}
}
}
void Creature::onGainSharedExperience(uint64_t gainExp)
{
if(gainExp > 0)
{
const Position& targetPos = getPosition();
Player* thisPlayer = getPlayer();
if(thisPlayer)
{
std::ostringstream ss;
ss << "You gained " << gainExp << " experience points.";
thisPlayer->sendExperienceMessage(MSG_EXPERIENCE, ss.str(), targetPos, gainExp, TEXTCOLOR_WHITE_EXP);
}
std::ostringstream ssExp;
ssExp << getNameDescription() << " gained " << gainExp << " experience points.";
std::string strExp = ssExp.str();
Player* tmpPlayer = NULL;
SpectatorVec list;
g_game.getSpectators(list, targetPos);
for(SpectatorVec::const_iterator it = list.begin(), end = list.end(); it != end; ++it)
{
if((tmpPlayer = (*it)->getPlayer()))
{
if(tmpPlayer != thisPlayer)
tmpPlayer->sendExperienceMessage(MSG_EXPERIENCE_OTHERS, strExp, targetPos, gainExp, TEXTCOLOR_WHITE_EXP);
}
}
}
}
void Creature::onAttackedCreatureBlockHit(Creature* target, BlockType_t blockType)
{
//
}
void Creature::onBlockHit(BlockType_t blockType)
{
//
}
void Creature::addSummon(Creature* creature)
{
//std::cout << "addSummon: " << this << " summon=" << creature << std::endl;
creature->setDropLoot(false);
creature->setLossSkill(false);
creature->setMaster(this);
creature->useThing2();
summons.push_back(creature);
}
void Creature::removeSummon(const Creature* creature)
{
//std::cout << "removeSummon: " << this << " summon=" << creature << std::endl;
std::list<Creature*>::iterator cit = std::find(summons.begin(), summons.end(), creature);
if(cit != summons.end())
{
(*cit)->setDropLoot(false);
(*cit)->setLossSkill(true);
(*cit)->setMaster(NULL);
(*cit)->releaseThing2();
summons.erase(cit);
}
}
bool Creature::addCondition(Condition* condition, bool force/* = false*/)
{
if(condition == NULL)
return false;
if(!force && condition->getType() == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE))
{
int64_t walkDelay = getWalkDelay();
if(walkDelay > 0)
{
g_scheduler.addEvent(createSchedulerTask(walkDelay, boost::bind(&Game::forceAddCondition, &g_game, getID(), condition)));
return false;
}
}
Condition* prevCond = getCondition(condition->getType(), condition->getId(), condition->getSubId());
if(prevCond)
{
prevCond->addCondition(this, condition);
delete condition;
return true;
}
if(condition->startCondition(this))
{
conditions.push_back(condition);
onAddCondition(condition->getType());
return true;
}
delete condition;
return false;
}
bool Creature::addCombatCondition(Condition* condition)
{
//Caution: condition variable could be deleted after the call to addCondition
ConditionType_t type = condition->getType();
if(!addCondition(condition))
return false;
onAddCombatCondition(type);
return true;
}
void Creature::removeCondition(ConditionType_t type, bool force/* = false*/)
{
for(ConditionList::iterator it = conditions.begin(); it != conditions.end();)
{
if((*it)->getType() == type)
{
Condition* condition = *it;
if(!force && (*it)->getType() == CONDITION_PARALYZE)
{
int64_t walkDelay = getWalkDelay();
if(walkDelay > 0)
{
g_scheduler.addEvent(createSchedulerTask(walkDelay, boost::bind(&Game::forceRemoveCondition, &g_game, getID(), type)));
return;
}
}
it = conditions.erase(it);
condition->endCondition(this, CONDITIONEND_ABORT);
delete condition;
onEndCondition(type);
}
else
++it;
}
}
void Creature::removeCondition(ConditionType_t type, ConditionId_t id, bool force/* = false*/)
{
for(ConditionList::iterator it = conditions.begin(); it != conditions.end();)
{
if((*it)->getType() == type && (*it)->getId() == id)
{
Condition* condition = *it;
if(!force && (*it)->getType() == CONDITION_PARALYZE)
{
int64_t walkDelay = getWalkDelay();
if(walkDelay > 0)
{
g_scheduler.addEvent(createSchedulerTask(walkDelay, boost::bind(&Game::forceRemoveCondition, &g_game, getID(), type)));
return;
}
}
it = conditions.erase(it);
condition->endCondition(this, CONDITIONEND_ABORT);
delete condition;
onEndCondition(type);
}
else
++it;
}
}
void Creature::removeCondition(const Creature* attacker, ConditionType_t type)
{
ConditionList tmpList = conditions;
for(ConditionList::iterator it = tmpList.begin(); it != tmpList.end(); ++it)
{
if((*it)->getType() == type)
onCombatRemoveCondition(attacker, *it);
}
}
void Creature::removeCondition(Condition* condition, bool force/* = false*/)
{
ConditionList::iterator it = std::find(conditions.begin(), conditions.end(), condition);
if(it != conditions.end())
{
Condition* condition = *it;
if(!force && (*it)->getType() == CONDITION_PARALYZE)
{
int64_t walkDelay = getWalkDelay();
if(walkDelay > 0)
{
g_scheduler.addEvent(createSchedulerTask(walkDelay, boost::bind(&Game::forceRemoveCondition, &g_game, getID(), (*it)->getType())));
return;
}
}
it = conditions.erase(it);
condition->endCondition(this, CONDITIONEND_ABORT);
onEndCondition(condition->getType());
delete condition;
}
}
Condition* Creature::getCondition(ConditionType_t type) const
{
for(ConditionList::const_iterator it = conditions.begin(); it != conditions.end(); ++it)
{
if((*it)->getType() == type)
return *it;
}
return NULL;
}
Condition* Creature::getCondition(ConditionType_t type, ConditionId_t id, uint32_t subId/* = 0*/) const
{
for(ConditionList::const_iterator it = conditions.begin(); it != conditions.end(); ++it)
{
if((*it)->getType() == type && (*it)->getId() == id && (*it)->getSubId() == subId)
return *it;
}
return NULL;
}
void Creature::executeConditions(uint32_t interval)
{
for(ConditionList::iterator it = conditions.begin(); it != conditions.end();)
{
if(!(*it)->executeCondition(this, interval))
{
ConditionType_t type = (*it)->getType();
Condition* condition = *it;
it = conditions.erase(it);
condition->endCondition(this, CONDITIONEND_TICKS);
delete condition;
onEndCondition(type);
}
else
++it;
}
}
bool Creature::hasCondition(ConditionType_t type, uint32_t subId/* = 0*/) const
{
if(type == CONDITION_EXHAUST_COMBAT && g_game.getStateTime() == 0)
return true;
if(isSuppress(type))
return false;
for(ConditionList::const_iterator it = conditions.begin(); it != conditions.end(); ++it)
{
if((*it)->getType() == type && (*it)->getSubId() == subId)
{
if(g_config.getBoolean(ConfigManager::OLD_CONDITION_ACCURACY))
return true;
if((*it)->getEndTime() == 0)
return true;
int64_t seekTime = g_game.getStateTime();
if(seekTime == 0)
return true;
if((*it)->getEndTime() >= seekTime)
seekTime = (*it)->getEndTime();
if(seekTime >= OTSYS_TIME())
return true;
}
}
return false;
}
bool Creature::isImmune(CombatType_t type) const
{
return hasBitSet((uint32_t)type, getDamageImmunities());
}
bool Creature::isImmune(ConditionType_t type) const
{
return hasBitSet((uint32_t)type, getConditionImmunities());
}
bool Creature::isSuppress(ConditionType_t type) const
{
return hasBitSet((uint32_t)type, getConditionSuppressions());
}
std::string Creature::getDescription(int32_t lookDistance) const
{
std::string str = "a creature";
return str;
}
int32_t Creature::getStepDuration(Direction dir) const
{
int32_t stepDuration = getStepDuration();
if(dir == NORTHWEST || dir == NORTHEAST || dir == SOUTHWEST || dir == SOUTHEAST)
stepDuration <<= 1;
return stepDuration;
}
int32_t Creature::getStepDuration() const
{
if(isRemoved())
return 0;
int32_t duration = 0;
const Tile* tile = getTile();
if(tile && tile->ground)
{
uint32_t groundId = tile->ground->getID();
uint16_t groundSpeed = Item::items[groundId].speed;
uint32_t stepSpeed = getStepSpeed();
if(stepSpeed != 0)
duration = (1000 * groundSpeed) / stepSpeed;
}
return duration;
}
int64_t Creature::getEventStepTicks(bool onlyDelay) const
{
int64_t ret = getWalkDelay();
if(ret <= 0)
{
int32_t stepDuration = getStepDuration();
if(onlyDelay && stepDuration > 0)
ret = 1;
else
ret = stepDuration * lastStepCost;
}
return ret;
}
void Creature::getCreatureLight(LightInfo& light) const
{
light = internalLight;
}
void Creature::setNormalCreatureLight()
{
internalLight.level = 0;
internalLight.color = 0;
}
bool Creature::registerCreatureEvent(const std::string& name)
{
CreatureEvent* event = g_creatureEvents->getEventByName(name);
if(!event)
return false;
CreatureEventType_t type = event->getEventType();
if(hasEventRegistered(type))
{
//check for duplicates
for(CreatureEventList::const_iterator it = eventsList.begin(); it != eventsList.end(); ++it)
{
if(*it == event)
return false;
}
}
else
{
//set the bit
scriptEventsBitField = scriptEventsBitField | ((uint32_t)1 << type);
}
eventsList.push_back(event);
return true;
}
CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type)
{
CreatureEventList tmpEventList;
if(!hasEventRegistered(type))
return tmpEventList;
for(CreatureEventList::const_iterator it = eventsList.begin(); it != eventsList.end(); ++it)
{
if((*it)->getEventType() == type)
tmpEventList.push_back(*it);
}
return tmpEventList;
}
FrozenPathingConditionCall::FrozenPathingConditionCall(const Position& _targetPos)
{
targetPos = _targetPos;
}
bool FrozenPathingConditionCall::isInRange(const Position& startPos, const Position& testPos,
const FindPathParams& fpp) const
{
int32_t dxMin = ((fpp.fullPathSearch || (startPos.x - targetPos.x) <= 0) ? fpp.maxTargetDist : 0);
int32_t dxMax = ((fpp.fullPathSearch || (startPos.x - targetPos.x) >= 0) ? fpp.maxTargetDist : 0);
int32_t dyMin = ((fpp.fullPathSearch || (startPos.y - targetPos.y) <= 0) ? fpp.maxTargetDist : 0);
int32_t dyMax = ((fpp.fullPathSearch || (startPos.y - targetPos.y) >= 0) ? fpp.maxTargetDist : 0);
if(testPos.x > targetPos.x + dxMax || testPos.x < targetPos.x - dxMin)
return false;
if(testPos.y > targetPos.y + dyMax || testPos.y < targetPos.y - dyMin)
return false;
return true;
}
bool FrozenPathingConditionCall::operator()(const Position& startPos, const Position& testPos,
const FindPathParams& fpp, int32_t& bestMatchDist) const
{
if(!isInRange(startPos, testPos, fpp))
return false;
if(fpp.clearSight && !g_game.isSightClear(testPos, targetPos, true))
return false;
int32_t testDist = std::max(std::abs(targetPos.x - testPos.x), std::abs(targetPos.y - testPos.y));
if(fpp.maxTargetDist == 1)
{
if(testDist < fpp.minTargetDist || testDist > fpp.maxTargetDist)
return false;
return true;
}
else if(testDist <= fpp.maxTargetDist)
{
if(testDist < fpp.minTargetDist)
return false;
if(testDist == fpp.maxTargetDist)
{
bestMatchDist = 0;
return true;
}
else if(testDist > bestMatchDist)
{
//not quite what we want, but the best so far
bestMatchDist = testDist;
return true;
}
}
return false;
}
| [
"manuel220@yahoo.com"
] | manuel220@yahoo.com |
249ad36925d79186866371ea44571a6057d949fb | 7129fbb2d290cf2bc5d12351cc5c87093ae52e56 | /IPFinal/IRenderer.hpp | 5714ac2c37fb995c5b2e722b0e45421e4d5e9811 | [] | no_license | 42yeah/IPFinal | 75263668e1fba78724a2181c497a91344988b067 | 161c5ccc7945b9545eae1a173050bb974f60fadd | refs/heads/master | 2020-12-05T21:57:10.591373 | 2020-01-09T09:08:12 | 2020-01-09T09:08:12 | 232,258,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | hpp | //
// Renderer.hpp
// IPFinal
//
// Created by apple on 2020/1/8.
// Copyright © 2020 aiofwa. All rights reserved.
//
#ifndef Renderer_hpp
#define Renderer_hpp
#include "StandardProgram.hpp"
#include "Framebuffer.hpp"
class IRenderer {
public:
IRenderer() {};
virtual void init() = 0;
virtual void render(StandardProgram &standardProgram) = 0;
virtual void renderToFrameBuffer(StandardProgram &standardProgram, Framebuffer &fbo);
};
#endif /* Renderer_hpp */
| [
"potion@live.cn"
] | potion@live.cn |
3e4bf5a52610066835c2a3d611dfdd3b984e20e7 | e29c1365c01a693c5fff034eb17c6080372fdb31 | /scripts/scripthelper.cpp | b83bf14d056f8b4c1c45a377d08a387fd93000a4 | [] | no_license | ClaudiuHNS/OGLeague2 | 574968399bf1141bb03c978ceadbb0c1d8f6b580 | e974de5a2e15d6b403fbf2aa739de25dedad36df | refs/heads/master | 2020-05-24T17:54:23.468796 | 2017-06-08T01:32:59 | 2017-06-08T01:32:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,330 | cpp | #include "scripthelper.h"
#include "scripthelperbb.h"
#include "scripthelperdamage.h"
#include "scripthelperextra.h"
#include "scripthelperspells.h"
#include <iostream>
#include "obj/gameobject.h"
std::vector<AiTimer *> *ScriptHelper::mLevelTimers = nullptr;
std::vector<NeutralTimer *> *ScriptHelper::mNeutralTimers = nullptr;
std::string ScriptHelper::mMapName = "Map1";
void ScriptHelper::RegisterGlobals(sol::global_table state)
{
state["PHYSICAL_DAMAGE"] = 0;
state["MAGIC_DAMAGE"] = 1;
state["TRUE_DAMAGE"] = 2;
state["HIT_Normal"] = 0;
state["HIT_Critical"] = 1;
state["HIT_Miss"] = 3;
state["HIT_Dodge"] = 2;
state["Log"] = &ScriptHelper::Log;
state["GetPosition"] = &ScriptHelper::GetPosition;
state["SetPosition"] = &ScriptHelper::SetPosition;
state["FacePosition"] = &ScriptHelper::FacePosition;
state["IncPosition"] = &ScriptHelper::IncPosition;
state["IncGold"] = &ScriptHelper::IncGold;
state["GiveExpToNearHeroesFromNeutral"] = &ScriptHelper::GiveExpToNearHeroesFromNeutral;
state["GetNormalizedPositionDelta"] = &ScriptHelper::GetNormalizedPositionDelta;
state["Multiply3dPointByScalar"] = &ScriptHelper::Multiply3dPointByScalar;
state["DistPoint3DSegment3D"] = &ScriptHelper::DistPoint3DSegment3D;
state["Add3dPoints"] = &ScriptHelper::Add3dPoints;
state["GetTeamID"] = &ScriptHelper::GetTeamID;
state["GetID"] = &ScriptHelper::GetID;
state["MakeSay"] = &ScriptHelper::MakeSay;
state["GetHQType"] = &ScriptHelper::GetHQType;
state["GetDampenerType"] = &ScriptHelper::GetDampenerType;
state["IsObjectHero"] = &ScriptHelper::IsObjectHero;
state["IsObjectAI"] = &ScriptHelper::IsObjectAI;
state["IsTurretAI"] = &ScriptHelper::IsTurretAI;
state["GetObjectLaneId"] = &ScriptHelper::GetObjectLaneId;
state["GetTurretPosition"] = &ScriptHelper::GetTurretPosition;
state["GetLinkedBarrack"] = &ScriptHelper::GetLinkedBarrack;
state["GetDampener"] = &ScriptHelper::GetDampener;
state["IsDampener"] = &ScriptHelper::IsDampener;
state["SetDampenerState"] = &ScriptHelper::SetDampenerState;
state["GetLane"] = &ScriptHelper::GetLane;
state["EndGame"] = &ScriptHelper::EndGame;
state["InitTimer"] = &ScriptHelper::InitTimer;
state["AssignTeamGold"] = &ScriptHelper::AssignTeamGold;
state["luaNeutralInitTimer"] = &ScriptHelper::luaNeutralInitTimer;
state["SpawnNeutralMinion"] = &ScriptHelper::SpawnNeutralMinion;
state["LoadScriptIntoScript"] = &ScriptHelper::LoadScriptIntoScript;
state["Make3DPoint"] = &ScriptHelper::Make3DPoint;
state["GetTurret"] = &ScriptHelper::GetTurret;
state["GetBarracks"] = &ScriptHelper::GetBarracks;
state["SetDisableMinionSpawn"] = &ScriptHelper::SetDisableMinionSpawn;
state["SetBarracksEnabled"] = &ScriptHelper::SetBarracksEnabled;
state["GetHQ"] = &ScriptHelper::GetHQ;
state["GetTutorialPlayer"] = &ScriptHelper::GetTutorialPlayer;
state["CreateGameObject"] = &ScriptHelper::CreateGameObject;
state["PreloadCharacter"] = &ScriptHelper::PreloadCharacter;
state["PreloadSpell"] = &ScriptHelper::PreloadSpell;
state["PreloadParticle"] = &ScriptHelper::PreloadParticle;
state["GetHashedGameObjName"] = &ScriptHelper::GetHashedGameObjName;
state["SetLaneAffinity"] = &ScriptHelper::SetLaneAffinity;
state["CreateChildTurret"] = &ScriptHelper::CreateChildTurret;
state["ToggleInputLockingFlag"] = &ScriptHelper::ToggleInputLockingFlag;
state["SetInputLockingFlag"] = &ScriptHelper::SetInputLockingFlag;
state["ToggleFogOfWar"] = &ScriptHelper::ToggleFogOfWar;
state["ToggleFogOfWarOn"] = &ScriptHelper::ToggleFogOfWarOn;
state["SetCircularCameraRestriction"] = &ScriptHelper::SetCircularCameraRestriction;
state["LockCamera"] = &ScriptHelper::LockCamera;
state["PauseGame"] = &ScriptHelper::PauseGame;
state["ResumeGame"] = &ScriptHelper::ResumeGame;
state["PlayTutorialAudioEvent"] = &ScriptHelper::PlayTutorialAudioEvent;
state["GetUnitSkinName"] = &ScriptHelper::GetUnitSkinName;
state["IncExp"] = &ScriptHelper::IncExp;
state["GetTime"] = &ScriptHelper::GetTime;
state["_ALERT"] = &ScriptHelper::_ALERT;
state["GetTotalTeamMinionsSpawned"] = &ScriptHelper::GetTotalTeamMinionsSpawned;
}
void ScriptHelper::InitState(sol::state_view state)
{
state.open_libraries(sol::lib::base, sol::lib::math , sol::lib::os, sol::lib::string);
state.new_usertype<r3dPoint3D>("r3dPoint3D");
state.new_usertype<GameObject>("GameObject");
ScriptHelper::RegisterGlobals(state.globals());
ScriptHelperBB::RegisterGlobals(state.globals());
ScriptHelperDamage::RegisterGlobals(state.globals());
ScriptHelperExtra::RegisterGlobals(state.globals());
ScriptHelperSpells::RegisterGlobals(state.globals());
ScriptHelper::LoadLuaFile("DATA/BuildingBlocks/BuildingBlocksBase.lua", state);
ScriptHelper::LoadLuaFile("DATA/BuildingBlocks/BBLuaConversionLibrary.lua", state);
}
bool ScriptHelper::LoadLuaFile(std::string name, sol::state_view state)
{
auto path = r3dFileManager::getFilePath(name);
if(path == "")
path = r3dFileManager::getFilePath(name+"obj");
if(path == "")
return false;
std::cout<<"Loading: "<<path<<std::endl;
state.do_file(path);
return true;
}
| [
"moonshadow565@gmail.com"
] | moonshadow565@gmail.com |
723ab2651fec0c3216962cd4a82ca2dcd89e8c44 | 71ef9f45e2fada26f34c75c1cb9513ccbe3ef17f | /GPStudio/src/main.cpp | b023264545190af7de6dacab822ba0a1e7679f9e | [] | no_license | yangli-learning/TrajectoryCompletion | 0668b1ad6fcf6da9195474df45b3208d2983e68d | 6a46ec1bf2ab6b3c40f2cbf01d51fbe717daeaee | refs/heads/master | 2023-01-29T07:52:57.494362 | 2019-05-26T07:34:41 | 2019-05-26T07:34:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | cpp | #include <QApplication>
//#include <glog/logging.h>
//#include "caffe_wrapper.h"
#include "main_window.h"
#include "guiless.h"
#include <gflags/gflags.h>
#include <ostream>
#include <string>
using namespace std;
string ti="Turns on interactive mode",
tb="Path to bbox file (.yaml format)",
tp="Path to parameter file ",
default_path="../GPStudio/parameters.ini",
tv = "Minimum voting image threshold";
double default_v=0.08;
DEFINE_bool(interactive, true, ti.c_str());
DEFINE_string(trace_fname, "", ti.c_str());
DEFINE_string(bbox_fname, "", tp.c_str()); //"Path to bbox file (.yaml format");
DEFINE_string(param_fname, default_path, tp.c_str()); //"../GPStudio/parameters.ini","Path to parameter file");
DEFINE_double(vmin,default_v,tv.c_str());
bool loadParameters() {
std::string filename(FLAGS_param_fname);
Parameters::getInstance()->setParameterFile(filename);
if (! Parameters::getInstance()->readParameters()){
std::cout << "Can not locate parameter file for GPStudio!" << std::endl;
std::cout << "Expected location: \"" << filename << "\"" << std::endl;
return false;
}
return true;
}
int main(int argc, char *argv[])
{
//::google::InitGoogleLogging("Image2Scene");
qDebug() << "------------------" << endl;
google::ParseCommandLineFlags(&argc,&argv,true);//flags
qDebug() << "------------------" << endl;
if (FLAGS_interactive){
// run with gui, use parameter from default file
google::ShutDownCommandLineFlags();
// Make Xlib and GLX thread safe under X11
QApplication::setAttribute(Qt::AA_X11InitThreads);
QApplication application(argc, argv);
MainWindow::getInstance()->show();//Maximized();
application.exec();
}else{ //run without gui, use parameters from
// read command line options to input, output trajectory,
// bbox dimension
// (including voting image and heading image, hence no need for
// computing voting map)
cout << "parameter file :" << FLAGS_param_fname << endl;
cout << "trajectory file :" << FLAGS_trace_fname << endl;
cout << "bounding box file :" << FLAGS_bbox_fname << endl;
// cout << "c_vmin file :" << FLAGS_vmin << endl;
if (!loadParameters()){
cout <<"Not loading parameters" << endl;
google::ShutDownCommandLineFlags();
//return false;
}
if (FLAGS_vmin){ //v_min overwrite thresh in parameters.ini
cout << "minimum vote threshold :" << FLAGS_vmin << endl;
}
Guiless app(FLAGS_trace_fname , FLAGS_bbox_fname);
google::ShutDownCommandLineFlags();
app.exec();
}
}
| [
"tori2011@gmail.com"
] | tori2011@gmail.com |
b43b6b4064816f12794b997139fa73569a0203cc | 1eb894c9842bbae917f5a8c35784e34abfa35331 | /Assignment-4(Stack & queues)/getMin.cpp | 2fc69d90925468e33315a4cd5bfe658c3114d40d | [] | no_license | witcher-shailesh/CP_CipherSchools | b4dc6b6dd2d1e93d3bddd64779af09dc93ae86bb | 96242b60b90d642fff306dedbc5d69b5ec739c14 | refs/heads/main | 2023-03-08T12:15:29.549532 | 2021-02-22T15:01:44 | 2021-02-22T15:01:44 | 338,615,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 890 | cpp | #include<bits/stdc++.h>
using namespace std;
int getMini=0;
void push(stack<int>& s, int a){
if(s.empty()){
s.push(a);
getMini = a;
}else{
if(a >= getMini){
s.push(a);
}else{
s.push(2*a-getMini);
getMini = a;
}
}
}
bool isFull(stack<int>& s,int n){
return s.size()==n;
}
bool isEmpty(stack<int>& s){
return s.empty();
}
int pop(stack<int>& s){
if(s.empty()){
return 0;
}else{
int top = s.top();
if(top >= getMini){
s.pop();
}else{
getMini =2*getMini - top;
s.pop();
return top;
}
}
}
int getMin(stack<int>& s){
return getMini;
}
int main(){
stack<int> st;
push(st,1);
push(st,-2);
push(st,-3);
push(st,0);
push(st,5);
cout<<getMin(st)<<endl;
int del = pop(st);
del = pop(st);
del = pop(st);
cout<<getMin(st)<<endl;
} | [
"shailesh.techcourse@gmail.com"
] | shailesh.techcourse@gmail.com |
febcbb7907993abdb8d852b755ed87d3c4de2929 | 1bbd0f6117dfd88587353f36688620e304d3f92b | /FMI/FMI_v3-1_with_HOS_v2-1/FMI_v3-1_with_HOS_v2-1/Fleet-Management-Controller/src/CIftaDlg.h | c29c87a5fbbcc63f239a443ecb4169db0ce6ba3d | [] | no_license | Qasemt/teltonikaRes | 46f30740043b5753d3c5bf75f616bbab9d5f8ac7 | b9c74ad7309ac67bbcfa9061b4ff3cb899c3115c | refs/heads/master | 2016-08-12T14:40:23.990338 | 2015-05-24T08:09:06 | 2015-05-24T08:09:06 | 36,158,291 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | h | /*********************************************************************
*
* HEADER NAME:
* CIftaDlg.h
*
* Copyright 2013 by Garmin Ltd. or its subsidiaries.
*---------------------------------------------------------------------
* $NoKeywords$
*********************************************************************/
#pragma once
#include "FmiApplicationLayer.h"
#include "CWndEventListener.h"
#if( FMI_SUPPORT_A615 )
//----------------------------------------------------------------------
//! \brief Form for interacting with IFTA data on the device
//! \details Download IFTA data or delete IFTA for a specified timeframe
//----------------------------------------------------------------------
class CIftaDlg : public CDialog, public CWndEventListener
{
DECLARE_DYNAMIC(CIftaDlg)
public:
CIftaDlg(
CWnd* pParent,
FmiApplicationLayer & aCom
);
virtual ~CIftaDlg();
// Dialog Data
enum { IDD = IDD_IFTA };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
private:
//event handlers
afx_msg void OnBnClickedDataFetch();
afx_msg void OnBnClickedDataDelete();
afx_msg LRESULT OnEventIftaFileTransferReceived( WPARAM, LPARAM );
//control data members
COleDateTime mStartDate;
COleDateTime mStartTime;
COleDateTime mEndDate;
COleDateTime mEndTime;
//! Reference to the FMI communication controller
FmiApplicationLayer& mCom;
};
#endif
| [
"qasemt@gmail.com"
] | qasemt@gmail.com |
ed12c48e56d595e468e725e32a4cb1aaacbe3eea | 1151d4f8b636a36db18829f0fb03166a3c40b735 | /tools/cmd/propenv.cpp | 9c588ccf19e996b18f081cd88a95fbe2afd957dd | [
"LicenseRef-scancode-public-domain",
"LGPL-3.0-only",
"MIT"
] | permissive | Afonso-2403/universal | 9f695344649f363d4faeaf8df4d1d033c258a952 | bddd1489de6476ee60bd45e473b918b6c7a4bce6 | refs/heads/main | 2023-08-05T06:54:48.006615 | 2021-09-16T11:42:42 | 2021-09-16T11:42:42 | 382,342,543 | 0 | 0 | MIT | 2021-07-02T12:40:39 | 2021-07-02T12:40:38 | null | UTF-8 | C++ | false | false | 8,610 | cpp | // propenv.cpp: cli to show the type properties of the compiler environment
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <universal/utility/number_system_properties.hpp> //minmax_range etc. for native types
// configure the posit environment
#define POSIT_FAST_SPECIALIZATION 1
#include <universal/number/posit/posit.hpp>
//#define POSIT_DECODED_CLASS
#ifdef POSIT_DECODED_CLASS
#include "posit_decoded.hpp"
// the decoded posits structure is caching decoded regime, exponent, and fraction ballooning the size
// of the class and making it unusable for real computational work.
void WhyWeRemovedDecodedPosits() {
using namespace std;
using namespace sw::universal;
// report on the size of different posit components and implementations
posit<4, 0> p4_0;
posit_decoded<4, 0> pd4_0;
posit<8, 0> p8_0;
posit_decoded<8, 0> pd8_0;
posit<16, 1> p16_1;
posit_decoded<16, 1> pd16_1;
posit<32, 2> p32_2;
posit_decoded<32, 2> pd32_2;
posit<64, 3> p64_3;
posit_decoded<64, 3> pd64_3;
posit<128, 4> p128_4;
posit_decoded<128, 4> pd128_4;
cout << left << setw(20) << "configuration" << setw(10) << "bytes" << endl;
cout << left << setw(20) << "posit<4,0>" << setw(10) << sizeof(p4_0) << endl;
cout << left << setw(20) << "decoded<4,0>" << setw(10) << sizeof(pd4_0) << endl;
cout << left << setw(20) << "posit<8,0>" << setw(10) << sizeof(p8_0) << endl;
cout << left << setw(20) << "decoded<8,0>" << setw(10) << sizeof(pd8_0) << endl;
cout << left << setw(20) << "posit<16,1>" << setw(10) << sizeof(p16_1) << endl;
cout << left << setw(20) << "decoded<16,1>" << setw(10) << sizeof(pd16_1) << endl;
cout << left << setw(20) << "posit<32,2>" << setw(10) << sizeof(p32_2) << endl;
cout << left << setw(20) << "decoded<32,2>" << setw(10) << sizeof(pd32_2) << endl;
cout << left << setw(20) << "posit<64,3>" << setw(10) << sizeof(p64_3) << endl;
cout << left << setw(20) << "decoded<64,3>" << setw(10) << sizeof(pd64_3) << endl;
cout << left << setw(20) << "posit<128,4>" << setw(10) << sizeof(p128_4) << endl;
cout << left << setw(20) << "decoded<128,4>" << setw(10) << sizeof(pd128_4) << endl;
}
#endif
// Report on size and numeric limits details of different data types
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::universal;
// long double attributes
constexpr int f_prec = std::numeric_limits<float>::max_digits10;
//constexpr int d_prec = std::numeric_limits<double>::max_digits10;
constexpr int q_prec = std::numeric_limits<long double>::max_digits10;
constexpr int uint8_bits = std::numeric_limits<unsigned char>::digits;
constexpr int uint16_bits = std::numeric_limits<unsigned short>::digits;
constexpr int uint32_bits = std::numeric_limits<unsigned int>::digits;
constexpr int uint64_bits = std::numeric_limits<unsigned long long>::digits;
constexpr int int8_bits = std::numeric_limits<signed char>::digits;
constexpr int int16_bits = std::numeric_limits<short>::digits;
constexpr int int32_bits = std::numeric_limits<int>::digits;
constexpr int int64_bits = std::numeric_limits<long long>::digits;
constexpr int f_fbits = std::numeric_limits<float>::digits;
constexpr int d_fbits = std::numeric_limits<double>::digits;
constexpr int q_fbits = std::numeric_limits<long double>::digits;
cout << "Bit sizes for native types" << endl;
cout << "unsigned char " << setw(4) << uint8_bits << " bits" << endl;
cout << "unsigned short " << setw(4) << uint16_bits << " bits" << endl;
cout << "unsigned int " << setw(4) << uint32_bits << " bits" << endl;
cout << "unsigned long long " << setw(4) << uint64_bits << " bits" << endl;
cout << " signed char " << setw(4) << int8_bits << " bits" << endl;
cout << " signed short " << setw(4) << int16_bits << " bits" << endl;
cout << " signed int " << setw(4) << int32_bits << " bits" << endl;
cout << " signed long long " << setw(4) << int64_bits << " bits" << endl;
cout << " float " << setw(4) << f_fbits << " bits" << endl;
cout << " double " << setw(4) << d_fbits << " bits" << endl;
cout << " long double " << setw(4) << q_fbits << " bits" << endl;
cout << endl;
cout << "Min-Max range for floats and posit<32,2> comparison\n";
cout << minmax_range<float>() << endl;
cout << minmax_range<posit<32, 2>>() << endl;
cout << endl;
// report on the size of different posit components and implementations
posit<4, 0> p4_0;
posit<8, 0> p8_0;
posit<16, 1> p16_1;
posit<20, 1> p20_1;
posit<24, 1> p24_1;
posit<28, 1> p28_1;
posit<32, 2> p32_2;
posit<40, 2> p40_2;
posit<48, 2> p48_2;
posit<56, 2> p56_2;
posit<64, 3> p64_3;
posit<80, 3> p80_3;
posit<96, 3> p96_3;
posit<112, 3> p112_3;
posit<128, 4> p128_4;
posit<256, 5> p256_5;
constexpr int columnWidth = 21;
cout << "Bit sizes for standard posit configurations\n";
cout << left << setw(columnWidth) << "posit<8,0>" << setw(4) << right << sizeof(p8_0) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<16,1>" << setw(4) << right << sizeof(p16_1) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<32,2>" << setw(4) << right << sizeof(p32_2) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<64,3>" << setw(4) << right << sizeof(p64_3) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<128,4>" << setw(4) << right << sizeof(p128_4) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<256,5>" << setw(4) << right << sizeof(p256_5) * 8 << " bits" << endl;
cout << endl;
cout << endl;
cout << "Bit sizes for extended posit configurations\n";
cout << left << setw(columnWidth) << "posit<4,0>" << setw(4) << right << sizeof(p4_0) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<8,0>" << setw(4) << right << sizeof(p8_0) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<16,1>" << setw(4) << right << sizeof(p16_1) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<20,1>" << setw(4) << right << sizeof(p20_1) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<24,1>" << setw(4) << right << sizeof(p24_1) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<28,1>" << setw(4) << right << sizeof(p28_1) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<32,2>" << setw(4) << right << sizeof(p32_2) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<40,2>" << setw(4) << right << sizeof(p40_2) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<48,2>" << setw(4) << right << sizeof(p48_2) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<56,2>" << setw(4) << right << sizeof(p56_2) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<64,3>" << setw(4) << right << sizeof(p64_3) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<80,3>" << setw(4) << right << sizeof(p80_3) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<96,3>" << setw(4) << right << sizeof(p96_3) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<112,3>" << setw(4) << right << sizeof(p112_3) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<128,4>" << setw(4) << right << sizeof(p128_4) * 8 << " bits" << endl;
cout << left << setw(columnWidth) << "posit<256,5>" << setw(4) << right << sizeof(p256_5) * 8 << " bits" << endl;
cout << endl;
cout << "Long double properties" << endl;
union {
long double da;
char bytes[16];
} ld;
ld.da = 1.234567890123456789;
bool sign = false;
int scale = 0;
long double fr = 0;
unsigned long long fraction = 0;
sw::universal::extract_fp_components(ld.da, sign, scale, fr, fraction);
cout << "value " << setprecision(q_prec) << ld.da << setprecision(f_prec) << endl;
cout << "hex ";
cout << hex << setfill('0');
for (int i = 15; i >= 0; i--) {
cout << setw(2) << (int)(uint8_t)ld.bytes[i] << " ";
}
cout << dec << setfill(' ') << endl;
cout << "sign " << (sign ? "-" : "+") << endl;
cout << "scale " << scale << endl;
cout << "fraction " << fraction << endl;
cout << endl;
// WhyWeRemovedDecodedPosits();
return EXIT_SUCCESS;
}
catch (const char* const msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
| [
"theo@stillwater-sc.com"
] | theo@stillwater-sc.com |
8bb3ae49816e375c8f5b098a48de14732f05edf3 | d29a98d4cfc6c4fe8705e583bef48ec5f25a1e13 | /leetcode/min-stack.cc | e252dfc95fdb5d18357abba5726307adff4b3a80 | [
"MIT"
] | permissive | Waywrong/leetcode-solution | 0295a83ea748a6295a598f996f82397f4ee728db | 55115aeab4040f5ff84bdce6ffcfe4a98f879616 | refs/heads/master | 2020-04-03T08:34:38.190104 | 2018-11-20T12:40:19 | 2018-11-20T12:40:19 | 155,137,800 | 0 | 0 | MIT | 2018-11-20T12:40:21 | 2018-10-29T02:07:05 | C++ | UTF-8 | C++ | false | false | 864 | cc | // Min Stack
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
main_stack.push(x);
if (mini_stack.empty() || x <= mini_stack.top())
mini_stack.push(x);
}
void pop() {
int tmp = main_stack.top();
main_stack.pop();
if (tmp == mini_stack.top())
mini_stack.pop();
}
int top() {
int res = main_stack.top();
return res;
}
int getMin() {
int res = mini_stack.top();
return res;
}
private:
stack<int> main_stack;
stack<int> mini_stack;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/ | [
"jiangxq18@outlook.com"
] | jiangxq18@outlook.com |
1eb0c710e0ed62988996f7e2652370b39e286f41 | 78ce9a6f9e5680af7c3f35d60f1d1d8d347afaba | /problems/42/header.cpp | b7694a66d535556bc5a8150226b399e516c6edf5 | [] | no_license | hacktheinterview/hacktheinterview | 3f32f91b8b8fdaa127331d98327f8ea0ce051775 | 2bd76c4c6ec454f1c14f69058126999099c71e60 | refs/heads/master | 2021-01-12T16:36:15.101277 | 2016-06-08T05:05:22 | 2016-06-08T05:05:22 | 52,276,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#include <ctime>
#include <climits>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root);
};
| [
"radhakrishnancegit@gmail.com"
] | radhakrishnancegit@gmail.com |
f9d6b0650145f1095d95adc572401aaac1e47bf1 | f5acd38efe9f28e14a3e77cf60f938000a6660ab | /clients/cpp-restbed-server/generated/model/ResponseTimeMonitorData.cpp | 054634157a0e03404ee69ddc12e4829b1332e54f | [
"MIT"
] | permissive | rahulyhg/swaggy-jenkins | 3fc9377c8cf8643d6b4ffe4a6aceb49315afdb8e | 21326779f8814a07153acaf5af15ffbbd593c48b | refs/heads/master | 2020-05-04T16:14:43.369417 | 2019-01-27T06:27:32 | 2019-01-27T06:27:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,835 | cpp | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.0.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ResponseTimeMonitorData.h"
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
namespace org {
namespace openapitools {
namespace server {
namespace model {
ResponseTimeMonitorData::ResponseTimeMonitorData()
{
m__class = "";
m_Timestamp = 0;
m_Average = 0;
}
ResponseTimeMonitorData::~ResponseTimeMonitorData()
{
}
std::string ResponseTimeMonitorData::toJsonString()
{
std::stringstream ss;
ptree pt;
pt.put("_class", m__class);
pt.put("Timestamp", m_Timestamp);
pt.put("Average", m_Average);
write_json(ss, pt, false);
return ss.str();
}
void ResponseTimeMonitorData::fromJsonString(std::string const& jsonString)
{
std::stringstream ss(jsonString);
ptree pt;
read_json(ss,pt);
m__class = pt.get("_class", "");
m_Timestamp = pt.get("Timestamp", 0);
m_Average = pt.get("Average", 0);
}
std::string ResponseTimeMonitorData::getClass() const
{
return m__class;
}
void ResponseTimeMonitorData::setClass(std::string value)
{
m__class = value;
}
int32_t ResponseTimeMonitorData::getTimestamp() const
{
return m_Timestamp;
}
void ResponseTimeMonitorData::setTimestamp(int32_t value)
{
m_Timestamp = value;
}
int32_t ResponseTimeMonitorData::getAverage() const
{
return m_Average;
}
void ResponseTimeMonitorData::setAverage(int32_t value)
{
m_Average = value;
}
}
}
}
}
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
5ab886da2d9d156811cbf1e54b6f0f9e6a51d361 | 823d69017612c90d072a59801ef10b60472a0c79 | /src/test_partial_search.cpp | 5888806cd04ca0fc9dc5d6a32a2cb1fe4ee500b2 | [] | no_license | zhangzongliang/object_3d_retrieval | 864404d2c36ef75d6f4647c071b818be9bf8b1ac | 414694d00fdc529673f6d9db945e645b0cf15fe8 | refs/heads/master | 2021-01-15T13:33:01.163411 | 2015-06-16T08:29:23 | 2015-06-16T08:29:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83,220 | cpp | #include <iostream>
#include <chrono>
#include <pcl/kdtree/kdtree_flann.h>
#include "object_3d_retrieval/supervoxel_segmentation.h"
#include "object_3d_retrieval/object_retrieval.h"
#include "object_3d_retrieval/dataset_convenience.h"
#include "object_3d_retrieval/register_objects.h"
#include "object_3d_retrieval/segment_features.h"
#include "object_3d_retrieval/pfhrgb_estimation.h"
#include "sift/sift.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/utility.hpp>
using namespace std;
using namespace dataset_convenience;
//using sift_point = pcl::Histogram<128>;
//using sift_cloud = pcl::PointCloud<sift_point>;
POINT_CLOUD_REGISTER_POINT_STRUCT (pcl::Histogram<128>,
(float[128], histogram, histogram)
)
POINT_CLOUD_REGISTER_POINT_STRUCT (pcl::Histogram<256>,
(float[256], histogram, histogram)
)
POINT_CLOUD_REGISTER_POINT_STRUCT (pcl::Histogram<250>,
(float[250], histogram, histogram)
)
POINT_CLOUD_REGISTER_POINT_STRUCT (pcl::Histogram<1344>,
(float[1344], histogram, histogram)
)
using SiftT = pcl::Histogram<128>;
using SiftCloudT = pcl::PointCloud<SiftT>;
using DupletT = pcl::Histogram<256>;
using DupletCloudT = pcl::PointCloud<DupletT>;
using PfhRgbT = pcl::Histogram<250>;
using PfhRgbCloudT = pcl::PointCloud<PfhRgbT>;
//POINT_CLOUD_REGISTER_POINT_STRUCT (object_retrieval::HistT,
// (float[object_retrieval::N], histogram, histogram)
//)
template<typename Key, typename Value>
void inverse_map(map<Value, vector<Key> >& imap, const map<Key, Value>& omap)
{
for (const pair<const Key, Value>& v : omap) {
imap[v.second].push_back(v.first);
}
}
void calculate_sift_features(cv::Mat& descriptors, vector<cv::KeyPoint>& keypoints, CloudT::Ptr& cloud, cv::Mat& image,
cv::Mat& depth, int minx, int miny, const Eigen::Matrix3f& K)
{
cv::SIFT::DetectorParams detector_params;
detector_params.edgeThreshold = 15.0; // 10.0 default
detector_params.threshold = 0.04; // 0.04 default
cv::SiftFeatureDetector detector(detector_params);
detector.detect(image, keypoints);
//-- Step 2: Calculate descriptors (feature vectors)
//cv::Mat descriptors;
// the length of the descriptors is 128
// the 3D sift keypoint detectors are probably very unreliable
cv::SIFT::DescriptorParams descriptor_params;
descriptor_params.isNormalize = true; // always true, shouldn't matter
descriptor_params.magnification = 3.0; // 3.0 default
descriptor_params.recalculateAngles = true; // true default
cv::SiftDescriptorExtractor extractor;
extractor.compute(image, keypoints, descriptors);
// get back to 3d coordinates
for (cv::KeyPoint k : keypoints) {
cv::Point2f p2 = k.pt;
Eigen::Vector3f p3;
p3(0) = p2.x + float(minx);
p3(1) = p2.y + float(miny);
p3(2) = 1.0f;
p3 = K.colPivHouseholderQr().solve(p3);
p3 *= depth.at<float>(int(p2.y), int(p2.x))/p3(2);
PointT p;
p.getVector3fMap() = p3;
cloud->push_back(p);
}
cv::Mat img_keypoints;
cv::drawKeypoints(image, keypoints, img_keypoints, cv::Scalar::all(-1), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
cv::imshow("my keypoints", img_keypoints);
cv::waitKey(0);
}
void shot_features_for_segment(HistCloudT::Ptr& desc_cloud, CloudT::Ptr& cloud, Eigen::Matrix3f& K, int points=0)
{
segment_features sf(K, false);
sf.compute_shot_features(desc_cloud, cloud, points != 0, points);
}
void save_supervoxel_features(object_retrieval& obr)
{
using Graph = supervoxel_segmentation::Graph;
string base_path = boost::filesystem::path(obr.segment_path).parent_path().string();
string segment_path = base_path + "/supervoxel_segments";
boost::filesystem::create_directory(segment_path);
Eigen::Matrix3f K; // dummy
bool found = false;
int counter = 0;
for (int i = 0; ; ++i) {
string folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(folder)) {
return;
}
CloudT::Ptr cloud(new CloudT);
string scan_file = obr.get_scan_file(i);
if (!found) {
if (scan_file != "/home/nbore/Data/Instances//muesli_1/patrol_run_5/room_1/intermediate_cloud0010.pcd") {
++counter;
continue;
}
else {
found = true;
counter = 28114;
}
}
cout << "Finally got scan " << scan_file << endl;
obr.read_scan(cloud, i);
//obr.visualize_cloud(cloud);
string graph_file = folder + "/graph.cereal";
supervoxel_segmentation ss;
vector<CloudT::Ptr> supervoxels;
//ss.create_supervoxel_graph(supervoxels, cloud);
Graph* g = ss.compute_convex_oversegmentation(supervoxels, cloud);
ss.save_graph(*g, graph_file);
delete g;
vector<string> segment_folders;
int j = 0;
for (CloudT::Ptr& sv : supervoxels) {
cout << "Segment size: " << sv->size() << endl;
HistCloudT::Ptr desc_cloud(new HistCloudT);
shot_features_for_segment(desc_cloud, sv, K);
if (desc_cloud->empty()) {
++j;
continue;
}
string segment_folder = segment_path + "/segment" + to_string(counter);
boost::filesystem::create_directory(segment_folder);
segment_folders.push_back(segment_folder);
// save features, maybe also save the segment itself? yes
string features_file = segment_folder + "/features.pcd";
pcl::io::savePCDFileBinary(features_file, *desc_cloud);
string cloud_file = segment_folder + "/segment.pcd";
pcl::io::savePCDFileBinary(cloud_file, *sv);
string metadata_file = segment_folder + "/metadata.txt";
{
ofstream f;
f.open(metadata_file);
f << folder << "\n";
f << scan_file << "\n";
f << "Vertex nbr: " << j << "\n";
f.close();
}
++counter;
++j;
}
string segment_folders_file = folder + "/segment_paths.txt";
{
ofstream f;
f.open(segment_folders_file);
for (string& sf : segment_folders) {
f << sf << "\n";
}
f.close();
}
}
}
void cloud_for_scan(CloudT::Ptr& cloud, int i, object_retrieval& obr)
{
string folder = obr.get_folder_for_segment_id(i);
string metadata_file = folder + "/metadata.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(metadata_file);
getline(f, metadata);
f.close();
}
if (pcl::io::loadPCDFile(metadata, *cloud) == -1) {
cout << "Could not load scan point cloud..." << endl;
exit(-1);
}
}
void compute_feature_duplets(DupletCloudT::Ptr& duplets, SiftCloudT::Ptr& desc_cloud, CloudT::Ptr& kp_cloud)
{
float radius = 0.1;
float plus_minus = 0.01;
set<pair<int, int> > used;
auto flip_pair = [](int i, int j) -> pair<int, int> {
if (i > j) {
return make_pair(i, j);
}
else {
return make_pair(j, i);
}
};
pcl::KdTreeFLANN<PointT> kdtree;
kdtree.setInputCloud(kp_cloud);
size_t counter = 0;
size_t nbr_not_finite = 0;
for (PointT& p : kp_cloud->points) {
// find all points close to a certain radius
if (!pcl::isFinite(p)) {
++counter;
++nbr_not_finite;
continue;
}
vector<int> inds;
vector<float> dists;
//int max_nbr = 100;
kdtree.radiusSearch(p, radius+plus_minus, inds, dists);
size_t _inds_size = inds.size();
for (size_t i = 0; i < _inds_size; ++i) {
if (sqrt(dists[i]) < radius-plus_minus) {
continue;
}
if (used.count(flip_pair(counter, inds[i])) == 1) {
continue;
}
DupletT duplet;
for (size_t j = 0; j < 128; ++j) {
duplet.histogram[j] = desc_cloud->at(counter).histogram[j];
duplet.histogram[128+j] = desc_cloud->at(inds[i]).histogram[j];
}
duplets->push_back(duplet);
used.insert(flip_pair(counter, inds[i]));
}
++counter;
}
cout << "Number not finite: " << nbr_not_finite << endl;
}
void save_duplet_features(object_retrieval& obr)
{
for (int i = 0; ; ++i) {
string folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(folder)) {
cout << folder << " is not a directory!" << endl;
break;
}
SiftCloudT::Ptr features(new SiftCloudT);
//obr.load_features_for_segment(features, i);
DupletCloudT::Ptr duplet_cloud(new DupletCloudT);
CloudT::Ptr kp_cloud(new CloudT);
string sift_points_file = folder + "/sift_points_file.pcd";
if (pcl::io::loadPCDFile(sift_points_file, *kp_cloud) == -1) {
cout << "Could not load keypoint cloud" << endl;
exit(0);
}
compute_feature_duplets(duplet_cloud, features, kp_cloud);
cout << "Features size: " << features->size() << endl;
cout << "Keypoints size: " << kp_cloud->size() << endl;
cout << "Duplets size: " << duplet_cloud->size() << endl;
string duplet_points_file = folder + "/duplet_points_file.pcd";
pcl::io::savePCDFileBinary(duplet_points_file, *duplet_cloud);
}
}
void save_sift_features(object_retrieval& obr)
{
for (int i = 0; ; ++i) {
string folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(folder)) {
cout << folder << " is not a directory!" << endl;
break;
}
CloudT::Ptr cloud(new CloudT);
obr.read_scan(cloud, i);
cv::Mat img(480, 640, CV_8UC3);
for (int y = 0; y < 480; ++y) {
for (int x = 0; x < 640; ++x) {
int ind = y*640+x;
cv::Vec3b& c = img.at<cv::Vec3b>(y, x);
c[2] = cloud->at(ind).r;
c[1] = cloud->at(ind).g;
c[0] = cloud->at(ind).b;
}
}
cv::FastFeatureDetector detector;
std::vector<cv::KeyPoint> keypoints;
detector.detect(img, keypoints);
cv::SIFT::DescriptorParams descriptor_params;
descriptor_params.isNormalize = true; // always true, shouldn't matter
descriptor_params.magnification = 3.0; // 3.0 default
descriptor_params.recalculateAngles = true; // true default
cv::SiftDescriptorExtractor extractor;
cv::Mat descriptors;
extractor.compute(img, keypoints, descriptors);
CloudT::Ptr kp_cloud(new CloudT);
HistCloudT::Ptr desc_cloud(new HistCloudT);
int j = 0;
for (cv::KeyPoint k : keypoints) {
cv::Point2f p2 = k.pt;
int ind = p2.y*640+p2.x;
PointT p = cloud->at(ind);
if (pcl::isFinite(p)) {
kp_cloud->push_back(p);
HistT sp;
for (int k = 0; k < 128; ++k) {
sp.histogram[k] = descriptors.at<float>(j, k);
}
desc_cloud->push_back(sp);
}
++j;
}
string sift_file = folder + "/sift_cloud.pcd";
string sift_points_file = folder + "/sift_points_file.pcd";
pcl::io::savePCDFileBinary(sift_file, *desc_cloud);
pcl::io::savePCDFileBinary(sift_points_file, *kp_cloud);
}
}
void sift_features_for_segment(SiftCloudT::Ptr& desc_cloud, CloudT::Ptr& kp_cloud, CloudT::Ptr& cloud, Eigen::Matrix3f& K)
{
int minx, miny;
cv::Mat img, depth;
register_objects ro;
tie(minx, miny) = ro.calculate_image_for_cloud(img, depth, cloud, K);
cv::Mat descriptors;
std::vector<cv::KeyPoint> keypoints;
calculate_sift_features(descriptors, keypoints, kp_cloud, img, depth, minx, miny, K);//ro.calculate_features_for_image(descriptors, keypoints, kp_cloud, img, depth, minx, miny, K);
int j = 0;
for (cv::KeyPoint& k : keypoints) {
// we need to check if the points are finite
SiftT sp;
for (int k = 0; k < 128; ++k) {
sp.histogram[k] = descriptors.at<float>(j, k);
}
desc_cloud->push_back(sp);
++j;
}
}
bool scan_contains_segment(int i, int segment, object_retrieval& obr)
{
string folder = obr.get_folder_for_segment_id(i);
string metadata_file = folder + "/metadata.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(metadata_file);
getline(f, metadata);
getline(f, metadata);
f.close();
}
stringstream ss(metadata);
vector<int> numbers((istream_iterator<int>(ss)), istream_iterator<int>());
return (find(numbers.begin(), numbers.end(), segment) != numbers.end());
}
pair<bool, bool> supervoxel_is_correct(CloudT::Ptr& cloud, const Eigen::Matrix3f& K, int minx, int maxx, int miny, int maxy)
{
cv::Mat cover = cv::Mat::zeros(maxy - miny + 1, maxx - minx + 1, CV_32SC1);
size_t counter = 0;
for (PointT& p : cloud->points) {
Eigen::Vector3f q = K*p.getVector3fMap();
int x = int(q(0)/q(2) + 0.5f);
int y = int(q(1)/q(2) + 0.5f);
if (x >= minx && x <= maxx && y >= miny && y <= maxy) {
cover.at<int>(y - miny, x - minx) = 1;
++counter;
}
}
int allpixels = cv::sum(cover)[0];
float segment_cover = float(allpixels)/float((maxx-minx)*(maxy-miny));
float annotation_cover = float(counter)/float(cloud->size());
return make_pair(annotation_cover > 0.75, segment_cover > 0.5);
}
struct voxel_annotation {
int segment_id;
string segment_file;
string scan_folder;
int scan_id;
string annotation;
bool full;
bool segment_covered;
bool annotation_covered;
template <typename Archive>
void serialize(Archive& archive)
{
archive(segment_id, segment_file, scan_folder, scan_id, annotation, full, segment_covered, annotation_covered);
}
};
int scan_ind_for_supervoxel(int i, object_retrieval& obr)
{
string segment_folder = obr.get_folder_for_segment_id(i);
string metadata_file = segment_folder + "/metadata.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(metadata_file);
getline(f, metadata);
f.close();
}
string scan_name = boost::filesystem::path(metadata).parent_path().stem().string();
size_t pos = scan_name.find_last_not_of("0123456789");
int ind = stoi(scan_name.substr(pos+1));
return ind;
}
// scan folder, scan number, annotation, covered
voxel_annotation scan_for_supervoxel(int i, const Eigen::Matrix3f& K, object_retrieval& obr)
{
string segment_folder = obr.get_folder_for_segment_id(i);
string metadata_file = segment_folder + "/metadata.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(metadata_file);
getline(f, metadata);
getline(f, metadata);
f.close();
}
string scan_folder = boost::filesystem::path(metadata).parent_path().string();
string scan_name = boost::filesystem::path(metadata).stem().string();
size_t pos = scan_name.find_last_not_of("0123456789");
int ind = stoi(scan_name.substr(pos+1));
string annotation_file = scan_folder + "/annotation" + to_string(ind) + ".txt";
string annotation; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(annotation_file);
getline(f, annotation);
f.close();
}
bool annotation_covered = false;
bool segment_covered = false;
bool full = false;
string cloud_file = segment_folder + "/segment.pcd";
if (annotation != "null") {
vector<string> strs;
boost::split(strs, annotation, boost::is_any_of(" \t\n"));
annotation = strs[0];
full = (strs[1] == "full");
int minx = stoi(strs[2]);
int maxx = stoi(strs[3]);
int miny = stoi(strs[4]);
int maxy = stoi(strs[5]);
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(cloud_file, *cloud);
tie(segment_covered, annotation_covered) = supervoxel_is_correct(cloud, K, minx, maxx, miny, maxy);
}
return voxel_annotation { i, cloud_file, scan_folder, ind, annotation, full, segment_covered, annotation_covered };
}
string annotation_for_supervoxel(int i, object_retrieval& obr)
{
string segment_folder = obr.get_folder_for_segment_id(i);
string metadata_file = segment_folder + "/metadata.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(metadata_file);
getline(f, metadata);
getline(f, metadata);
f.close();
}
string scan_folder = boost::filesystem::path(metadata).parent_path().string();
string scan_name = boost::filesystem::path(metadata).stem().string();
size_t pos = scan_name.find_last_not_of("0123456789");
int ind = stoi(scan_name.substr(pos+1));
string annotation_file = scan_folder + "/annotation" + to_string(ind) + ".txt";
string annotation; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(annotation_file);
getline(f, annotation);
f.close();
}
if (annotation != "null") {
vector<string> strs;
boost::split(strs, annotation, boost::is_any_of(" \t\n"));
annotation = strs[0];
}
return annotation;
}
void list_annotated_supervoxels(vector<voxel_annotation>& annotations, const string& annotations_file,
const Eigen::Matrix3f& K, object_retrieval& obr)
{
if (boost::filesystem::is_regular_file(annotations_file)) {
ifstream in(annotations_file, std::ios::binary);
cereal::BinaryInputArchive archive_i(in);
archive_i(annotations);
return;
}
for (int i = 0; ; ++i) {
string segment_folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(segment_folder)) {
break;
}
voxel_annotation annotation = scan_for_supervoxel(i, K, obr);
annotations.push_back(annotation);
}
{
ofstream out(annotations_file, std::ios::binary);
cereal::BinaryOutputArchive archive_o(out);
archive_o(annotations);
}
}
void visualize_supervoxel_annotation(vector<voxel_annotation>& annotations, object_retrieval& obr)
{
for (voxel_annotation& a : annotations) {
if (!a.annotation_covered || !a.segment_covered) {
continue;
}
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
cout << "Showing " << a.segment_file << " with annotation " << a.annotation << endl;
obr.visualize_cloud(cloud);
}
}
void save_sift_features_for_supervoxels(Eigen::Matrix3f& K, object_retrieval& obr)
{
for (int i = 0; ; ++i) {
string segment_folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(segment_folder)) {
break;
}
string cloud_file = segment_folder + "/segment.pcd";
CloudT::Ptr cloud(new CloudT);
if (pcl::io::loadPCDFile(cloud_file, *cloud) == -1) {
cout << "Could not load " << cloud_file << endl;
exit(0);
}
SiftCloudT::Ptr desc_cloud(new SiftCloudT);
CloudT::Ptr kp_cloud(new CloudT);
sift_features_for_segment(desc_cloud, kp_cloud, cloud, K);
string sift_file = segment_folder + "/sift_cloud.pcd";
string sift_points_file = segment_folder + "/sift_points_file.pcd";
if (desc_cloud->empty()) {
// push back one inf point on descriptors and keypoints
SiftT sp;
for (int i = 0; i < 128; ++i) {
sp.histogram[i] = std::numeric_limits<float>::infinity();
}
desc_cloud->push_back(sp);
PointT p;
p.x = p.y = p.z = std::numeric_limits<float>::infinity();
kp_cloud->push_back(p);
}
pcl::io::savePCDFileBinary(sift_file, *desc_cloud);
pcl::io::savePCDFileBinary(sift_points_file, *kp_cloud);
}
}
void save_pfhrgb_features_for_supervoxels(object_retrieval& obr)
{
for (int i = 0; ; ++i) {
string segment_folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(segment_folder)) {
break;
}
string cloud_file = segment_folder + "/segment.pcd";
CloudT::Ptr cloud(new CloudT);
if (pcl::io::loadPCDFile(cloud_file, *cloud) == -1) {
cout << "Could not load " << cloud_file << endl;
exit(0);
}
PfhRgbCloudT::Ptr desc_cloud(new PfhRgbCloudT);
CloudT::Ptr kp_cloud(new CloudT);
pfhrgb_estimation::compute_pfhrgb_features(desc_cloud, kp_cloud, cloud, false);
string pfhrgb_file = segment_folder + "/pfhrgb_cloud_2.pcd";
string pfhrgb_points_file = segment_folder + "/pfhrgb_points_file_2.pcd";
if (desc_cloud->empty()) {
// push back one inf point on descriptors and keypoints
PfhRgbT sp;
for (int i = 0; i < 250; ++i) {
sp.histogram[i] = std::numeric_limits<float>::infinity();
}
desc_cloud->push_back(sp);
PointT p;
p.x = p.y = p.z = std::numeric_limits<float>::infinity();
kp_cloud->push_back(p);
}
pcl::io::savePCDFileBinary(pfhrgb_file, *desc_cloud);
pcl::io::savePCDFileBinary(pfhrgb_points_file, *kp_cloud);
}
}
void save_split_features(object_retrieval& obr)
{
for (int i = 0; ; ++i) {
string segment_folder = obr.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(segment_folder)) {
break;
}
// we should add a keypoints argument to object_retrieval
string pfhrgb_file = segment_folder + "/pfhrgb_cloud.pcd";
string pfhrgb_points_file = segment_folder + "/pfhrgb_points_file.pcd";
PfhRgbCloudT::Ptr desc_cloud(new PfhRgbCloudT);
CloudT::Ptr kp_cloud(new CloudT);
if (pcl::io::loadPCDFile(pfhrgb_file, *desc_cloud) == -1) {
cout << "Could not load " << pfhrgb_file << endl;
exit(0);
}
if (pcl::io::loadPCDFile(pfhrgb_points_file, *kp_cloud) == -1) {
cout << "Could not load " << pfhrgb_points_file << endl;
exit(0);
}
vector<PfhRgbCloudT::Ptr> split_features;
vector<CloudT::Ptr> split_keypoints;
pfhrgb_estimation::split_descriptor_points(split_features, split_keypoints, desc_cloud, kp_cloud, 30);
int counter = 0;
for (PfhRgbCloudT::Ptr& split_cloud : split_features) {
if (split_cloud->empty()) {
continue;
}
if (desc_cloud->size() >= 20 && split_cloud->size() < 20) {
cout << "Doing cloud: " << pfhrgb_file << endl;
cout << "Split cloud had size: " << split_cloud->size() << endl;
exit(0);
}
string split_file = segment_folder + "/split_features" + to_string(counter) + ".pcd";
pcl::io::savePCDFile(split_file, *split_cloud);
++counter;
}
}
}
void get_voxels_for_scan(vector<int>& voxels, int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string segment_paths_file = scan_path + "/segment_paths.txt";
string metadata; // in this dataset, this is the path to the scan
{
ifstream f;
f.open(segment_paths_file);
while (getline(f, metadata)) {
size_t pos = metadata.find_last_not_of("0123456789");
int ind = stoi(metadata.substr(pos+1));
voxels.push_back(ind);
}
f.close();
}
}
void get_just_oversegmented_voxels_for_scan(vector<HistCloudT::Ptr>& voxels, int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string segment_paths_file = scan_path + "/segment_paths.txt";
vector<string> voxel_paths;
{
ifstream f;
string metadata;
f.open(segment_paths_file);
while (getline(f, metadata)) {
voxel_paths.push_back(metadata);
}
}
for (const string& voxel_path : voxel_paths) {
for (int i = 0; ; ++i) {
string oversegment_path = voxel_path + "/split_features" + to_string(i) + ".pcd";
if (!boost::filesystem::is_regular_file(oversegment_path)) {
break;
}
voxels.push_back(HistCloudT::Ptr(new HistCloudT));
if (pcl::io::loadPCDFile(oversegment_path, *voxels.back()) == -1) {
cout << "Could not read oversegment file " << oversegment_path << endl;
exit(0);
}
}
}
}
void get_oversegmented_voxels_for_scan(vector<HistCloudT::Ptr>& voxels, CloudT::Ptr& voxel_centers,
vector<double>& vocabulary_norms, int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string segment_paths_file = scan_path + "/segment_paths.txt";
vector<string> voxel_paths;
{
ifstream f;
string metadata;
f.open(segment_paths_file);
while (getline(f, metadata)) {
voxel_paths.push_back(metadata);
}
}
for (const string& voxel_path : voxel_paths) {
for (int i = 0; ; ++i) {
string oversegment_path = voxel_path + "/split_features" + to_string(i) + ".pcd";
if (!boost::filesystem::is_regular_file(oversegment_path)) {
break;
}
voxels.push_back(HistCloudT::Ptr(new HistCloudT));
if (pcl::io::loadPCDFile(oversegment_path, *voxels.back()) == -1) {
cout << "Could not read oversegment file " << oversegment_path << endl;
exit(0);
}
string center_path = voxel_path + "/split_center" + to_string(i) + ".pcd";
CloudT split_cloud;
if (pcl::io::loadPCDFile(center_path, split_cloud) == -1) {
cout << "Could not read center file " << center_path << endl;
exit(0);
}
if (split_cloud.size() != 1) {
cout << "Cloud did not have size 1: " << center_path << endl;
exit(0);
}
voxel_centers->push_back(split_cloud.at(0));
}
}
string norms_file = scan_path + "/vocabulary_norms.cereal";
ifstream in(norms_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(in);
archive_i(vocabulary_norms);
}
}
void get_oversegmented_vectors_for_scan(CloudT::Ptr& voxel_centers, vector<double>& vocabulary_norms,
vector<map<int, double> >& vocabulary_vectors, int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string centers_file = scan_path + "/split_centers.pcd";
if (pcl::io::loadPCDFile(centers_file, *voxel_centers) == -1) {
cout << "Could not read file " << centers_file << endl;
exit(0);
}
string norms_file = scan_path + "/vocabulary_norms.cereal";
ifstream inn(norms_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(inn);
archive_i(vocabulary_norms);
}
string vectors_file = scan_path + "/vocabulary_vectors.cereal";
ifstream inv(vectors_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(inv);
archive_i(vocabulary_vectors);
}
}
void get_grouped_oversegmented_vectors_for_scan(CloudT::Ptr& voxel_centers, vector<double>& vocabulary_norms,
vector<map<int, double> >& vocabulary_vectors, int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string centers_file = scan_path + "/split_centers.pcd";
if (pcl::io::loadPCDFile(centers_file, *voxel_centers) == -1) {
cout << "Could not read file " << centers_file << endl;
exit(0);
}
string norms_file = scan_path + "/grouped_vocabulary_norms.cereal";
ifstream inn(norms_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(inn);
archive_i(vocabulary_norms);
}
string vectors_file = scan_path + "/grouped_vocabulary_vectors.cereal";
ifstream inv(vectors_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(inv);
archive_i(vocabulary_vectors);
}
}
void save_oversegmented_vocabulary_vectors(object_retrieval& obr_scans)
{
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
vector<HistCloudT::Ptr> voxels;
CloudT::Ptr voxel_centers(new CloudT);
//get_oversegmented_voxels_for_scan(voxels, voxel_centers, i, obr_scans);
vector<double> vocabulary_norms;
for (HistCloudT::Ptr& voxel : voxels) {
double pnorm = obr_scans.rvt.compute_vocabulary_norm(voxel);
vocabulary_norms.push_back(pnorm);
}
string norms_file = path + "/vocabulary_norms.cereal";
ofstream out(norms_file, std::ios::binary);
{
cereal::BinaryOutputArchive archive_o(out);
archive_o(vocabulary_norms);
}
}
}
void save_supervoxel_centers_for_scan(int i, object_retrieval& obr_scans)
{
string scan_path = obr_scans.get_folder_for_segment_id(i);
string segment_paths_file = scan_path + "/segment_paths.txt";
vector<string> voxel_paths;
{
ifstream f;
string metadata;
f.open(segment_paths_file);
while (getline(f, metadata)) {
voxel_paths.push_back(metadata);
}
}
for (const string& voxel_path : voxel_paths) {
for (int i = 0; ; ++i) {
string oversegment_path = voxel_path + "/split_points" + to_string(i) + ".pcd";
if (!boost::filesystem::is_regular_file(oversegment_path)) {
break;
}
CloudT::Ptr cloud(new CloudT);
if (pcl::io::loadPCDFile(oversegment_path, *cloud) == -1) {
cout << "Could not read oversegment file " << oversegment_path << endl;
exit(0);
}
Eigen::Vector3f center;
bool finite = false;
int counter = 0;
for (PointT& p : cloud->points) {
if (!pcl::isFinite(p)) {
continue;
}
finite = true;
center += eig(p);
++counter;
}
if (counter > 0) {
center *= 1.0f/float(counter);
}
CloudT::Ptr center_cloud(new CloudT);
PointT p;
if (!finite) {
p.x = std::numeric_limits<float>::infinity();
p.y = std::numeric_limits<float>::infinity();
p.z = std::numeric_limits<float>::infinity();
}
else {
p.x = center(0);
p.y = center(1);
p.z = center(2);
}
center_cloud->push_back(p);
string center_path = voxel_path + "/split_center" + to_string(i) + ".pcd";
pcl::io::savePCDFileBinary(center_path, *center_cloud);
}
}
}
void save_supervoxel_centers(object_retrieval& obr_scans)
{
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
save_supervoxel_centers_for_scan(i, obr_scans);
}
}
void convert_voxels_to_binary(object_retrieval& obr_scans)
{
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
vector<HistCloudT::Ptr> dummy;
CloudT::Ptr dummy_centers(new CloudT);
vector<double> dummy_norms;
get_oversegmented_voxels_for_scan(dummy, dummy_centers, dummy_norms, i, obr_scans);
}
}
void save_oversegmented_voxels_for_scan(int i, object_retrieval& obr_scans)
{
vector<HistCloudT::Ptr> voxels;
string scan_path = obr_scans.get_folder_for_segment_id(i);
string segment_paths_file = scan_path + "/segment_paths.txt";
vector<string> voxel_paths;
{
ifstream f;
string metadata;
f.open(segment_paths_file);
while (getline(f, metadata)) {
voxel_paths.push_back(metadata);
}
}
for (const string& voxel_path : voxel_paths) {
string features_path = voxel_path + "/pfhrgb_cloud.pcd";
HistCloudT::Ptr features(new HistCloudT);
if (pcl::io::loadPCDFile(features_path, *features) == -1) {
cout << "Could not read features file " << features_path << endl;
exit(0);
}
string point_path = voxel_path + "/pfhrgb_points_file.pcd";
CloudT::Ptr points(new CloudT);
if (pcl::io::loadPCDFile(point_path, *points) == -1) {
cout << "Could not read points file " << point_path << endl;
exit(0);
}
for (int i = 0; ; ++i) {
string oversegment_path = voxel_path + "/split_features" + to_string(i) + ".pcd";
if (!boost::filesystem::is_regular_file(oversegment_path)) {
break;
}
voxels.push_back(HistCloudT::Ptr(new HistCloudT));
if (pcl::io::loadPCDFile(oversegment_path, *voxels.back()) == -1) {
cout << "Could not read oversegment file " << oversegment_path << endl;
exit(0);
}
string oversegments_points_path = voxel_path + "/split_points" + to_string(i) + ".pcd";
CloudT::Ptr split_points(new CloudT);
for (HistT& h : voxels.back()->points) {
// find h in features
bool found = false;
for (int j = 0; j < features->size(); ++j) {
if ((eig(h).isApprox(eig(features->at(j)), 1e-30))) {
split_points->push_back(points->at(j));
/*cout << "Found matching points:" << endl;
cout << eig(h).transpose() << endl;
cout << eig(features->at(j)).transpose() << endl;*/
found = true;
break;
}
}
if (features->size() > 0 && !found) {
cout << "Could not find point in global cloud " << features_path << endl;
cout << "Global cloud size: " << features->size() << endl;
cout << eig(h).transpose() << endl;
//exit(0);
PointT p;
p.x = std::numeric_limits<float>::infinity();
p.y = std::numeric_limits<float>::infinity();
p.z = std::numeric_limits<float>::infinity();
split_points->push_back(p);
}
}
pcl::io::savePCDFileBinary(oversegments_points_path, *split_points);
}
}
}
void save_oversegmented_points(object_retrieval& obr_scans)
{
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
save_oversegmented_voxels_for_scan(i, obr_scans);
}
}
vector<index_score> top_combined_similarities(map<int, double>& larger_map, map<int, double>& smaller_map, int nbr_query, float& ratio, int nbr_features);
void query_supervoxel_annotations(vector<voxel_annotation>& annotations, object_retrieval& obr)
{
const int nbr_query = 11;
/*if (obr.gvt.empty()) {
obr.read_vocabulary(obr.gvt);
}
obr.gvt.set_min_match_depth(3);
obr.gvt.compute_normalizing_constants();*/
if (obr.vt.empty()) {
obr.read_vocabulary(obr.vt);
}
obr.vt.set_min_match_depth(3);
obr.vt.compute_normalizing_constants();
map<string, int> nbr_full_instances;
map<string, pair<float, int> > instance_correct_ratios;
for (voxel_annotation& a : annotations) {
if (a.full) {
nbr_full_instances[a.annotation] += 1;
}
if (!a.full || !a.annotation_covered || !a.segment_covered) {
continue;
}
if (a.annotation != "ajax_1" && a.annotation != "ajax_2" && a.annotation != "ball_1") {
//continue;
}
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
HistCloudT::Ptr features(new HistCloudT);
obr.load_features_for_segment(features, a.segment_id);
vector<index_score> larger_scores;
//obr.gvt.top_grouped_similarities(scores, features, nbr_query);
obr.vt.top_larger_similarities(larger_scores, features, 0);
vector<index_score> smaller_scores;
obr.vt.top_smaller_similarities(smaller_scores, features, 0);
map<int, double> larger_map((larger_scores.begin()), larger_scores.end());
map<int, double> smaller_map((smaller_scores.begin()), smaller_scores.end());
float max_ratio;
vector<index_score> scores = top_combined_similarities(larger_map, smaller_map, nbr_query, max_ratio, features->size());
bool found = false;
int counter = 0;
int partial_counter = 0;
bool last_match;
for (index_score s : scores) {
//CloudT::Ptr segment(new CloudT);
//obr.read_scan(segment, s.first);
//obr.visualize_cloud(segment);
string instance = annotation_for_supervoxel(s.first, obr);
if (s.first == a.segment_id) {
found = true;
continue;
}
last_match = false;
if (instance == a.annotation) {
++counter;
last_match = true;
if (!a.full) {
++partial_counter;
}
cout << "This was true." << endl;
}
else {
cout << "This was false." << endl;
}
HistCloudT::Ptr features_match(new HistCloudT);
obr.load_features_for_segment(features_match, s.first);
cout << "Score: " << s.second << endl;
cout << "Number of features: " << features_match->size() << endl;
}
if (!found) {
if (last_match) {
--counter;
}
}
float correct_ratio = float(counter)/float(scores.size()-1);
instance_correct_ratios[a.annotation].first += correct_ratio;
instance_correct_ratios[a.annotation].second += 1;
cout << "Showing " << a.segment_file << " with annotation " << a.annotation << endl;
cout << "Number of features: " << features->size() << endl;
cout << "Correct ratio: " << correct_ratio << endl;
cout << "Partial ratio: " << float(partial_counter)/float(counter) << endl;
//obr.visualize_cloud(cloud);
}
for (pair<const string, pair<float, int> > c : instance_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
}
}
void calculate_correct_ratio(map<string, pair<float, int> >& instance_correct_ratios, voxel_annotation& a,
int scan_ind, vector<index_score>& scores, object_retrieval& obr_scans, const bool verbose = true)
{
bool found = false;
int counter = 0;
int partial_counter = 0;
bool last_match;
for (index_score s : scores) {
string instance = annotation_for_scan(s.first, obr_scans);
if (s.first == scan_ind) {
found = true;
continue;
}
last_match = false;
if (instance == a.annotation) {
++counter;
last_match = true;
if (!a.full) {
++partial_counter;
}
if (verbose) cout << "This was true." << endl;
}
else {
if (verbose) cout << "This was false." << endl;
}
HistCloudT::Ptr features_match(new HistCloudT);
obr_scans.load_features_for_segment(features_match, s.first);
if (verbose) {
cout << "Score: " << s.second << endl;
cout << "Number of features: " << features_match->size() << endl;
}
}
if (!found) {
if (last_match) {
--counter;
}
}
float correct_ratio = float(counter)/float(scores.size()-1);
instance_correct_ratios[a.annotation].first += correct_ratio;
instance_correct_ratios[a.annotation].second += 1;
if (verbose) {
cout << "Showing " << a.segment_file << " with annotation " << a.annotation << endl;
cout << "Correct ratio: " << correct_ratio << endl;
cout << "Partial ratio: " << float(partial_counter)/float(counter) << endl;
}
}
void query_supervoxel_annotations_scans(vector<voxel_annotation>& annotations, Eigen::Matrix3f& K,
object_retrieval& obr, object_retrieval& obr_scans)
{
const int nbr_query = 11;
if (obr_scans.rvt.empty()) {
obr_scans.read_vocabulary(obr_scans.rvt);
}
obr_scans.rvt.set_min_match_depth(3);
obr_scans.rvt.compute_normalizing_constants();
map<string, int> nbr_full_instances;
map<string, pair<float, int> > instance_correct_ratios;
map<string, pair<float, int> > reweight_correct_ratios;
map<string, pair<int, int> > instance_mean_features;
map<string, int> instance_number_queries;
for (voxel_annotation& a : annotations) {
if (a.full) {
nbr_full_instances[a.annotation] += 1;
}
if (!a.full || !a.annotation_covered || !a.segment_covered) {
continue;
}
if (a.annotation != "ajax_1" && a.annotation != "ajax_2" && a.annotation != "ball_1") {
//continue;
}
instance_number_queries[a.annotation] += 1;
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
HistCloudT::Ptr features(new HistCloudT);
obr.load_features_for_segment(features, a.segment_id);
vector<index_score> scores;
vector<index_score> reweight_scores;
obr_scans.rvt.top_larger_similarities(scores, features, nbr_query);
obr_scans.rvt.top_smaller_similarities(reweight_scores, features, nbr_query);
//obr_scans.query_reweight_vocabulary(scores, reweight_scores, features, cloud, K, nbr_query);
int scan_ind = scan_ind_for_supervoxel(a.segment_id, obr);
calculate_correct_ratio(instance_correct_ratios, a, scan_ind, scores, obr_scans);
calculate_correct_ratio(reweight_correct_ratios, a, scan_ind, reweight_scores, obr_scans);
cout << "Number of features: " << features->size() << endl;
instance_mean_features[a.annotation].first += features->size();
instance_mean_features[a.annotation].second += 1;
//obr.visualize_cloud(cloud);
}
cout << "First round correct ratios: " << endl;
for (pair<const string, pair<float, int> > c : instance_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
cout << "Mean features: " << float(instance_mean_features[c.first].first)/float(instance_mean_features[c.first].second) << endl;
cout << "Number of queries: " << instance_number_queries[c.first] << endl;
}
cout << "Reweight round correct ratios: " << endl;
for (pair<const string, pair<float, int> > c : reweight_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
}
}
void save_oversegmented_vocabulary_index_vectors(object_retrieval& obr_scans)
{
map<vocabulary_tree<HistT, 8>::node*, int> mapping;
obr_scans.rvt.get_node_mapping(mapping);
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
vector<HistCloudT::Ptr> voxels;
CloudT::Ptr voxel_centers(new CloudT);
vector<double> voxel_norms;
get_oversegmented_voxels_for_scan(voxels, voxel_centers, voxel_norms, i, obr_scans);
vector<map<int, double> > vocabulary_vectors;
for (HistCloudT::Ptr& voxel : voxels) {
vocabulary_vectors.push_back(map<int, double>());
double pnorm = obr_scans.rvt.compute_query_index_vector(vocabulary_vectors.back(), voxel, mapping);
//vocabulary_norms.push_back(pnorm);
}
string vectors_file = path + "/vocabulary_vectors.cereal";
ofstream out(vectors_file, std::ios::binary);
{
cereal::BinaryOutputArchive archive_o(out);
archive_o(vocabulary_vectors);
}
}
}
void save_oversegmented_grouped_vocabulary_index_vectors(object_retrieval& obr_scans, object_retrieval& obr_voxels)
{
map<vocabulary_tree<HistT, 8>::node*, int> mapping;
obr_voxels.gvt.get_node_mapping(mapping);
for (int i = 0; ; ++i) {
string path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(path)) {
break;
}
vector<HistCloudT::Ptr> voxels;
CloudT::Ptr voxel_centers(new CloudT);
vector<double> voxel_norms;
get_oversegmented_voxels_for_scan(voxels, voxel_centers, voxel_norms, i, obr_scans);
vector<map<int, double> > vocabulary_vectors;
vector<double> vocabulary_norms;
for (HistCloudT::Ptr& voxel : voxels) {
if (voxel->size() < 20) {
continue;
}
vocabulary_vectors.push_back(map<int, double>());
double pnorm = obr_voxels.gvt.compute_query_index_vector(vocabulary_vectors.back(), voxel, mapping);
vocabulary_norms.push_back(pnorm);
}
string vectors_file = path + "/grouped_vocabulary_vectors.cereal";
ofstream outv(vectors_file, std::ios::binary);
{
cereal::BinaryOutputArchive archive_o(outv);
archive_o(vocabulary_vectors);
}
string norms_file = path + "/grouped_vocabulary_norms.cereal";
ofstream outn(norms_file, std::ios::binary);
{
cereal::BinaryOutputArchive archive_o(outn);
archive_o(vocabulary_norms);
}
}
}
void query_supervoxel_annotations_oversegments(vector<voxel_annotation>& annotations, Eigen::Matrix3f& K,
object_retrieval& obr, object_retrieval& obr_scans)
{
const int nbr_query = 11;
const int nbr_intial_query = 1000;
if (obr_scans.rvt.empty()) {
obr_scans.read_vocabulary(obr_scans.rvt);
}
obr_scans.rvt.set_min_match_depth(1);
obr_scans.rvt.compute_normalizing_constants();
map<vocabulary_tree<HistT, 8>::node*, int> mapping;
obr_scans.rvt.get_node_mapping(mapping);
//save_oversegmented_vocabulary_vectors(obr_scans);
//save_oversegmented_vocabulary_index_vectors(obr_scans);
//exit(0);
map<string, int> nbr_full_instances;
map<string, pair<float, int> > instance_correct_ratios;
map<string, pair<float, int> > first_correct_ratios;
map<string, pair<float, int> > usual_correct_ratios;
map<string, pair<int, int> > instance_mean_features;
map<string, int> instance_number_queries;
for (voxel_annotation& a : annotations) {
if (a.full) {
nbr_full_instances[a.annotation] += 1;
}
if (!a.full || !a.annotation_covered || !a.segment_covered) {
continue;
}
if (a.annotation != "ajax_1" && a.annotation != "ajax_2" && a.annotation != "ball_1") {
//continue;
}
instance_number_queries[a.annotation] += 1;
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
HistCloudT::Ptr features(new HistCloudT);
obr.load_features_for_segment(features, a.segment_id);
vector<index_score> scores;
obr_scans.rvt.top_larger_similarities(scores, features, nbr_intial_query);
vector<index_score> updated_scores;
for (size_t i = 0; i < scores.size(); ++i) {
CloudT::Ptr voxel_centers(new CloudT);
vector<double> vocabulary_norms;
vector<map<int, double> > vocabulary_vectors;
//vector<HistCloudT::Ptr> voxels;
//CloudT::Ptr dummy_centers(new CloudT);
//vector<double> dummy_norms;
//get_oversegmented_voxels_for_scan(voxels, dummy_centers, dummy_norms, scores[i].first, obr_scans);
get_oversegmented_vectors_for_scan(voxel_centers, vocabulary_norms, vocabulary_vectors, scores[i].first, obr_scans);
vector<int> selected_indices;
double score = obr_scans.rvt.compute_min_combined_dist(selected_indices, features, vocabulary_vectors, vocabulary_norms, voxel_centers, mapping);
//double score = obr_scans.rvt.compute_min_combined_dist(features, voxels, dummy_norms, dummy_centers);
updated_scores.push_back(index_score(scores[i].first, score));
}
std::sort(updated_scores.begin(), updated_scores.end(), [](const index_score& s1, const index_score& s2) {
return s1.second < s2.second; // find min elements!
});
updated_scores.resize(nbr_query);
int scan_ind = scan_ind_for_supervoxel(a.segment_id, obr);
calculate_correct_ratio(instance_correct_ratios, a, scan_ind, updated_scores, obr_scans);
calculate_correct_ratio(first_correct_ratios, a, scan_ind, scores, obr_scans, false);
scores.resize(nbr_query);
calculate_correct_ratio(usual_correct_ratios, a, scan_ind, scores, obr_scans);
cout << "Number of features: " << features->size() << endl;
instance_mean_features[a.annotation].first += features->size();
instance_mean_features[a.annotation].second += 1;
//obr.visualize_cloud(cloud);
}
cout << "First round correct ratios: " << endl;
for (pair<const string, pair<float, int> > c : instance_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
cout << c.first << " usual correct ratio: " << usual_correct_ratios[c.first].first/float(usual_correct_ratios[c.first].second) << endl;
cout << c.first << " first round correct ratio: " << first_correct_ratios[c.first].first/float(first_correct_ratios[c.first].second) << endl;
cout << "Mean features: " << float(instance_mean_features[c.first].first)/float(instance_mean_features[c.first].second) << endl;
cout << "Number of queries: " << instance_number_queries[c.first] << endl;
}
}
void change_supervoxel_groups(object_retrieval& obr_voxels)
{
map<int, int> number_features_in_group;
int current_ind = -1;
int current_offset = 0;
map<int, int> temp(obr_voxels.gvt.index_group.begin(), obr_voxels.gvt.index_group.end());
int nbr_groups = 0;
int counter = 0;
vector<HistCloudT::Ptr> voxels;
for (pair<const int, int>& p : temp) {
//cout << p.second << endl;
int scan_ind = scan_ind_for_supervoxel(p.second, obr_voxels); // the second is the actual segment
number_features_in_group[scan_ind] += 1;
if (scan_ind != current_ind) {
current_ind = scan_ind;
current_offset = p.first; // this is the first oversegmented in the group
++nbr_groups;
counter = 0;
}
obr_voxels.gvt.group_subgroup.insert(make_pair(p.first, make_pair(scan_ind, counter)));//p.first-current_offset)));
++counter;
}
vector<pair<int, int> > max_features_in_group;
max_features_in_group.insert(max_features_in_group.end(), number_features_in_group.begin(), number_features_in_group.end());
std::sort(max_features_in_group.begin(), max_features_in_group.end(), [](const pair<int, int>& p1, const pair<int, int>& p2) {
return p1.second < p2.second;
});
for (int i = 0; i < 1000; ++i) {
cout << max_features_in_group[i].first << ": " << max_features_in_group[i].second << endl;
}
cout << "number of scans: " << number_features_in_group.size() << endl;
cout << "number of supervoxels: " << obr_voxels.gvt.index_group.size() << endl;
cout << "deep count supervoxels: " << obr_voxels.gvt.deep_count_sets() << endl;
cout << "number of groups: " << nbr_groups << endl;
string root_path = obr_voxels.segment_path;
string group_file = root_path + "/group_subgroup.cereal";
ofstream out(group_file, std::ios::binary);
{
cereal::BinaryOutputArchive archive_o(out);
archive_o(obr_voxels.gvt.group_subgroup);
}
}
void read_supervoxel_groups(object_retrieval& obr_voxels)
{
string root_path = obr_voxels.segment_path;
string group_file = root_path + "/group_subgroup.cereal";
ifstream in(group_file, std::ios::binary);
{
cereal::BinaryInputArchive archive_i(in);
archive_i(obr_voxels.gvt.group_subgroup);
}
}
void get_max_supervoxel_features(object_retrieval& obr_scans)
{
int max_features = 0;
for (int i = 0; ; ++i) {
string scan_path = obr_scans.get_folder_for_segment_id(i);
if (!boost::filesystem::is_directory(scan_path)) {
break;
}
vector<HistCloudT::Ptr> voxels;
CloudT::Ptr voxel_centers(new CloudT);
vector<double> vocabulary_norms;
get_oversegmented_voxels_for_scan(voxels, voxel_centers, vocabulary_norms, i, obr_scans);
for (HistCloudT::Ptr& v : voxels) {
max_features = std::max(max_features, int(v->size()));
}
}
cout << "Highest number of features: " << max_features << endl;
}
void test_supervoxel_ordering(object_retrieval& obr, object_retrieval& obr_scans)
{
}
void query_supervoxel_oversegments(vector<voxel_annotation>& annotations, Eigen::Matrix3f& K,
object_retrieval& obr, object_retrieval& obr_scans)
{
const int nbr_query = 11;
const int nbr_intial_query = 0;
/*if (obr_scans.rvt.empty()) {
obr_scans.read_vocabulary(obr_scans.rvt);
}
obr_scans.rvt.set_min_match_depth(2);
obr_scans.rvt.compute_normalizing_constants();*/
map<vocabulary_tree<HistT, 8>::node*, int> mapping;
//obr_scans.rvt.get_node_mapping(mapping);
if (obr.gvt.empty()) {
obr.read_vocabulary(obr.gvt);
}
obr.gvt.set_min_match_depth(2);
obr.gvt.compute_normalizing_constants();
read_supervoxel_groups(obr);
//obr.gvt.compute_group_normalizing_constants();
obr.gvt.compute_leaf_vocabulary_vectors();
obr.gvt.get_node_mapping(mapping);
//obr.gvt.compute_min_group_indices();
//obr.gvt.compute_intermediate_node_vocabulary_vectors();
//save_oversegmented_grouped_vocabulary_index_vectors(obr_scans, obr);
//exit(0);
//get_max_supervoxel_features(obr_scans);
//change_supervoxel_groups(obr);
//exit(0);
map<string, int> nbr_full_instances;
map<string, pair<float, int> > instance_correct_ratios;
//map<string, pair<float, int> > first_correct_ratios;
map<string, pair<float, int> > usual_correct_ratios;
map<string, pair<float, int> > total_correct_ratios;
map<string, pair<int, int> > instance_mean_features;
map<string, int> instance_number_queries;
chrono::time_point<std::chrono::system_clock> start, end;
start = chrono::system_clock::now();
double total_time1 = 0.0;
double total_time2 = 0.0;
double total_timec = 0.0;
int counter = 0;
for (voxel_annotation& a : annotations) {
if (counter > 5) {
break;
}
if (a.full) {
nbr_full_instances[a.annotation] += 1;
}
if (!a.full || !a.annotation_covered || !a.segment_covered) {
continue;
}
if (a.annotation != "ajax_1" && a.annotation != "ajax_2" && a.annotation != "ball_1") {
//continue;
}
instance_number_queries[a.annotation] += 1;
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
HistCloudT::Ptr features(new HistCloudT);
obr.load_features_for_segment(features, a.segment_id);
vector<tuple<int, int, double> > tuple_scores;
chrono::time_point<std::chrono::system_clock> start1, end1;
start1 = chrono::system_clock::now();
// this also takes care of the scan association
obr.gvt.top_optimized_similarities(tuple_scores, features, nbr_intial_query);
//cout << normalizing_constants.size() << endl;
//obr.gvt.top_combined_similarities(scores, features, nbr_intial_query);
vector<index_score> scores;
vector<int> hints;
for (const tuple<int, int, double>& t : tuple_scores) {
scores.push_back(index_score(get<0>(t), get<2>(t)));
hints.push_back(get<1>(t));
}
end1 = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds1 = end1-start1;
chrono::time_point<std::chrono::system_clock> start2, end2;
start2 = chrono::system_clock::now();
vector<index_score> updated_scores;
vector<index_score> total_scores;
for (size_t i = 0; i < scores.size(); ++i) {
CloudT::Ptr voxel_centers(new CloudT);
vector<double> vocabulary_norms;
vector<map<int, double> > vocabulary_vectors;
//get_oversegmented_vectors_for_scan(voxel_centers, vocabulary_norms, vocabulary_vectors, get<0>(scores[i]), obr_scans);
get_grouped_oversegmented_vectors_for_scan(voxel_centers, vocabulary_norms, vocabulary_vectors, get<0>(scores[i]), obr_scans);
set<int> subgroups;
obr.gvt.get_subgroups_for_group(subgroups, scores[i].first);
vector<double> computed_norms;
for (int k : subgroups) {
computed_norms.push_back(obr.gvt.get_norm_for_group_subgroup(scores[i].first, k));
}
std::sort(computed_norms.begin(), computed_norms.end());
std::sort(vocabulary_norms.begin(), vocabulary_norms.end());
cout << "Subgroups size: " << computed_norms.size() << endl;
cout << "Vocabulary size: " << vocabulary_norms.size() << endl;
for (double v : computed_norms) {
cout << v << " ";
}
cout << endl;
for (double v : vocabulary_norms) {
cout << v << " ";
}
cout << endl;
/*vector<double> computed_norms(vocabulary_norms.size());
for (int j = 0; j < vocabulary_norms.size(); ++j) {
computed_norms[j] = obr.gvt.get_norm_for_group_subgroup(scores[i].first, j);
cout << vocabulary_norms[j] << ", " << computed_norms[j] << endl;
}
exit(0);*/
vector<HistCloudT::Ptr> voxels;
get_just_oversegmented_voxels_for_scan(voxels, get<0>(scores[i]), obr_scans);
cout << "Saved first norm: " << vocabulary_norms[hints[i]] << endl;
cout << "Hint: " << scores[i].first << ", " << hints[i] << endl;
//cout << "Original norm: " << normalizing_constants[i] << endl;
chrono::time_point<std::chrono::system_clock> startc, endc;
startc = chrono::system_clock::now();
// compare the hint vector with the previous one:
int j = hints[i]; {
cout << "Looking at vector " << j << endl;
cout << "Hint: " << hints[i] << endl;
cout << "Vector norm: " << vocabulary_norms[j] << endl;
cout << "saved vector size: " << vocabulary_vectors[j].size() << endl;
//map<vocabulary_tree<HistT, 8>::node*, double> recomputed_node_vector;
map<int, double> recomputed_saved_vector;
double pnorm = obr.gvt.compute_query_index_vector(recomputed_saved_vector, voxels[j], mapping);
//obr.gvt.compute_vocabulary_vector_for_group_with_subgroup(recomputed_node_vector, scores[i].first, j);
/*for (const pair<vocabulary_tree<HistT, 8>::node*, double>& u : recomputed_node_vector) {
recomputed_saved_vector[mapping[u.first]] = u.second;
}*/
//cout << "Recomputed saved vector norm: " << pnorm << endl;
for (const pair<int, double>& u : recomputed_saved_vector) {
if (vocabulary_vectors[j].count(u.first) > 0) {
cout << "Index: " << u.first << "stored one: " << u.second << ", computed: " << vocabulary_vectors[j][u.first] << endl;
}
else {
cout << u.first << " with value " << u.second << " not present " << endl;
}
}
}
// the hints are sometimes the same index and then the scores are the same (naturally)
// otherwise the second one is lower, it would be interesting to look at the score of the hint also
// at least the norms seem to be the same for the saved vectors
cout << "Hint score: " << scores[i].second << endl;
vector<map<int, double> > vocabulary_vectors_copy = vocabulary_vectors;
vector<double> vocabulary_norms_copy = vocabulary_norms;
CloudT::Ptr voxel_centers_copy(new CloudT);
*voxel_centers_copy = *voxel_centers;
//double score = obr_scans.rvt.compute_min_combined_dist(features, vocabulary_vectors, vocabulary_norms, voxel_centers, mapping, hints[i]);
vector<int> selected_indices_1;
double score = obr.gvt.compute_min_combined_dist(selected_indices_1, features, vocabulary_vectors, vocabulary_norms, voxel_centers, mapping, hints[i]);
updated_scores.push_back(index_score(get<0>(scores[i]), score));
vector<int> selected_indices_2;
double total_score = obr.gvt.compute_min_combined_dist(selected_indices_2, features, vocabulary_vectors_copy, vocabulary_norms_copy, voxel_centers_copy, mapping, -1);
total_scores.push_back(index_score(get<0>(scores[i]), total_score));
endc = chrono::system_clock::now();
chrono::duration<double> elapsed_secondsc = endc-startc;
total_timec += elapsed_secondsc.count();
exit(0);
}
end2 = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds2 = end2-start2;
total_time1 += elapsed_seconds1.count();
total_time2 += elapsed_seconds2.count();
std::sort(updated_scores.begin(), updated_scores.end(), [](const index_score& s1, const index_score& s2) {
return s1.second < s2.second; // find min elements!
});
updated_scores.resize(nbr_query);
std::sort(total_scores.begin(), total_scores.end(), [](const index_score& s1, const index_score& s2) {
return s1.second < s2.second; // find min elements!
});
total_scores.resize(nbr_query);
int scan_ind = scan_ind_for_supervoxel(a.segment_id, obr);
calculate_correct_ratio(instance_correct_ratios, a, scan_ind, updated_scores, obr_scans);
//calculate_correct_ratio(first_correct_ratios, a, scan_ind, scores, obr_scans, false);
scores.resize(nbr_query);
calculate_correct_ratio(usual_correct_ratios, a, scan_ind, scores, obr_scans);
calculate_correct_ratio(total_correct_ratios, a, scan_ind, total_scores, obr_scans);
cout << "Number of features: " << features->size() << endl;
instance_mean_features[a.annotation].first += features->size();
instance_mean_features[a.annotation].second += 1;
++counter;
}
end = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = end-start;
cout << "Benchmark took " << elapsed_seconds.count() << " seconds" << endl;
cout << "First part took " << total_time1 << " seconds" << endl;
cout << "Second part took " << total_time2 << " seconds" << endl;
cout << "Calculation of second part took: " << total_timec << " seconds" << endl;
cout << "First round correct ratios: " << endl;
for (pair<const string, pair<float, int> > c : instance_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
cout << c.first << " total correct ratio: " << total_correct_ratios[c.first].first/float(total_correct_ratios[c.first].second) << endl;
cout << c.first << " usual correct ratio: " << usual_correct_ratios[c.first].first/float(usual_correct_ratios[c.first].second) << endl;
//cout << c.first << " first round correct ratio: " << first_correct_ratios[c.first].first/float(first_correct_ratios[c.first].second) << endl;
cout << "Mean features: " << float(instance_mean_features[c.first].first)/float(instance_mean_features[c.first].second) << endl;
cout << "Number of queries: " << instance_number_queries[c.first] << endl;
}
}
vector<index_score> top_combined_similarities(map<int, double>& larger_map, map<int, double>& smaller_map, int nbr_query, float& ratio, int nbr_features)
{
double larger_mean = 1.0;
/*size_t counter = 2;
for (const index_score& s : larger_map) {
if (counter > 10) {
break;
}
larger_mean += s.second;
++counter;
}
larger_mean /= double(counter);*/
double smaller_mean = 1.0;
/*counter = 2;
for (const index_score& s : smaller_map) {
if (counter > 10) {
break;
}
smaller_mean += s.second;
++counter;
}
smaller_mean /= double(counter);*/
int smaller_count = 0;
int larger_count = 0;
for (pair<const int, double>& s : smaller_map) {
if (larger_map.count(s.first)) {
//s.second = std::max(s.second/larger_mean, smaller_map[s.first]/smaller_mean);
//s.second *= smaller_map[s.first];
//float extra = 1.0 + float(nbr_features) / 500.0f;
if (s.second/smaller_mean > larger_map[s.first]/larger_mean) {
s.second = s.second/smaller_mean;
++smaller_count;
}
else {
s.second = larger_map[s.first]/larger_mean;
++larger_count;
}
}
else {
s.second = 1000.0; // very larger
}
}
vector<index_score> rtn;
rtn.insert(rtn.end(), smaller_map.begin(), smaller_map.end());
std::sort(rtn.begin(), rtn.end(), [](const index_score& s1, const index_score& s2) {
return s1.second < s2.second; // find min elements!
});
rtn.resize(nbr_query);
ratio = float(larger_count) / float(larger_count + smaller_count);
return rtn;
}
void query_supervoxel_and_scan_annotations(vector<voxel_annotation>& annotations, object_retrieval& obr, object_retrieval& obr_scans)
{
const int nbr_query = 11;
/*if (obr.gvt.empty()) {
obr.read_vocabulary(obr.gvt);
}
obr.gvt.set_min_match_depth(3);
obr.gvt.compute_normalizing_constants();*/
if (obr_scans.vt.empty()) {
obr_scans.read_vocabulary(obr_scans.vt);
}
obr_scans.vt.set_min_match_depth(3);
obr_scans.vt.compute_normalizing_constants();
/*object_retrieval::my_vocabulary_tree svt;
ifstream in("/home/nbore/Data/Instances/scan_segments/vocabulary_pfhrgb.cereal", std::ios::binary);
{
cereal::BinaryInputArchive archive_i(in);
archive_i(svt);
}
in.close();
svt.set_min_match_depth(3);
svt.compute_normalizing_constants();*/
// read supervoxel vocabulary
if (obr.vt.empty()) {
obr.read_vocabulary(obr.vt);
}
obr.vt.set_min_match_depth(3);
obr.vt.compute_normalizing_constants();
// read scan vocabulary, could also use obr_scans for this
map<string, int> nbr_full_instances;
map<string, pair<float, int> > instance_correct_ratios;
map<string, float> instance_max_ratios;
for (voxel_annotation& a : annotations) {
if (a.full) {
nbr_full_instances[a.annotation] += 1;
}
if (!a.full || !a.annotation_covered || !a.segment_covered) {
continue;
}
if (a.annotation != "ajax_1" && a.annotation != "ajax_2" && a.annotation != "ball_1") {
continue;
}
CloudT::Ptr cloud(new CloudT);
pcl::io::loadPCDFile(a.segment_file, *cloud);
HistCloudT::Ptr features(new HistCloudT);
obr.load_features_for_segment(features, a.segment_id);
vector<index_score> larger_scores;
//obr.gvt.top_grouped_similarities(scores, features, nbr_query);
obr_scans.vt.top_larger_similarities(larger_scores, features, 0);
//svt.top_partial_similarities(larger_scores, features, 0);
int scan_ind = scan_ind_for_supervoxel(a.segment_id, obr);
vector<index_score> smaller_scores;
obr.vt.top_smaller_similarities(smaller_scores, features, 0);
map<int, double> larger_map((larger_scores.begin()), larger_scores.end());
map<int, double> smaller_map((smaller_scores.begin()), smaller_scores.end());
// do some after-processing to put this in a longer vector with correct segments
// just keep the smaller segments with the smallest distance?
//unordered_map<int, int> scan_for_supervoxel_hash;
vector<index_score> voxel_larger_scores;
for (pair<const int, double>& s : larger_map) {
if (s.first == scan_ind) {
continue;
}
vector<int> supervoxel_indices;
get_voxels_for_scan(supervoxel_indices, s.first, obr_scans);
int min_ind = -1;
float min_dist = 1000.0; // very large
for (int i : supervoxel_indices) {
if (smaller_map.count(i) && smaller_map[i] < min_dist) {
min_ind = i;
min_dist = smaller_map[i];
}
//voxel_larger_scores.push_back(index_score(i, s.second));
//scan_for_supervoxel_hash[i] = s.first;
}
for (int i : supervoxel_indices) {
if (i != min_ind) {
smaller_map.erase(i);
}
}
if (min_ind != -1) {
larger_map.insert(make_pair(min_ind, s.second));
}
}
float max_ratio;
vector<index_score> scores = top_combined_similarities(larger_map, smaller_map, nbr_query, max_ratio, features->size());
bool found = false;
int counter = 0;
int partial_counter = 0;
bool last_match;
for (index_score s : scores) {
//CloudT::Ptr segment(new CloudT);
//obr.read_scan(segment, s.first);
//obr.visualize_cloud(segment);
string instance = annotation_for_supervoxel(s.first, obr);
if (s.first == a.segment_id) {
found = true;
continue;
}
last_match = false;
if (instance == a.annotation) {
++counter;
last_match = true;
if (!a.full) {
++partial_counter;
}
cout << "This was true." << endl;
}
else {
cout << "This was false." << endl;
}
HistCloudT::Ptr features_match(new HistCloudT);
obr.load_features_for_segment(features_match, s.first);
cout << "Score: " << s.second << endl;
cout << "Number of features: " << features_match->size() << endl;
}
if (!found) {
if (last_match) {
--counter;
}
}
float correct_ratio = float(counter)/float(scores.size()-1);
instance_correct_ratios[a.annotation].first += correct_ratio;
instance_correct_ratios[a.annotation].second += 1;
instance_max_ratios[a.annotation] += max_ratio;
cout << "Showing " << a.segment_file << " with annotation " << a.annotation << endl;
cout << "Number of features: " << features->size() << endl;
cout << "Correct ratio: " << correct_ratio << endl;
cout << "Partial ratio: " << float(partial_counter)/float(counter) << endl;
//obr.visualize_cloud(cloud);
}
for (pair<const string, pair<float, int> > c : instance_correct_ratios) {
cout << c.first << " correct ratio: " << c.second.first/float(c.second.second) << endl;
cout << "Max ratio: " << instance_max_ratios[c.first] / float(c.second.second) << endl;
}
}
int main(int argc, char** argv)
{
int nbr_results = 11;
using entity = SimpleSummaryParser::EntityStruct;
string root_path = "/home/nbore/Data/Instances/";
string segments_path = root_path + "object_segments";
string aggregate_path = root_path + "scan_segments";
string voxels_path = root_path + "supervoxel_segments";
map<int, string> annotated;
map<int, string> full_annotated;
//aggregate the features of the segments into features of scans
object_retrieval obr_segments(segments_path);
list_all_annotated_segments(annotated, full_annotated, segments_path);
//aggregate_features(obr_segments, aggregate_path);
object_retrieval obr(aggregate_path);
obr.segment_name = "scan";
//aggregate_pfhrgb_features(obr);
Eigen::Matrix3f Kall;
{
CloudT::Ptr segment(new CloudT);
NormalCloudT::Ptr normal(new NormalCloudT);
CloudT::Ptr hd_segment(new CloudT);
string metadata;
obr_segments.read_segment(segment, normal, hd_segment, Kall, metadata, 0);
}
//save_supervoxel_features(obr);
//save_sift_features(obr);
//save_duplet_features(obr);
//exit(0);
object_retrieval obr_voxels(voxels_path);
vector<voxel_annotation> annotations;
string annotations_file = voxels_path + "/voxel_annotations.cereal";
list_annotated_supervoxels(annotations, annotations_file, Kall, obr_voxels);
//visualize_supervoxel_annotation(annotations, obr_voxels);
//query_supervoxel_annotations(annotations, obr_voxels);
//query_supervoxel_and_scan_annotations(annotations, obr_voxels, obr);
//query_supervoxel_annotations_scans(annotations, Kall, obr_voxels, obr);
//query_supervoxel_annotations_oversegments(annotations, Kall, obr_voxels, obr);
query_supervoxel_oversegments(annotations, Kall, obr_voxels, obr);
//save_sift_features_for_supervoxels(Kall, obr_voxels);
//save_pfhrgb_features_for_supervoxels(obr_voxels);
//convert_voxels_to_binary(obr);
//save_oversegmented_points(obr);
//save_supervoxel_centers(obr);
cout << "Extracted all of the features" << endl;
// do initial training of vocabulary, save vocabulary
//obr.train_vocabulary_incremental(5000, false);
//obr_voxels.train_vocabulary_incremental(12000, false);
//save_split_features(obr_voxels);
//obr_voxels.train_grouped_vocabulary(4000, false);
exit(0);
// make sure there is a vocabulary to query from
if (obr.rvt.empty()) {
obr.read_vocabulary(obr.rvt);
}
obr.rvt.set_min_match_depth(2);
obr.rvt.compute_normalizing_constants();
using node = vocabulary_tree<HistT, 8>::node;
map<node*, double> original_weights;
//obr.rvt.compute_pyramid_match_weights(original_weights); // not necessary for this kind of matching
int true_hits = 0;
int false_hits = 0;
int nbr_annotated = 0;
int first_hits = 0;
int reweight_true_hits = 0;
int reweight_false_hits = 0;
int reweight_first_hits = 0;
chrono::time_point<std::chrono::system_clock> start, end;
start = chrono::system_clock::now();
map<string, pair<int, int> > instance_true_false_hits;
map<string, pair<int, int> > reweight_instance_true_false_hits;
// ok, now we've trained the representation, let's query it
// and simply count the scans with correct annotation
// so, simply find the annotated segments and query them
for (pair<const int, string>& v : full_annotated) {
HistCloudT::Ptr features(new HistCloudT);
obr_voxels.load_features_for_segment(features, v.first);
//obr_segments.load_features_for_segment(features, v.first);
cout << "Features length: " << features->size() << endl;
cout << "Queried instance: " << v.second << endl;
CloudT::Ptr segment(new CloudT);
NormalCloudT::Ptr normal(new NormalCloudT);
CloudT::Ptr hd_segment(new CloudT);
CloudT::Ptr kp_cloud(new CloudT);
Eigen::Matrix3f K;
string metadata;
cout << __FILE__ << ", " << __LINE__ << endl;
//obr_segments.read_segment(segment, normal, hd_segment, K, metadata, v.first);
cout << __FILE__ << ", " << __LINE__ << endl;
//SiftCloudT::Ptr sift_features(new SiftCloudT);
//sift_features_for_segment(sift_features, kp_cloud, hd_segment, K);
//compute_feature_duplets(features, sift_features, kp_cloud);
//shot_features_for_segment(features, hd_segment, K);
//obr_segments.visualize_cloud(hd_segment);
vector<index_score> scores;
vector<index_score> reweight_scores;
obr.rvt.top_similarities(scores, features, nbr_results);
//obr.query_reweight_vocabulary(scores, reweight_scores, features, hd_segment, K, nbr_results);
string first_annotation = annotation_for_scan(scores[0].first, obr);
if (first_annotation == v.second) {
++first_hits;
}
bool found_query = false;
bool reweight_found_query = false;
bool last_hit;
bool reweight_last_hit;
for (index_score s : scores) {
if (scan_contains_segment(s.first, v.first, obr)) {
found_query = true;
continue;
}
string annotation = annotation_for_scan(s.first, obr);
last_hit = (annotation == v.second);
cout << "Annotation: " << annotation << " with score: " << s.second << endl;
if (annotation == v.second) {
++true_hits;
instance_true_false_hits[v.second].first += 1;
}
else {
++false_hits;
instance_true_false_hits[v.second].second += 1;
}
}
for (index_score s : reweight_scores) {
if (scan_contains_segment(s.first, v.first, obr)) {
reweight_found_query = true;
continue;
}
string annotation = annotation_for_scan(s.first, obr);
reweight_last_hit = (annotation == v.second);
cout << "Annotation: " << annotation << " with score: " << s.second << endl;
if (annotation == v.second) {
++reweight_true_hits;
reweight_instance_true_false_hits[v.second].first += 1;
}
else {
++reweight_false_hits;
reweight_instance_true_false_hits[v.second].second += 1;
}
}
if (!found_query) {
if (last_hit) {
--true_hits;
instance_true_false_hits[v.second].first -= 1;
}
else {
--false_hits;
instance_true_false_hits[v.second].second -= 1;
}
}
if (!reweight_found_query) {
if (reweight_last_hit) {
--reweight_true_hits;
reweight_instance_true_false_hits[v.second].first -= 1;
}
else {
--false_hits;
reweight_instance_true_false_hits[v.second].second -= 1;
}
}
++nbr_annotated;
}
end = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = end-start;
cout << "True hits: " << true_hits << endl;
cout << "False hits: " << false_hits << endl;
cout << "Ratio: " << float(true_hits)/float(true_hits+false_hits) << endl;
cout << "First hit ratio: " << float(first_hits)/float(nbr_annotated) << endl;
cout << "Reweight True hits: " << reweight_true_hits << endl;
cout << "Reweight False hits: " << reweight_false_hits << endl;
cout << "Reweight Ratio: " << float(reweight_true_hits)/float(reweight_true_hits+reweight_false_hits) << endl;
cout << "Reweight First hit ratio: " << float(reweight_first_hits)/float(nbr_annotated) << endl;
cout << "Benchmark took " << elapsed_seconds.count() << " seconds" << endl;
cout << "First round: " << endl;
for (pair<const string, pair<int, int> >& a : instance_true_false_hits) {
cout << a.first << " ratio: " << float(a.second.first)/float(a.second.first+a.second.second) << endl;
}
cout << "Reweight round: " << endl;
for (pair<const string, pair<int, int> >& a : reweight_instance_true_false_hits) {
cout << a.first << " ratio: " << float(a.second.first)/float(a.second.first+a.second.second) << endl;
}
// ratio 0.0875 for voc tree minus norms
// ratio 0.0875 for voc tree
// ratio 0.0875 for voc tree min comparison
// vt normal and min comp
// True hits: 161
// False hits: 1679
// Ratio: 0.0875
// First hit ratio: 0.228261
// Benchmark took 73.3449 seconds
// pm normal
// True hits: 42
// False hits: 1798
// Ratio: 0.0228261
// First hit ratio: 0.0271739
return 0;
}
| [
"nilsbore@gmail.com"
] | nilsbore@gmail.com |
402273bc37927fa530f28c217f9403fb2561f24a | 7ba254b6e04238d482c62420781fa995719a984c | /mpac_mproc/pac-soc/pac-soc.cpp | 0f9f4bf9f453a1c0d5c3e1d8e5a9504fff287a2a | [] | no_license | cuibixiong/multicore-simulation | 25d3ba38ad1270e19868e297fa6af484606ed638 | 8b22030c2e264fee08ff92f315a2948e45de9012 | refs/heads/master | 2021-01-01T05:35:34.857120 | 2013-05-26T16:04:22 | 2013-05-26T16:04:22 | 10,299,972 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,759 | cpp | #include "mpac-mproc-define.h"
#include "pac-socshm-prot.h"
#include "pac-soc.h"
#include "pac-parser.h"
#ifdef PAC_2WAY_ICACHE_LINE
#include "pac-l2-way-bus.h"
#elif PAC_4WAY_ICACHE_LINE
#include "pac-l2-way-bus.h"
#elif PAC_8WAY_ICACHE_LINE
#include "pac-l2-way-bus.h"
#else
#include "pac-l2-direct-bus.h"
#endif
#include "pac-core-bus.h"
#include "pac-m1-bus.h"
#include "pac-m2-bus.h"
#include "pac-biu-bus.h"
#include "pac-dma-bus.h"
#include "pac-dmu-bus.h"
#include "pac-d2-bus.h"
#include "getopt.h"
#include "sys/shm.h"
#include "sys/types.h"
#ifdef C2CC
#include "c2cc-wrap.h"
#include "pac-c2cc-bus.h"
#endif
Core_Bus *dsp[DSPNUM];
static struct option long_options[] = {
{"exec", required_argument, NULL, 'x'},
{"help", no_argument, NULL, 'h'},
{NULL, no_argument, NULL, 0}
};
static void show_help()
{
printf("example: ./pac-soc-run -x sim.ini \r\n");
printf("Argument:\r\n");
printf("-x --exec execve *.ini file\r\n");
printf("-h --help help\r\n");
exit(0);
}
struct sim_arg multi_sim_arg;
int sc_main(int argc, char *argv[])
{
int opt, option_index;
char *filename = NULL;
if (argc < 2) {
show_help();
exit(-1);
}
soc_sim_setup(&multi_sim_arg);
while ((opt = getopt_long(argc, argv, "hx:", long_options, &option_index)) != -1) {
switch (opt) {
case 'x':
filename = optarg;
soc_sim_parser(filename, &multi_sim_arg);
break;
case 'h':
show_help();
break;
default:
printf("Invalid Argument \r\n");
exit(-1);
}
}
if (filename == NULL) {
printf("No sim.ini file .\r\n");
exit(-1);
}
sc_clock clk("clk", 1, SC_NS);
shm_soc_setup(&multi_sim_arg);
D2_Bus d2_bus("d2_bus", &multi_sim_arg);
Biu_Bus biu_bus("biu_bus", &multi_sim_arg);
Dmu_Bus dmu_bus("dmu_bus", &multi_sim_arg);
Dma_Bus dma_bus("dma_bus", &multi_sim_arg);
M2_Bus m2_bus("m2_bus", &multi_sim_arg);
L2_Bus l2_bus("l2_bus", &multi_sim_arg);
#ifdef C2CC
C2CC_Bus c2cc_bus("c2cc_bus", &multi_sim_arg);
#if DSPNUM >= 1
C2CC_Wrap c2cc_wrap0("c2cc_wrap0", CORE0_ID, &multi_sim_arg);
c2cc_wrap0.clk(clk);
c2cc_wrap0.tx_init_socket(c2cc_bus.targ_socket[CORE0_ID]);
c2cc_wrap0.rx_targ_socket(c2cc_bus.init_socket[CORE0_ID]);
#endif
#if DSPNUM >= 2
C2CC_Wrap c2cc_wrap1("c2cc_wrap1", CORE1_ID, &multi_sim_arg);
c2cc_wrap1.clk(clk);
c2cc_wrap1.tx_init_socket(c2cc_bus.targ_socket[CORE1_ID]);
c2cc_wrap1.rx_targ_socket(c2cc_bus.init_socket[CORE1_ID]);
#endif
#if DSPNUM >= 3
C2CC_Wrap c2cc_wrap2("c2cc_wrap2", CORE2_ID, &multi_sim_arg);
c2cc_wrap2.clk(clk);
c2cc_wrap2.tx_init_socket(c2cc_bus.targ_socket[CORE2_ID]);
c2cc_wrap2.rx_targ_socket(c2cc_bus.init_socket[CORE2_ID]);
#endif
#if DSPNUM >= 4
C2CC_Wrap c2cc_wrap3("c2cc_wrap3", CORE3_ID, &multi_sim_arg);
c2cc_wrap3.clk(clk);
c2cc_wrap3.tx_init_socket(c2cc_bus.targ_socket[CORE3_ID]);
c2cc_wrap3.rx_targ_socket(c2cc_bus.init_socket[CORE3_ID]);
#endif
#endif
#if DSPNUM >= 1
M1_Bus dsp0_m1_bus("dsp0_m1_bus", CORE0_ID, &multi_sim_arg);
dsp0_m1_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[CORE0_ID]); //M1_Bus connect to Dma_Bus
Core_Bus dsp0("dsp0", CORE0_ID, &multi_sim_arg);
dma_bus.dma_d1_dcache_init_socket_tagged[CORE0_ID](dsp0.d1_dcache_targ_socket);
dsp0.l2_bus_init_socket(l2_bus.l2_bus_targ_socket_tagged[CORE0_ID]); //connect to L2_Bus
dsp0.d2_bus_init_socket(d2_bus.d2_bus_targ_socket_tagged[CORE0_ID]);
d2_bus.m1_bus_init_socket_tagged[CORE0_ID](dsp0_m1_bus.m1_bus_targ_socket_tagged[0]);
d2_bus.m2_bus_init_socket_tagged[CORE0_ID](m2_bus.m2_bus_targ_socket_tagged[CORE0_ID]);
d2_bus.biu_bus_init_socket_tagged[CORE0_ID](biu_bus.biu_bus_targ_socket_tagged[CORE0_ID]);
d2_bus.dmu_bus_init_socket_tagged[CORE0_ID](dmu_bus.dmu_bus_targ_socket_tagged[CORE0_ID]);
dma_bus.dma_init_socket_tagged[CORE0_ID](dsp0_m1_bus.m1_bus_targ_socket_tagged[1]); //Dma_Bus connect to M1_Bus dma
dmu_bus.m1_dmu_init_socket_tagged[CORE0_ID](dsp0_m1_bus.m1_bus_targ_socket_tagged[2]); //Dmu_Bus connect to M1_Bus dmu
dsp0.clk(clk);
dsp[CORE0_ID] = &dsp0;
#ifdef C2CC
dsp0_m1_bus.c2cc_init_socket(c2cc_wrap0.tx_targ_socket); //connect to c2cc_wrap
#endif
#endif
#if DSPNUM >= 2
M1_Bus dsp1_m1_bus("dsp1_m1_bus", CORE1_ID, &multi_sim_arg);
dsp1_m1_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[CORE1_ID]); //M1_Bus connect to Dma_Bus
Core_Bus dsp1("dsp1", CORE1_ID, &multi_sim_arg);
dma_bus.dma_d1_dcache_init_socket_tagged[CORE1_ID](dsp1.d1_dcache_targ_socket);
dsp1.l2_bus_init_socket(l2_bus.l2_bus_targ_socket_tagged[CORE1_ID]); //connect to L2_Bus
dsp1.d2_bus_init_socket(d2_bus.d2_bus_targ_socket_tagged[CORE1_ID]);
d2_bus.m1_bus_init_socket_tagged[CORE1_ID](dsp1_m1_bus.m1_bus_targ_socket_tagged[0]);
d2_bus.m2_bus_init_socket_tagged[CORE1_ID](m2_bus.m2_bus_targ_socket_tagged[CORE1_ID]);
d2_bus.biu_bus_init_socket_tagged[CORE1_ID](biu_bus.biu_bus_targ_socket_tagged[CORE1_ID]);
d2_bus.dmu_bus_init_socket_tagged[CORE1_ID](dmu_bus.dmu_bus_targ_socket_tagged[CORE1_ID]);
dma_bus.dma_init_socket_tagged[CORE1_ID](dsp1_m1_bus.m1_bus_targ_socket_tagged[1]); //Dma_Bus connect to M1_Bus dma
dmu_bus.m1_dmu_init_socket_tagged[CORE1_ID](dsp1_m1_bus.m1_bus_targ_socket_tagged[2]); //Dmu_Bus connect to M1_Bus dmu
dsp1.clk(clk);
dsp[CORE1_ID] = &dsp1;
#ifdef C2CC
dsp1_m1_bus.c2cc_init_socket(c2cc_wrap1.tx_targ_socket); //connect to c2cc_wrap
#endif
#endif
#if DSPNUM >= 3
M1_Bus dsp2_m1_bus("dsp2_m1_bus", CORE2_ID, &multi_sim_arg);
dsp2_m1_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[CORE2_ID]); //M1_Bus connect to Dma_Bus
Core_Bus dsp2("dsp2", CORE2_ID, &multi_sim_arg);
dma_bus.dma_d1_dcache_init_socket_tagged[CORE2_ID](dsp2.d1_dcache_targ_socket);
dsp2.l2_bus_init_socket(l2_bus.l2_bus_targ_socket_tagged[CORE2_ID]); //connect to L2_Bus
dsp2.d2_bus_init_socket(d2_bus.d2_bus_targ_socket_tagged[CORE2_ID]);
d2_bus.m1_bus_init_socket_tagged[CORE2_ID](dsp2_m1_bus.m1_bus_targ_socket_tagged[0]);
d2_bus.m2_bus_init_socket_tagged[CORE2_ID](m2_bus.m2_bus_targ_socket_tagged[CORE2_ID]);
d2_bus.biu_bus_init_socket_tagged[CORE2_ID](biu_bus.biu_bus_targ_socket_tagged[CORE2_ID]);
d2_bus.dmu_bus_init_socket_tagged[CORE2_ID](dmu_bus.dmu_bus_targ_socket_tagged[CORE2_ID]);
dma_bus.dma_init_socket_tagged[CORE2_ID](dsp2_m1_bus.m1_bus_targ_socket_tagged[1]); //Dma_Bus connect to M1_Bus dma
dmu_bus.m1_dmu_init_socket_tagged[CORE2_ID](dsp2_m1_bus.m1_bus_targ_socket_tagged[2]); //Dmu_Bus connect to M1_Bus dmu
dsp2.clk(clk);
dsp[CORE2_ID] = &dsp2;
#ifdef C2CC
dsp2_m1_bus.c2cc_init_socket(c2cc_wrap2.tx_targ_socket); //connect to c2cc_wrap
#endif
#endif
#if DSPNUM >= 4
M1_Bus dsp3_m1_bus("dsp3_m1_bus", CORE3_ID, &multi_sim_arg);
dsp3_m1_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[CORE3_ID]); //M1_Bus connect to Dma_Bus
Core_Bus dsp3("dsp3", CORE3_ID, &multi_sim_arg);
dma_bus.dma_d1_dcache_init_socket_tagged[CORE3_ID](dsp3.d1_dcache_targ_socket);
dsp3.l2_bus_init_socket(l2_bus.l2_bus_targ_socket_tagged[CORE3_ID]); //connect to L2_Bus
dsp3.d2_bus_init_socket(d2_bus.d2_bus_targ_socket_tagged[CORE3_ID]);
d2_bus.m1_bus_init_socket_tagged[CORE3_ID](dsp3_m1_bus.m1_bus_targ_socket_tagged[0]);
d2_bus.m2_bus_init_socket_tagged[CORE3_ID](m2_bus.m2_bus_targ_socket_tagged[CORE3_ID]);
d2_bus.biu_bus_init_socket_tagged[CORE3_ID](biu_bus.biu_bus_targ_socket_tagged[CORE3_ID]);
d2_bus.dmu_bus_init_socket_tagged[CORE3_ID](dmu_bus.dmu_bus_targ_socket_tagged[CORE3_ID]);
dma_bus.dma_init_socket_tagged[CORE3_ID](dsp3_m1_bus.m1_bus_targ_socket_tagged[1]); //Dma_Bus connect to M1_Bus dma
dmu_bus.m1_dmu_init_socket_tagged[CORE3_ID](dsp3_m1_bus.m1_bus_targ_socket_tagged[2]); //Dmu_Bus connect to M1_Bus dmu
dsp3.clk(clk);
dsp[CORE3_ID] = &dsp3;
#ifdef C2CC
dsp3_m1_bus.c2cc_init_socket(c2cc_wrap3.tx_targ_socket); //connect to c2cc_wrap
#endif
#endif
dma_bus.dma_d2_dcache_init_socket(d2_bus.d2_bus_targ_socket_tagged[DSPNUM]);
l2_bus.ddr_mem_init_socket(biu_bus.biu_bus_targ_socket_tagged[DSPNUM]); //connect Biu_Bus
m2_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[DSPNUM]); //M2_Bus connect to Dma_Bus
biu_bus.dma_bus_init_socket(dma_bus.dma_targ_socket_tagged[DSPNUM + 1]); //Biu_Bus connect to Dma_Bus
dma_bus.dma_init_socket_tagged[DSPNUM](m2_bus.m2_bus_targ_socket_tagged[DSPNUM]);
dma_bus.dma_init_socket_tagged[DSPNUM + 1](biu_bus.biu_bus_targ_socket_tagged[DSPNUM+1]);
if (MULTI_ARG(boot, share_mode)) {
void *soc_pthread(void *);
pthread_t th;
printf("startup soc_pthread, Now use not direct mode.\r\n");
if (pthread_create(&th, NULL, soc_pthread, NULL) < 0) {
printf("can not create soc pthread.\r\n");
exit(-1);
}
}
sc_start();
shm_soc_del(&multi_sim_arg);
soc_sim_del(&multi_sim_arg);
return 0;
}
| [
"cuibixiong@gmail.com"
] | cuibixiong@gmail.com |
67c1cefb22028cf24c8e7e759e69ad2a29f4f055 | 238bb5b432dbaf3c6bae06a0320898592c67bffe | /16zombie-process/main.cpp | c7935d9033adcdfbf877ee49961f3a348a577025 | [] | no_license | morningblu/linux-program | ae71d417eb4c608e8190cd8422946519fc90c1a7 | 9702252f44758ac519fbf8959a4f9f52da557f93 | refs/heads/master | 2020-08-02T22:06:36.219117 | 2018-10-26T09:09:41 | 2018-10-26T09:09:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp | #include "../common.h"
int main()
{
pid_t pid = fork();
if(pid > 0)
{
// 等待子进程退出,如果子进程退出,回收子进程的PCB
wait(NULL);
while(1)
{
sleep(1);
}
}
return 0;
}
| [
"mazhao@iMac-2.local"
] | mazhao@iMac-2.local |
5b6bb3f597fbb56044c098a19831a774b7c1f018 | aa9ced7d5ffac5ea642ec893c75b62cc46fb3046 | /src/response.cc | 3724a585709a5c2e20d28c6fee6ed7000a1c2c66 | [
"MIT"
] | permissive | dwd/chorus | 103baeea71ef68a6edde63ea0949b0bddcb7c0ba | 1d3ad50936a2840e1fb06fc91003a83a8be25b02 | refs/heads/master | 2016-09-10T21:39:55.381280 | 2016-01-14T09:38:31 | 2016-01-14T09:38:31 | 41,246,382 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | cc | //
// Created by dwd on 28/12/15.
//
#include <chorus/response.h>
| [
"dave.cridland@surevine.com"
] | dave.cridland@surevine.com |
66a689d1678734a1a2bb9aa861673473dec91836 | 71cc711461927a5fb15b19c4529117f62cec4210 | /host/streaming_reg_access/src/host.cpp | dab4414950cefeb587421df8c4c7616ca0042742 | [
"BSD-3-Clause"
] | permissive | yfduskk/Vitis_Accel_Examples | aa37adb021e8332791927709e248ff48780a1636 | 9231c73b3849b0ef7fca756086db3e3912f51dbb | refs/heads/master | 2022-10-29T16:25:55.206281 | 2020-06-04T12:09:25 | 2020-06-04T12:09:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,367 | cpp | /**********
Copyright (c) 2019, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********/
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>
#include <xclhal2.h>
#include "experimental/xclbin_util.h"
// This extension file is required for stream APIs
#include "CL/cl_ext_xilinx.h"
// This file is required for OpenCL C++ wrapper APIs
#include "xcl2.hpp"
// Declaration of custom stream APIs that binds to Xilinx Streaming APIs.
decltype(&clCreateStream) xcl::Stream::createStream = nullptr;
decltype(&clReleaseStream) xcl::Stream::releaseStream = nullptr;
decltype(&clReadStream) xcl::Stream::readStream = nullptr;
decltype(&clWriteStream) xcl::Stream::writeStream = nullptr;
decltype(&clPollStreams) xcl::Stream::pollStreams = nullptr;
decltype(&xclGetComputeUnitInfo) xcl::Ext::getComputeUnitInfo = nullptr;
auto constexpr c_test_size = 4 * 1024; // 4 KB data
////////MAIN FUNCTION//////////
int main(int argc, char **argv) {
size_t size = c_test_size;
size_t max_length = 2 * size;
bool check_status = 0;
// I/O Data Vectors
std::vector<int, aligned_allocator<int>> h_data(max_length);
std::vector<int, aligned_allocator<int>> read_data(size);
if (argc != 3) {
std::cout << "Usage: " << argv[0] << " <XCLBIN File>"
<< "<an interger> " << std::endl;
return EXIT_FAILURE;
}
auto binaryFile = argv[1];
int foo = atoi(argv[2]);
// Reset the data vector
for (size_t i = 0; i < max_length; i++) {
h_data[i] = i + 1;
}
// OpenCL Setup
// OpenCL objects
cl::Device device;
cl::Context context;
cl::CommandQueue q;
cl::Program program;
cl::Kernel krnl_incr;
// Error Status variable
cl_int err;
// get_xil_devices() is a utility API which will find the xilinx
// platforms and will return list of devices connected to Xilinx platform
auto devices = xcl::get_xil_devices();
// read_binary_file() is a utility API which will load the binaryFile
// and will return the pointer to file buffer.
auto fileBuf = xcl::read_binary_file(binaryFile);
cl::Program::Binaries bins{{fileBuf.data(), fileBuf.size()}};
int valid_device = 0;
for (unsigned int i = 0; i < devices.size(); i++) {
device = devices[i];
// Creating Context and Command Queue for selected Device
OCL_CHECK(err, context = cl::Context(device, NULL, NULL, NULL, &err));
OCL_CHECK(err,
q = cl::CommandQueue(context, device,
CL_QUEUE_PROFILING_ENABLE |
CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,
&err));
std::cout << "Trying to program device[" << i
<< "]: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
cl::Program program(context, {device}, bins, NULL, &err);
if (err != CL_SUCCESS) {
std::cout << "Failed to program device[" << i << "] with xclbin file!\n";
} else {
std::cout << "Device[" << i << "]: program successful!\n";
// Creating Kernel
OCL_CHECK(err, krnl_incr = cl::Kernel(program, "increment", &err));
valid_device++;
break; // we break because we found a valid device
}
}
if (valid_device == 0) {
std::cout << "Failed to program any device found, exit!\n";
exit(EXIT_FAILURE);
}
size_t vector_size_bytes = size * sizeof(int);
auto platform_id = device.getInfo<CL_DEVICE_PLATFORM>(&err);
// Initialization of streaming class is needed before using it.
xcl::Stream::init(platform_id);
xcl::Ext::init(platform_id);
uuid_t xclbinId;
xclbin_uuid(fileBuf.data(), xclbinId);
// Get the device handle
xclDeviceHandle handle;
clGetDeviceInfo(device.get(), CL_DEVICE_HANDLE, sizeof(handle), &handle,
nullptr);
cl_uint cuidx;
xcl::Ext::getComputeUnitInfo(krnl_incr.get(), 0, XCL_COMPUTE_UNIT_INDEX,
sizeof(cuidx), &cuidx, nullptr);
// Get the argument offset
size_t foo_offset = 0;
clGetKernelArgInfo(krnl_incr.get(), 2, CL_KERNEL_ARG_OFFSET,
sizeof(foo_offset), &foo_offset, nullptr);
// Use device handle and offset to write the register value
xclOpenContext(handle, xclbinId, cuidx, false);
xclRegWrite(handle, cuidx, foo_offset, foo);
std::cout << "\nThe register value that is written : " << foo << std::endl;
uint32_t drive_valid = 1;
xclRegWrite(handle, cuidx, foo_offset + sizeof(int), drive_valid);
xclCloseContext(handle, xclbinId, cuidx);
// Streams
// Device Connection specification of the stream through extension pointer
cl_int ret;
cl_mem_ext_ptr_t ext_stream;
ext_stream.param = krnl_incr.get();
ext_stream.obj = NULL;
ext_stream.flags = 1;
// Create write stream for argument 0 and 1 of kernel
cl_stream axis00_stream, axis01_stream;
OCL_CHECK(ret, axis00_stream = xcl::Stream::createStream(
device.get(), XCL_STREAM_WRITE_ONLY, CL_STREAM,
&ext_stream, &ret));
ext_stream.flags = 0;
OCL_CHECK(ret, axis01_stream = xcl::Stream::createStream(
device.get(), XCL_STREAM_READ_ONLY, CL_STREAM, &ext_stream,
&ret));
// Initiating the WRITE transfer
cl_stream_xfer_req wr_req{0};
wr_req.flags = CL_STREAM_EOT;
OCL_CHECK(ret, xcl::Stream::writeStream(axis01_stream, h_data.data(),
vector_size_bytes, &wr_req, &ret));
// Initiating the READ transfer
cl_stream_xfer_req rd_req{0};
rd_req.flags = CL_STREAM_EOT;
OCL_CHECK(ret, xcl::Stream::readStream(axis00_stream, read_data.data(),
vector_size_bytes, &rd_req, &ret));
uint32_t beyond_foo;
size_t beyond_foo_offset = 0;
clGetKernelArgInfo(krnl_incr.get(), 3, CL_KERNEL_ARG_OFFSET,
sizeof(beyond_foo_offset), &beyond_foo_offset, nullptr);
// Use device handle and offset to read the register value
xclOpenContext(handle, xclbinId, cuidx, false);
xclRegRead(handle, cuidx, beyond_foo_offset, &beyond_foo);
std::cout << "\nThe register value that is read : " << beyond_foo << std::endl;
xclCloseContext(handle, xclbinId, cuidx);
for (cl_uint i = 0; i < size; i++) {
if (h_data[i] != read_data[i]) {
check_status = 1;
}
}
int expected_result = size - foo;
std::cout << "\nThe number of data should more than " << foo << " is "
<< expected_result;
std::cout << "\nThe Result coming from hardware is " << beyond_foo
<< std::endl;
if (expected_result == (int)beyond_foo)
std::cout << "\nTEST PASSED\n";
else
std::cout << "\nTEST FAILED\n";
// Ensuring all OpenCL objects are released.
q.finish();
// Releasing Streams
xcl::Stream::releaseStream(axis00_stream);
xcl::Stream::releaseStream(axis01_stream);
return (check_status ? EXIT_FAILURE : EXIT_SUCCESS);
}
| [
"heeran@xilinx.com"
] | heeran@xilinx.com |
1923fb53faa11d714a8695e33a858543a6e2d9fd | df6311ad5d9a7f056b682281feb2bc0a79768f23 | /win.h | cbad0460fdbf1128b34cff909778a7aa1ae0ee78 | [] | no_license | annsngkv/qt-counter | ef5c841451bd0d4e4a4fab11f7d6be77f2740d3c | 95daf517912b4ce9fa7f6a2572fc261e73694203 | refs/heads/master | 2023-04-26T17:36:54.772140 | 2021-05-23T19:15:05 | 2021-05-23T19:15:05 | 367,749,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,250 | h | #ifndef win_h
#define win_h
#include <QtGui>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
/*
* Класс счетчик, наследуемый от QLineEdit
*/
class Counter:public QLineEdit
{
/*
* Обязательный макрос, так как класс Counter определяет новые сигналы и слоты
*/
Q_OBJECT // макрос Qt, обеспечивающий корректное создание сигналов и слотов
public:
/*
* Конструктор класса Counter
*/
Counter(const QString & contents, QWidget *parent=0):
QLineEdit(contents, parent){} // вызов конструктора родительского класса - QLineEdit
signals:
/*
* Объявляем новый сигнал, который будет генерироваться по достижении пяти нажатий
*/
void tick_signal();
public slots:
/*
* метод увеличивающий содержимое на единицу
*/
void add_one() {
/*
* Считываем содержимое счетчика
*/
QString str = text();
/*
* Функция, возвращающая строку, преобразованную в значение типа int
*/
int r = str.toInt();
/*
* Если число нажатий не равно 0 и равно 0 по модулю 5, то генерируем сигнал
*/
if (r != 0 && r % 5 == 0) emit tick_signal();
/*
* Увеличиваем содержимое счетчика
*/
r++;
/*
* Функция, устанавливающая строку в печатное представление числа
*/
str.setNum(r);
/*
* Вставляем полученное значение в счетчик
*/
setText(str);
}
};
/*
* Наследуемся от класса QWidget – базовый класс всех виджетов
*/
class Win: public QWidget
{
Q_OBJECT // макрос Qt, обеспечивающий корректное создание сигналов и слотов
protected:
/*
* Объявляем указатель на объект класса QTextCodec - один из семейства классов, определенных
* для работы с разными, в том числе национальными кодировками в Qt
*/
QTextCodec *codec; // перекодировщик
/*
* Объявляем указатели на объекты класса QLabel - метка – виджет
*/
QLabel *label1, *label2;
/*
* Объявляем указатели на счетчики
*/
Counter *edit1, *edit2;
/*
* Объявляем указатели на объекты класса QPushButton - виджет-кнопка
*/
QPushButton *calcbutton; // кнопка "+1"
QPushButton *exitbutton; // кнопка "Выход"
public:
/*
* Конструктор базового класса QWidget с двумя параметрами
* 1-й параметр - родитель, так как он установлен в 0, то у нашего класса нет родителей
*
* 2-й параметр - флаги – битовая комбинация, отвечающая за тип окна: обычное,
* диалоговое, контекстное меню, панель инструментов, выпадающая подсказка и т.п.
* Так как здесь этот параметр опущен, то он берется по умолчанию – обычное окно.
*/
Win(QWidget *parent = 0);
};
#endif
| [
"snegarkova@yandex.ru"
] | snegarkova@yandex.ru |
f82aeb841d5d5fff61fa51fd958ba933f87cbd4d | 301ed54244fd41502fd6f23a2e016c6e0cfba2dd | /02 CONTESTS/Codechef/LTIME87A/A.cpp | 1d236bdd33adbc7e14882b93f0f6b98aeb6f6fbf | [] | no_license | iCodeIN/Competitive-Programming-4 | 660607a74c4a846340b6fb08316668057f75a7ba | 05b55d2736f6b22758cd57f3ed5093cf8a2f4e2f | refs/heads/master | 2023-02-22T12:53:39.878593 | 2021-01-28T10:57:50 | 2021-01-28T10:57:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,883 | cpp | #include <bits/stdc++.h>
using namespace std;
#define en "\n"
#define INF (int) 9e18
#define HELL (int) (1e9 + 7)
#define int long long
#define double long double
#define uint unsigned long long
#define pii pair<int, int>
#define pb push_back
#define fs first
#define sc second
#define size(a) (int) a.size()
#define deb(x) cerr << #x << " => " << x << en
#define debp(a) cerr << #a << " => " <<"("<<a.fs<<", "<<a.sc<<") " << en;
#define deba(x) cerr << #x << en; for (auto a : x) cerr << a << " "; cerr << en;
#define debpa(x) cerr << #x << en; for (auto a : x)cerr<<"("<<a.fs<<", "<<a.sc<<") "; cerr << en;
#define debm(x) cerr << #x << en; for (auto a : x){for(auto b : a) cerr << b << " "; cerr << en;}
#define getMat(x, n, m, val) vector<vector<int>> x(n, vector<int> (m, val))
#define fastio ios_base :: sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define pout cout << fixed << setprecision(10)
int fastpow(int a, int b, int m = HELL) { int res = 1; a %= m;
while (b > 0) { if (b & 1) res = (res * a) % m; a = (a * a) % m; b >>= 1; } return res;}
#define inv(a) fastpow(a, HELL - 2)
#define mul(a, b) ((a % HELL) * (b % HELL)) % HELL
int32_t main() { fastio;
int t; cin >> t;
while (t--) {
int n; cin >> n;
vector<char> s(n);
for (int i = 0; i < n; i++) cin >> s[i];
vector<int> res;
int prev = 'X';
for (int i = 0; i < n; i++) {
if (prev != s[i]) {
if (s[i] == '0') {
res.pb(0);
}
}
prev = s[i];
if (prev == '0') {
res[size(res) - 1]++;
}
}
sort(res.begin(), res.end(), greater<int>());
if (size(res) == 1) {
if (res[0] & 1) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
} else if (size(res)) {
if ((res[0] & 1) and (res[1] <= (res[0] / 2))) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
} else {
cout << "No" << endl;
}
}
return 0;
} | [
"yashjain0530@gmail.com"
] | yashjain0530@gmail.com |
edc208ccbc4122874a1987a9adb6c5ac85b5cc3b | b03be8c91e696a1f68f9086d5a13dfc4a8cf96bf | /20190427_ABC125/B-Resale.cpp | 5768cfa80a7a6f19b94552c5ee28bfe84d575ad1 | [] | no_license | shimech/AtCoder | 6b4cc9d7b664f29e9d0ec23c344933558a77be1b | 992a36c0a578d4117e5e08275954c51e5cb5037d | refs/heads/main | 2021-07-25T21:01:58.619897 | 2021-06-26T06:36:37 | 2021-06-26T06:36:37 | 182,351,805 | 0 | 0 | null | 2021-06-06T12:58:58 | 2019-04-20T02:49:06 | C++ | UTF-8 | C++ | false | false | 409 | cpp | #include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
int V[N], C[N];
for (int i = 0; i < N; i++) {
cin >> V[i];
}
for (int i = 0; i < N; i++) {
cin >> C[i];
}
int sum = 0;
for (int i = 0; i < N; i++) {
if (V[i] - C[i] > 0) {
sum += V[i] - C[i];
}
else {}
}
cout << sum << endl;
return 0;
}
| [
"ut.s.shimizu@gmail.com"
] | ut.s.shimizu@gmail.com |
58fb24ed5d3083561f774d10fd5cfe58edc1dcc3 | 351a4b2f0cf7e66d1d86ec175c001528cc933b26 | /examples/RenderManagerOpenGLPresentExample.cpp | e8a3443290b3f0bc07fe9f6abd8b8d3d0aadfddf | [
"Apache-2.0"
] | permissive | bwrsandman/OSVR-RenderManager | 831dd1ec30facc57245810f66b1ea9d30695c510 | c22e7e068228b236b1a51094ae32cc34b151d859 | refs/heads/master | 2021-01-17T21:39:51.098718 | 2016-06-12T00:17:55 | 2016-06-12T00:17:55 | 61,181,130 | 1 | 0 | null | 2016-06-15T05:54:08 | 2016-06-15T05:54:08 | null | UTF-8 | C++ | false | false | 14,927 | cpp | /** @file
@brief Example program that uses the OSVR direct-to-display interface
and OpenGL to render a scene with low latency.
@date 2015
@author
Russ Taylor <russ@sensics.com>
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/RenderKit/RenderManager.h>
// Needed for render buffer calls. OSVR will have called glewInit() for us
// when we open the display.
#include <GL/glew.h>
// Library/third-party includes
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
// Standard includes
#include <iostream>
#include <string>
#include <stdlib.h> // For exit()
// This must come after we include <GL/gl.h> so its pointer types are defined.
#include <osvr/RenderKit/GraphicsLibraryOpenGL.h>
// Forward declarations of rendering functions defined below.
void draw_cube(double radius);
// Set to true when it is time for the application to quit.
// Handlers below that set it to true when the user causes
// any of a variety of events so that we shut down the system
// cleanly. This only works on Windows, but so does D3D...
static bool quit = false;
#ifdef _WIN32
// Note: On Windows, this runs in a different thread from
// the main application.
static BOOL CtrlHandler(DWORD fdwCtrlType) {
switch (fdwCtrlType) {
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
quit = true;
return TRUE;
default:
return FALSE;
}
}
#endif
// This callback sets a boolean value whose pointer is passed in to
// the state of the button that was pressed. This lets the callback
// be used to handle any button press that just needs to update state.
void myButtonCallback(void* userdata, const OSVR_TimeValue* /*timestamp*/,
const OSVR_ButtonReport* report) {
bool* result = static_cast<bool*>(userdata);
*result = (report->state != 0);
}
bool SetupRendering(osvr::renderkit::GraphicsLibrary library) {
// Make sure our pointers are filled in correctly. The config file selects
// the graphics library to use, and may not match our needs.
if (library.OpenGL == nullptr) {
std::cerr << "SetupRendering: No OpenGL GraphicsLibrary, this should "
"not happen"
<< std::endl;
return false;
}
osvr::renderkit::GraphicsLibraryOpenGL* glLibrary = library.OpenGL;
// Turn on depth testing, so we get correct ordering.
glEnable(GL_DEPTH_TEST);
return true;
}
// Render the world from the specified point of view.
void RenderView(
const osvr::renderkit::RenderInfo& renderInfo, //< Info needed to render
GLuint frameBuffer, //< Frame buffer object to bind our buffers to
GLuint colorBuffer, //< Color buffer to render into
GLuint depthBuffer //< Depth buffer to render into
) {
// Make sure our pointers are filled in correctly. The config file selects
// the graphics library to use, and may not match our needs.
if (renderInfo.library.OpenGL == nullptr) {
std::cerr
<< "RenderView: No OpenGL GraphicsLibrary, this should not happen"
<< std::endl;
return;
}
// Render to our framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
// Set color and depth buffers for the frame buffer
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorBuffer, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, depthBuffer);
// Set the list of draw buffers.
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers
// Always check that our framebuffer is ok
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
std::cerr << "RenderView: Incomplete Framebuffer" << std::endl;
return;
}
// Set the viewport to cover our entire render texture.
glViewport(0, 0, static_cast<GLsizei>(renderInfo.viewport.width),
static_cast<GLsizei>(renderInfo.viewport.height));
// Set the OpenGL projection matrix
GLdouble projection[16];
osvr::renderkit::OSVR_Projection_to_OpenGL(projection,
renderInfo.projection);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMultMatrixd(projection);
/// Put the transform into the OpenGL ModelView matrix
GLdouble modelView[16];
osvr::renderkit::OSVR_PoseState_to_OpenGL(modelView, renderInfo.pose);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMultMatrixd(modelView);
// Clear the screen to black and clear depth
glClearColor(0, 0, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// =================================================================
// This is where we draw our world and hands and any other objects.
// We're in World Space. To find out about where to render objects
// in OSVR spaces (like left/right hand space) we need to query the
// interface and handle the coordinate tranforms ourselves.
// Draw a cube with a 5-meter radius as the room we are floating in.
draw_cube(5.0);
}
int main(int argc, char* argv[]) {
// Get an OSVR client context to use to access the devices
// that we need.
osvr::clientkit::ClientContext context(
"com.osvr.renderManager.openGLExample");
// Construct button devices and connect them to a callback
// that will set the "quit" variable to true when it is
// pressed. Use button "1" on the left-hand or
// right-hand controller.
osvr::clientkit::Interface leftButton1 =
context.getInterface("/controller/left/1");
leftButton1.registerCallback(&myButtonCallback, &quit);
osvr::clientkit::Interface rightButton1 =
context.getInterface("/controller/right/1");
rightButton1.registerCallback(&myButtonCallback, &quit);
// Open OpenGL and set up the context for rendering to
// an HMD. Do this using the OSVR RenderManager interface,
// which maps to the nVidia or other vendor direct mode
// to reduce the latency.
osvr::renderkit::RenderManager* render =
osvr::renderkit::createRenderManager(context.get(), "OpenGL");
if ((render == nullptr) || (!render->doingOkay())) {
std::cerr << "Could not create RenderManager" << std::endl;
return 1;
}
// Set up a handler to cause us to exit cleanly.
#ifdef _WIN32
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
#endif
// Open the display and make sure this worked.
osvr::renderkit::RenderManager::OpenResults ret = render->OpenDisplay();
if (ret.status == osvr::renderkit::RenderManager::OpenStatus::FAILURE) {
std::cerr << "Could not open display" << std::endl;
delete render;
return 2;
}
// Set up the rendering state we need.
if (!SetupRendering(ret.library)) {
return 3;
}
// Do a call to get the information we need to construct our
// color and depth render-to-texture buffers.
std::vector<osvr::renderkit::RenderInfo> renderInfo;
context.update();
renderInfo = render->GetRenderInfo();
std::vector<osvr::renderkit::RenderBuffer> colorBuffers;
std::vector<GLuint> depthBuffers; //< Depth/stencil buffers to render into
// Construct the buffers we're going to need for our render-to-texture
// code.
GLuint frameBuffer; //< Groups a color buffer and a depth buffer
glGenFramebuffers(1, &frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
for (size_t i = 0; i < renderInfo.size(); i++) {
// The color buffer for this eye. We need to put this into
// a generic structure for the Present function, but we only need
// to fill in the OpenGL portion.
// Note that this must be used to generate a RenderBuffer, not just
// a texture, if we want to be able to present it to be rendered
// via Direct3D for DirectMode. This is selected based on the
// config file value, so we want to be sure to use the more general
// case.
// Note that this texture format must be RGBA and unsigned byte,
// so that we can present it to Direct3D for DirectMode
GLuint colorBufferName = 0;
glGenRenderbuffers(1, &colorBufferName);
osvr::renderkit::RenderBuffer rb;
rb.OpenGL = new osvr::renderkit::RenderBufferOpenGL;
rb.OpenGL->colorBufferName = colorBufferName;
colorBuffers.push_back(rb);
// "Bind" the newly created texture : all future texture
// functions will modify this texture glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, colorBufferName);
// Determine the appropriate size for the frame buffer to be used for
// this eye.
int width = static_cast<int>(renderInfo[i].viewport.width);
int height = static_cast<int>(renderInfo[i].viewport.height);
// Give an empty image to OpenGL ( the last "0" means "empty" )
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
// Bilinear filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// The depth buffer
GLuint depthrenderbuffer;
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width,
height);
depthBuffers.push_back(depthrenderbuffer);
}
// Register our constructed buffers so that we can use them for
// presentation.
if (!render->RegisterRenderBuffers(colorBuffers)) {
std::cerr << "RegisterRenderBuffers() returned false, cannot continue"
<< std::endl;
quit = true;
}
// Continue rendering until it is time to quit.
while (!quit) {
// Update the context so we get our callbacks called and
// update tracker state.
context.update();
renderInfo = render->GetRenderInfo();
// Render into each buffer using the specified information.
for (size_t i = 0; i < renderInfo.size(); i++) {
RenderView(renderInfo[i], frameBuffer,
colorBuffers[i].OpenGL->colorBufferName,
depthBuffers[i]);
}
// Send the rendered results to the screen
if (!render->PresentRenderBuffers(colorBuffers, renderInfo)) {
std::cerr << "PresentRenderBuffers() returned false, maybe because "
"it was asked to quit"
<< std::endl;
quit = true;
}
}
// Clean up after ourselves.
glDeleteFramebuffers(1, &frameBuffer);
for (size_t i = 0; i < renderInfo.size(); i++) {
glDeleteTextures(1, &colorBuffers[i].OpenGL->colorBufferName);
delete colorBuffers[i].OpenGL;
glDeleteRenderbuffers(1, &depthBuffers[i]);
}
// Close the Renderer interface cleanly.
delete render;
return 0;
}
static GLfloat matspec[4] = {0.5, 0.5, 0.5, 0.0};
static float red_col[] = {1.0, 0.0, 0.0};
static float grn_col[] = {0.0, 1.0, 0.0};
static float blu_col[] = {0.0, 0.0, 1.0};
static float yel_col[] = {1.0, 1.0, 0.0};
static float lightblu_col[] = {0.0, 1.0, 1.0};
static float pur_col[] = {1.0, 0.0, 1.0};
void draw_cube(double radius) {
GLfloat matspec[4] = {0.5, 0.5, 0.5, 0.0};
glPushMatrix();
glScaled(radius, radius, radius);
glMaterialfv(GL_FRONT, GL_SPECULAR, matspec);
glMaterialf(GL_FRONT, GL_SHININESS, 64.0);
glBegin(GL_POLYGON);
glColor3fv(lightblu_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, lightblu_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, lightblu_col);
glNormal3f(0.0, 0.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
glEnd();
glBegin(GL_POLYGON);
glColor3fv(blu_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, blu_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, blu_col);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glEnd();
glBegin(GL_POLYGON);
glColor3fv(yel_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, yel_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, yel_col);
glNormal3f(0.0, -1.0, 0.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glEnd();
glBegin(GL_POLYGON);
glColor3fv(grn_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, grn_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, grn_col);
glNormal3f(0.0, 1.0, 0.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, 1.0);
glEnd();
glBegin(GL_POLYGON);
glColor3fv(pur_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pur_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pur_col);
glNormal3f(-1.0, 0.0, 0.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, 1.0);
glEnd();
glBegin(GL_POLYGON);
glColor3fv(red_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, red_col);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red_col);
glNormal3f(1.0, 0.0, 0.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, 1.0, 1.0);
glEnd();
glPopMatrix();
}
| [
"russ@reliasolve.com"
] | russ@reliasolve.com |
82244daf927743fb77f3a6986f41e42b1b623ad6 | cbaefe57f2b4f860745bf84254b30318534c1555 | /SDK/pfc/nix-objects.cpp | e35ed1c805b4d07f3fe86adb4db81ffc1aad4a97 | [
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
] | permissive | topia/foobar2000-sdk | f9b6a4a3d74af3e3f33eb543f70a9434c2c7b219 | f0f995e67e9fc5e36e96f5f6540ea7f8a6c8b964 | refs/heads/master | 2023-06-08T11:23:00.013923 | 2023-06-02T03:47:34 | 2023-06-02T03:47:34 | 238,448,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,970 | cpp | #include "pfc-lite.h"
#ifndef _WIN32
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <poll.h>
#include <math.h>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
#include "nix-objects.h"
#include "string_base.h"
#include "array.h"
#include "debug.h"
#include "timers.h"
#include "filehandle.h"
namespace pfc {
void nixFormatError( string_base & str, int code ) {
char buffer[512] = {};
strerror_r(code, buffer, sizeof(buffer));
str = buffer;
}
void setNonBlocking( int fd, bool bNonBlocking ) {
int flags = fcntl(fd, F_GETFL, 0);
int flags2 = flags;
if (bNonBlocking) flags2 |= O_NONBLOCK;
else flags2 &= ~O_NONBLOCK;
if (flags2 != flags) fcntl(fd, F_SETFL, flags2);
}
void setCloseOnExec( int fd, bool bCloseOnExec ) {
int flags = fcntl(fd, F_GETFD);
int flags2 = flags;
if (bCloseOnExec) flags2 |= FD_CLOEXEC;
else flags2 &= ~FD_CLOEXEC;
if (flags != flags2) fcntl(fd, F_SETFD, flags2);
}
void setInheritable( int fd, bool bInheritable ) {
setCloseOnExec( fd, !bInheritable );
}
void createPipe( int fd[2], bool bInheritable ) {
#if defined(__linux__) && defined(O_CLOEXEC)
if (pipe2(fd, bInheritable ? 0 : O_CLOEXEC) < 0) throw exception_nix();
#else
if (pipe(fd) < 0) throw exception_nix();
if (!bInheritable) {
setInheritable( fd[0], false );
setInheritable( fd[1], false );
}
#endif
}
exception_nix::exception_nix() {
_init(errno);
}
exception_nix::exception_nix(int code) {
_init(code);
}
void exception_nix::_init(int code) {
PFC_ASSERT( code != EINTR );
m_code = code;
nixFormatError(m_msg, code);
}
timeval makeTimeVal( double timeSeconds ) {
timeval tv = {};
uint64_t temp = (uint64_t) floor( timeSeconds * 1000000.0 + 0.5);
tv.tv_usec = (uint32_t) (temp % 1000000);
tv.tv_sec = (uint32_t) (temp / 1000000);
return tv;
}
double importTimeval(const timeval & in) {
return (double)in.tv_sec + (double)in.tv_usec / 1000000.0;
}
void fdSet::operator+=( int fd ) {
m_fds.insert( fd );
}
void fdSet::operator-=( int fd ) {
m_fds.erase(fd);
}
bool fdSet::operator[] (int fd ) {
return m_fds.find( fd ) != m_fds.end();
}
void fdSet::clear() {
m_fds.clear();
}
void fdSet::operator+=( fdSet const & other ) {
for(auto i = other.m_fds.begin(); i != other.m_fds.end(); ++ i ) {
(*this) += *i;
}
}
int fdSelect::Select() {
return Select_( -1 );
}
int fdSelect::Select( double timeOutSeconds ) {
int ms;
if (timeOutSeconds < 0) {
ms = -1;
} else if (timeOutSeconds == 0) {
ms = 0;
} else {
ms = pfc::rint32( timeOutSeconds * 1000 );
if (ms < 1) ms = 1;
}
return Select_( ms );
}
int fdSelect::Select_( int timeOutMS ) {
fdSet total = Reads;
total += Writes;
total += Errors;
const size_t count = total.m_fds.size();
pfc::array_t< pollfd > v;
v.set_size_discard( count );
size_t walk = 0;
for( auto i = total.m_fds.begin(); i != total.m_fds.end(); ++ i ) {
const int fd = *i;
auto & f = v[walk++];
f.fd = fd;
f.events = (Reads[fd] ? POLLIN : 0) | (Writes[fd] ? POLLOUT : 0);
// POLLERR ignored in events, only used in revents
f.revents = 0;
}
hires_timer timer;
int countdown = timeOutMS;
if (countdown > 0) timer.start();
int status;
for ( ;; ) {
status = poll(v.get_ptr(), (int)count, countdown);
if (status >= 0) break;
int e = errno;
if (e == EINTR) {
if (countdown < 0) continue; // infinite
if (countdown > 0) {
countdown = timeOutMS - rint32( timer.query() );
if (countdown > 0) continue;
}
// should not really get here
status = 0;
break;
} else {
throw exception_nix(e);
}
}
Reads.clear(); Writes.clear(); Errors.clear();
if (status > 0) {
for(walk = 0; walk < count; ++walk) {
auto & f = v[walk];
if (f.revents & POLLIN) Reads += f.fd;
if (f.revents & POLLOUT) Writes += f.fd;
if (f.revents & POLLERR) Errors += f.fd;
}
}
return status;
}
bool fdCanRead( int fd ) {
return fdWaitRead( fd, 0 );
}
bool fdCanWrite( int fd ) {
return fdWaitWrite( fd, 0 );
}
bool fdWaitRead( int fd, double timeOutSeconds ) {
fdSelect sel; sel.Reads += fd;
return sel.Select( timeOutSeconds ) > 0;
}
bool fdWaitWrite( int fd, double timeOutSeconds ) {
fdSelect sel; sel.Writes += fd;
return sel.Select( timeOutSeconds ) > 0;
}
nix_event::nix_event(bool state) {
createPipe( m_fd );
setNonBlocking( m_fd[0] );
setNonBlocking( m_fd[1] );
if ( state ) set_state(true);
}
nix_event::~nix_event() {
close( m_fd[0] );
close( m_fd[1] );
}
void nix_event::set_state( bool state ) {
if (state) {
// Ensure that there is a byte in the pipe
if (!fdCanRead(m_fd[0] ) ) {
uint8_t dummy = 0;
write( m_fd[1], &dummy, 1);
}
} else {
// Keep reading until clear
for(;;) {
uint8_t dummy;
if (read(m_fd[0], &dummy, 1 ) != 1) break;
}
}
}
bool nix_event::wait_for( double p_timeout_seconds ) {
return fdWaitRead( m_fd[0], p_timeout_seconds );
}
bool nix_event::g_wait_for( int p_event, double p_timeout_seconds ) {
return fdWaitRead( p_event, p_timeout_seconds );
}
size_t nix_event::g_multiWait( const pfc::eventHandle_t * events, size_t count, double timeout ) {
fdSelect sel;
for( size_t i = 0; i < count; ++ i ) {
sel.Reads += events[i];
}
int state = sel.Select( timeout );
if (state < 0) throw exception_nix();
if (state == 0) return SIZE_MAX;
for( size_t i = 0; i < count; ++ i ) {
if ( sel.Reads[ events[i] ] ) return i;
}
crash(); // should not get here
return SIZE_MAX;
}
size_t nix_event::g_multiWait(std::initializer_list<eventHandle_t> const & arg, double timeout) {
return g_multiWait(arg.begin(), arg.size(), timeout);
}
int nix_event::g_twoEventWait( int h1, int h2, double timeout ) {
fdSelect sel;
sel.Reads += h1;
sel.Reads += h2;
int state = sel.Select( timeout );
if (state < 0) throw exception_nix();
if (state == 0) return 0;
if (sel.Reads[ h1 ] ) return 1;
if (sel.Reads[ h2 ] ) return 2;
crash(); // should not get here
return 0;
}
int nix_event::g_twoEventWait( nix_event & ev1, nix_event & ev2, double timeout ) {
return g_twoEventWait( ev1.get_handle(), ev2.get_handle(), timeout );
}
void nixSleep(double seconds) {
fdSelect sel; sel.Select( seconds );
}
void sleepSeconds(double seconds) {
return nixSleep(seconds);
}
void yield() {
return nixSleep(0.001);
}
double nixGetTime() {
timeval tv = {};
gettimeofday(&tv, NULL);
return importTimeval(tv);
}
tickcount_t getTickCount() {
return rint64(nixGetTime() * 1000.f);
}
bool nixReadSymLink( string_base & strOut, const char * path ) {
size_t l = 1024;
for(;;) {
array_t<char> buffer; buffer.set_size( l + 1 );
ssize_t rv = (size_t) readlink(path, buffer.get_ptr(), l);
if (rv < 0) return false;
if ((size_t)rv <= l) {
buffer.get_ptr()[rv] = 0;
strOut = buffer.get_ptr();
return true;
}
l *= 2;
}
}
bool nixSelfProcessPath( string_base & strOut ) {
#ifdef __APPLE__
uint32_t len = 0;
_NSGetExecutablePath(NULL, &len);
array_t<char> temp; temp.set_size( len + 1 ); temp.fill_null();
_NSGetExecutablePath(temp.get_ptr(), &len);
strOut = temp.get_ptr();
return true;
#else
return nixReadSymLink( strOut, PFC_string_formatter() << "/proc/" << (unsigned) getpid() << "/exe");
#endif
}
void nixGetRandomData( void * outPtr, size_t outBytes ) {
try {
fileHandle randomData;
randomData = open("/dev/urandom", O_RDONLY);
if (randomData.h < 0) throw exception_nix();
if (read(randomData.h, outPtr, outBytes) != outBytes) throw exception_nix();
}
catch (std::exception const & e) {
throw std::runtime_error("getRandomData failure");
}
}
#ifndef __APPLE__ // for Apple they are implemented in Obj-C
bool isShiftKeyPressed() {return false;}
bool isCtrlKeyPressed() {return false;}
bool isAltKeyPressed() {return false;}
#endif
}
void uSleepSeconds( double seconds, bool ) {
pfc::nixSleep( seconds );
}
#endif // _WIN32
| [
"topia@clovery.jp"
] | topia@clovery.jp |
1c1ab1c522118915bf02e61db636f94c4a4d51ce | 64bd2dbc0d2c8f794905e3c0c613d78f0648eefc | /Cpp/SDK/BP_BuoyantStorageBarrel_LockedToWater_functions.cpp | 61264f20eeecf672586c0602ece0ee8bbd016fca | [] | no_license | zanzo420/SoT-Insider-SDK | 37232fa74866031dd655413837813635e93f3692 | 874cd4f4f8af0c58667c4f7c871d2a60609983d3 | refs/heads/main | 2023-06-18T15:48:54.547869 | 2021-07-19T06:02:00 | 2021-07-19T06:02:00 | 387,354,587 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,850 | cpp | // Name: SoT Insider, Version: 1.103.4306.0
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_BuoyantStorageBarrel_LockedToWater.BP_BuoyantStorageBarrel_LockedToWater_C.GetPxActorCapacityForPhysXAggregate
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// unsigned char ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
unsigned char ABP_BuoyantStorageBarrel_LockedToWater_C::GetPxActorCapacityForPhysXAggregate()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_BuoyantStorageBarrel_LockedToWater.BP_BuoyantStorageBarrel_LockedToWater_C.GetPxActorCapacityForPhysXAggregate");
ABP_BuoyantStorageBarrel_LockedToWater_C_GetPxActorCapacityForPhysXAggregate_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function BP_BuoyantStorageBarrel_LockedToWater.BP_BuoyantStorageBarrel_LockedToWater_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_BuoyantStorageBarrel_LockedToWater_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_BuoyantStorageBarrel_LockedToWater.BP_BuoyantStorageBarrel_LockedToWater_C.UserConstructionScript");
ABP_BuoyantStorageBarrel_LockedToWater_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
ed6a5f6d3488c05d4eb67d1b82f7b6e5177eec0e | a1804529be44f876f55143a66396381da743c229 | /code/Others/TernarySearch.cpp | dadd819a7fbcd19bd68161dca97b8ff3faf2eec9 | [] | no_license | dcordb/icpc-reference | 73fc0644e88c87f3447af9aab650f65f8aaf3bdc | 9d2b6e52cd807696e63987092372ee227cf36e6e | refs/heads/master | 2023-03-25T00:58:34.403609 | 2023-03-12T22:54:53 | 2023-03-12T22:54:53 | 214,291,425 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 309 | cpp | //ternary search for minimum (for maximum reverse < operator)
double st = -INF, nd = INF; //domain of function
for(int i = 1; i <= 150; i++) {
double m1 = st + (nd - st) / 3.0;
double m2 = nd - (nd - st) / 3.0;
if(f(m1) < f(m2))
nd = m2;
else st = m1;
}
double res = (st + nd) / 2.0; //optimal point | [
"dcordb97@gmail.com"
] | dcordb97@gmail.com |
530b75ea0f4b29d06042f21e399a52335913cf0a | 12c545c0c8eb79240f43875505bddeffe2018950 | /lantern/src/Contrib/SortVertices/cuda_utils.h | 0dbd4d55aaec3618a98ff997adbe78f7fe70ef4d | [
"MIT"
] | permissive | snapbuy/torch | 9322b8ee7e5ba1a31ac02a9151d4fc587a460ba7 | 8d968099ef78242062d4d301b2fc8364f2de2eb5 | refs/heads/master | 2023-08-26T16:41:10.695600 | 2021-10-19T22:56:58 | 2021-10-19T22:56:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,485 | h | /*
MIT License
Copyright (c) 2020 Lanxiao Li
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef _CUDA_UTILS_H
#define _CUDA_UTILS_H
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <cmath>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#define TOTAL_THREADS 512
inline int opt_n_thread(int work_size){
const int pow_2 = std::log(static_cast<double>(work_size)) / std::log(2.0);
return max(min(1<<pow_2, TOTAL_THREADS), 1);
}
inline dim3 opt_block_config(int x, int y){
const int x_thread = opt_n_thread(x);
const int y_thread = max(min(opt_n_thread(y), TOTAL_THREADS/x_thread), 1);
dim3 block_config(x_thread, y_thread, 1);
return block_config;
}
# define CUDA_CHECK_ERRORS() \
do { \
cudaError_t err = cudaGetLastError(); \
if (cudaSuccess!=err){ \
fprintf(stderr, "CUDA kernel failed : %s\n%s at L:%d in %s\n", \
cudaGetErrorString(err), __PRETTY_FUNCTION__, __LINE__, \
__FILE__); \
exit(-1); \
} \
} while(0) \
#endif | [
"dfalbel@gmail.com"
] | dfalbel@gmail.com |
809b10c5034af885382e0f94950f3f3ba20ac9ee | b2e2b269e930a399d011398c3b9beef19da94d8b | /benchmarks/SpanningForest/Framework/mains/unite_early_ldd.cc | 17d57a08ee136284079168adb70b8da5da58a284 | [
"MIT"
] | permissive | jiangjiaqi6/gbbs | b81df575fdfc2e0b24b9ec7eaafbdd1c3f7390cc | ff372b104e4c66766230ecafd34c2840726aee92 | refs/heads/master | 2023-08-23T15:14:46.536379 | 2021-10-13T18:41:40 | 2021-10-13T18:41:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,101 | cc | // This code is part of the project "Theoretically Efficient Parallel Graph
// Algorithms Can Be Fast and Scalable", presented at Symposium on Parallelism
// in Algorithms and Architectures, 2018.
// Copyright (c) 2018 Laxman Dhulipala, Guy Blelloch, and Julian Shun
//
// 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 "benchmarks/SpanningForest/Framework/framework.h"
#include "benchmarks/SpanningForest/BFSSF/SpanningForest.h"
#include "benchmarks/SpanningForest/common.h"
#include "bench_utils.h"
#include "uf_utils.h"
namespace gbbs {
namespace connectit {
template <class Graph>
void unite_find_compress(Graph& G, int rounds, commandLine& P, sequence<edge>& correct) {
run_multiple_uf_alg<Graph, sample_ldd, unite_early, find_compress>(G, rounds, correct, P);
}
template <class Graph>
void unite_find_naive(Graph& G, int rounds, commandLine& P, sequence<edge>& correct) {
run_multiple_uf_alg<Graph, sample_ldd, unite_early, find_naive>(G, rounds, correct, P);
}
template <class Graph>
void unite_find_atomic_split(Graph& G, int rounds, commandLine& P, sequence<edge>& correct) {
run_multiple_uf_alg<Graph, sample_ldd, unite_early, find_atomic_split>(G, rounds, correct, P);
}
template <class Graph>
void unite_find_atomic_halve(Graph& G, int rounds, commandLine& P, sequence<edge>& correct) {
run_multiple_uf_alg<Graph, sample_ldd, unite_early, find_atomic_halve>(G, rounds, correct, P);
}
}
template <class Graph>
double Benchmark_runner(Graph& G, commandLine P) {
int test_num = P.getOptionIntValue("-t", -1);
int rounds = P.getOptionIntValue("-r", 5);
auto correct = sequence<edge>();
if (P.getOptionValue("-check")) {
correct = bfs_sf::SpanningForestDet(G);
}
run_tests(G, rounds, P, correct, connectit::unite_find_naive<Graph>,
{
connectit::unite_find_compress<Graph>,
connectit::unite_find_naive<Graph>,
connectit::unite_find_atomic_split<Graph>,
connectit::unite_find_atomic_halve<Graph>
});
return 1.0;
}
} // namespace gbbs
generate_symmetric_once_main(gbbs::Benchmark_runner, false);
| [
"laxmandhulipala@gmail.com"
] | laxmandhulipala@gmail.com |
040772402f5353c36c63e9c32db6fce200c880cf | 8856f444618e0bbdd821ecda3bcca7f3fc9abd34 | /Enemy.cpp | 8d9923c97ee9aca93730ada03b8bddfde053f02b | [] | no_license | jGold6001/2DEasyGameByQt | f0d9ad643fd08b4b28abf9b7115954d1d74cd1a5 | 22bccbc191191688e3abbb9430421a0a61b4f4ba | refs/heads/master | 2021-08-16T07:50:38.809808 | 2017-11-19T09:24:18 | 2017-11-19T09:24:18 | 111,280,192 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 859 | cpp | #include "using_libs.h"
#include "Enemy.h"
#include "Game.h"
extern Game * game;
Enemy::Enemy(QGraphicsItem *parent): QObject(), QGraphicsPixmapItem(parent){
//set random position
int random_number = rand() % 700;
setPos(random_number,0);
//draw the enemyCar
setPixmap(QPixmap(":/images/images/car2.png"));
setTransformOriginPoint(60,50);//устанавливает отступы обьекта от края окна программы
setRotation(180);//разворот изображения
//connect
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),this, SLOT(move()));
timer->start(50);
}
void Enemy::move(){
//move enemy down
setPos(x(),y()+5);
if(pos().y() > 600){
game->health->decrease();
scene()->removeItem(this);
delete this;
}
}
| [
"jgold6001@gmail.com"
] | jgold6001@gmail.com |
2317780ce50ff3ed2872c79f618c5ecb92ee92b0 | 8fca8c6b8c324f9a3a0cd842a41ac88e4c138d94 | /zipeg-mac/p7z/p7z/CPP/7zip/Archive/Zip/ZipHandler.cpp | 8dc1af2977737805b8fa54b192ccfa0f5f358b64 | [] | no_license | leok7v/zipeg | 98ef829ae7cbfb9091558b9abc4f7beed77059d7 | 10bdd8af188526246eeb8fc25040bff689e13d0d | refs/heads/master | 2021-05-28T01:10:08.737491 | 2013-11-06T18:18:41 | 2013-11-06T18:18:41 | 11,702,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,409 | cpp | // ZipHandler.cpp
#include "StdAfx.h"
#include "Common/ComTry.h"
#include "Common/IntToString.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../../IPassword.h"
#include "../../Common/FilterCoder.h"
#include "../../Common/ProgressUtils.h"
#include "../../Common/StreamObjects.h"
#include "../../Common/StreamUtils.h"
#include "../../Compress/CopyCoder.h"
#include "../../Compress/LzmaDecoder.h"
#include "../../Compress/ImplodeDecoder.h"
#include "../../Compress/PpmdZip.h"
#include "../../Compress/ShrinkDecoder.h"
#include "../../Crypto/WzAes.h"
#include "../../Crypto/ZipCrypto.h"
#include "../../Crypto/ZipStrong.h"
#include "../Common/ItemNameUtils.h"
#include "../Common/OutStreamWithCRC.h"
#include "ZipHandler.h"
using namespace NWindows;
namespace NArchive {
namespace NZip {
static const CMethodId kMethodId_ZipBase = 0x040100;
static const CMethodId kMethodId_BZip2 = 0x040202;
static const char *kHostOS[] =
{
"FAT",
"AMIGA",
"VMS",
"Unix",
"VM/CMS",
"Atari",
"HPFS",
"Macintosh",
"Z-System",
"CP/M",
"TOPS-20",
"NTFS",
"SMS/QDOS",
"Acorn",
"VFAT",
"MVS",
"BeOS",
"Tandem",
"OS/400",
"OS/X"
};
static const char *kUnknownOS = "Unknown";
static const char *kMethods[] =
{
"Store",
"Shrink",
"Reduced1",
"Reduced2",
"Reduced3",
"Reduced4",
"Implode",
"Tokenizing",
"Deflate",
"Deflate64",
"PKImploding"
};
static const char *kBZip2Method = "BZip2";
static const char *kLZMAMethod = "LZMA";
static const char *kJpegMethod = "Jpeg";
static const char *kWavPackMethod = "WavPack";
static const char *kPPMdMethod = "PPMd";
static const char *kAESMethod = "AES";
static const char *kZipCryptoMethod = "ZipCrypto";
static const char *kStrongCryptoMethod = "StrongCrypto";
static struct CStrongCryptoPair
{
UInt16 Id;
const char *Name;
} g_StrongCryptoPairs[] =
{
{ NStrongCryptoFlags::kDES, "DES" },
{ NStrongCryptoFlags::kRC2old, "RC2a" },
{ NStrongCryptoFlags::k3DES168, "3DES-168" },
{ NStrongCryptoFlags::k3DES112, "3DES-112" },
{ NStrongCryptoFlags::kAES128, "pkAES-128" },
{ NStrongCryptoFlags::kAES192, "pkAES-192" },
{ NStrongCryptoFlags::kAES256, "pkAES-256" },
{ NStrongCryptoFlags::kRC2, "RC2" },
{ NStrongCryptoFlags::kBlowfish, "Blowfish" },
{ NStrongCryptoFlags::kTwofish, "Twofish" },
{ NStrongCryptoFlags::kRC4, "RC4" }
};
static STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidATime, VT_FILETIME},
{ NULL, kpidAttrib, VT_UI4},
{ NULL, kpidEncrypted, VT_BOOL},
{ NULL, kpidComment, VT_BSTR},
{ NULL, kpidCRC, VT_UI4},
{ NULL, kpidMethod, VT_BSTR},
{ NULL, kpidHostOS, VT_BSTR},
{ NULL, kpidUnpackVer, VT_UI4}
};
static STATPROPSTG kArcProps[] =
{
{ NULL, kpidBit64, VT_BOOL},
{ NULL, kpidComment, VT_BSTR},
{ NULL, kpidPhySize, VT_UI8},
{ NULL, kpidOffset, VT_UI8}
};
CHandler::CHandler()
{
InitMethodProperties();
}
static AString BytesToString(const CByteBuffer &data)
{
AString s;
int size = (int)data.GetCapacity();
if (size > 0)
{
char *p = s.GetBuffer(size + 1);
memcpy(p, (const Byte *)data, size);
p[size] = '\0';
s.ReleaseBuffer();
}
return s;
}
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
switch(propID)
{
case kpidBit64: if (m_Archive.IsZip64) prop = m_Archive.IsZip64; break;
case kpidComment: prop = MultiByteToUnicodeString(BytesToString(m_Archive.ArcInfo.Comment), CP_ACP); break;
case kpidPhySize: prop = m_Archive.ArcInfo.GetPhySize(); break;
case kpidOffset: if (m_Archive.ArcInfo.StartPosition != 0) prop = m_Archive.ArcInfo.StartPosition; break;
}
prop.Detach(value);
COM_TRY_END
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = m_Items.Size();
return S_OK;
}
STDMETHODIMP CHandler::SetEncoding(Int32 e) {
_encoding = e;
return S_OK;
}
STDMETHODIMP CHandler::GetItemName(UInt32 index, const char* &buf) {
COM_TRY_BEGIN
const CItemEx &item = m_Items[index];
buf = item.Name;
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CItemEx &item = m_Items[index];
switch(propID)
{
case kpidPath: prop = NItemName::GetOSName2(item.GetUnicodeString(item.Name, _encoding)); break;
case kpidIsDir: prop = item.IsDir(); break;
case kpidSize: prop = item.UnPackSize; break;
case kpidPackSize: prop = item.PackSize; break;
case kpidTimeType:
{
FILETIME ft;
UInt32 unixTime;
if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kMTime, ft))
prop = (UInt32)NFileTimeType::kWindows;
else if (item.CentralExtra.GetUnixTime(NFileHeader::NUnixTime::kMTime, unixTime))
prop = (UInt32)NFileTimeType::kUnix;
else
prop = (UInt32)NFileTimeType::kDOS;
break;
}
case kpidCTime:
{
FILETIME ft;
if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kCTime, ft))
prop = ft;
break;
}
case kpidATime:
{
FILETIME ft;
if (item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kATime, ft))
prop = ft;
break;
}
case kpidMTime:
{
FILETIME utc;
if (!item.CentralExtra.GetNtfsTime(NFileHeader::NNtfsExtra::kMTime, utc))
{
UInt32 unixTime;
if (item.CentralExtra.GetUnixTime(NFileHeader::NUnixTime::kMTime, unixTime))
NTime::UnixTimeToFileTime(unixTime, utc);
else
{
FILETIME localFileTime;
if (!NTime::DosTimeToFileTime(item.Time, localFileTime) ||
!LocalFileTimeToFileTime(&localFileTime, &utc))
utc.dwHighDateTime = utc.dwLowDateTime = 0;
}
}
prop = utc;
break;
}
case kpidAttrib: prop = item.GetWinAttributes(); break;
case kpidEncrypted: prop = item.IsEncrypted(); break;
case kpidComment: prop = item.GetUnicodeString(BytesToString(item.Comment), _encoding); break;
case kpidCRC: if (item.IsThereCrc()) prop = item.FileCRC; break;
case kpidMethod:
{
UInt16 methodId = item.CompressionMethod;
AString method;
if (item.IsEncrypted())
{
if (methodId == NFileHeader::NCompressionMethod::kWzAES)
{
method = kAESMethod;
CWzAesExtraField aesField;
if (item.CentralExtra.GetWzAesField(aesField))
{
method += '-';
char s[32];
ConvertUInt64ToString((aesField.Strength + 1) * 64 , s);
method += s;
method += ' ';
methodId = aesField.Method;
}
}
else
{
if (item.IsStrongEncrypted())
{
CStrongCryptoField f;
bool finded = false;
if (item.CentralExtra.GetStrongCryptoField(f))
{
for (int i = 0; i < sizeof(g_StrongCryptoPairs) / sizeof(g_StrongCryptoPairs[0]); i++)
{
const CStrongCryptoPair &pair = g_StrongCryptoPairs[i];
if (f.AlgId == pair.Id)
{
method += pair.Name;
finded = true;
break;
}
}
}
if (!finded)
method += kStrongCryptoMethod;
}
else
method += kZipCryptoMethod;
method += ' ';
}
}
if (methodId < sizeof(kMethods) / sizeof(kMethods[0]))
method += kMethods[methodId];
else switch (methodId)
{
case NFileHeader::NCompressionMethod::kLZMA:
method += kLZMAMethod;
if (item.IsLzmaEOS())
method += ":EOS";
break;
case NFileHeader::NCompressionMethod::kBZip2: method += kBZip2Method; break;
case NFileHeader::NCompressionMethod::kJpeg: method += kJpegMethod; break;
case NFileHeader::NCompressionMethod::kWavPack: method += kWavPackMethod; break;
case NFileHeader::NCompressionMethod::kPPMd: method += kPPMdMethod; break;
default:
{
char s[32];
ConvertUInt64ToString(methodId, s);
method += s;
}
}
prop = method;
break;
}
case kpidHostOS:
prop = (item.MadeByVersion.HostOS < sizeof(kHostOS) / sizeof(kHostOS[0])) ?
(kHostOS[item.MadeByVersion.HostOS]) : kUnknownOS;
break;
case kpidUnpackVer:
prop = (UInt32)item.ExtractVersion.Version;
break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
class CProgressImp: public CProgressVirt
{
CMyComPtr<IArchiveOpenCallback> _callback;
public:
STDMETHOD(SetTotal)(UInt64 numFiles);
STDMETHOD(SetCompleted)(UInt64 numFiles);
CProgressImp(IArchiveOpenCallback *callback): _callback(callback) {}
};
STDMETHODIMP CProgressImp::SetTotal(UInt64 numFiles)
{
if (_callback)
return _callback->SetTotal(&numFiles, NULL);
return S_OK;
}
STDMETHODIMP CProgressImp::SetCompleted(UInt64 numFiles)
{
if (_callback)
return _callback->SetCompleted(&numFiles, NULL);
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
try
{
Close();
RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL));
RINOK(m_Archive.Open(inStream, maxCheckStartPosition));
CProgressImp progressImp(callback);
return m_Archive.ReadHeaders(m_Items, &progressImp);
}
catch(const CInArchiveException &) { Close(); return S_FALSE; }
catch(...) { Close(); throw; }
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
m_Items.Clear();
m_Archive.Close();
return S_OK;
}
//////////////////////////////////////
// CHandler::DecompressItems
class CLzmaDecoder:
public ICompressCoder,
public CMyUnknownImp
{
NCompress::NLzma::CDecoder *DecoderSpec;
CMyComPtr<ICompressCoder> Decoder;
public:
CLzmaDecoder();
STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
MY_UNKNOWN_IMP
};
CLzmaDecoder::CLzmaDecoder()
{
DecoderSpec = new NCompress::NLzma::CDecoder;
Decoder = DecoderSpec;
}
HRESULT CLzmaDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)
{
Byte buf[9];
RINOK(ReadStream_FALSE(inStream, buf, 9));
if (buf[2] != 5 || buf[3] != 0)
return E_NOTIMPL;
RINOK(DecoderSpec->SetDecoderProperties2(buf + 4, 5));
return Decoder->Code(inStream, outStream, NULL, outSize, progress);
}
struct CMethodItem
{
UInt16 ZipMethod;
CMyComPtr<ICompressCoder> Coder;
};
class CZipDecoder
{
NCrypto::NZip::CDecoder *_zipCryptoDecoderSpec;
NCrypto::NZipStrong::CDecoder *_pkAesDecoderSpec;
NCrypto::NWzAes::CDecoder *_wzAesDecoderSpec;
CMyComPtr<ICompressFilter> _zipCryptoDecoder;
CMyComPtr<ICompressFilter> _pkAesDecoder;
CMyComPtr<ICompressFilter> _wzAesDecoder;
CFilterCoder *filterStreamSpec;
CMyComPtr<ISequentialInStream> filterStream;
CMyComPtr<ICryptoGetTextPassword> getTextPassword;
CObjectVector<CMethodItem> methodItems;
public:
CZipDecoder():
_zipCryptoDecoderSpec(0),
_pkAesDecoderSpec(0),
_wzAesDecoderSpec(0),
filterStreamSpec(0) {}
HRESULT Decode(
DECL_EXTERNAL_CODECS_LOC_VARS
CInArchive &archive, const CItemEx &item,
ISequentialOutStream *realOutStream,
IArchiveExtractCallback *extractCallback,
ICompressProgressInfo *compressProgress,
UInt32 numThreads, Int32 &res);
};
HRESULT CZipDecoder::Decode(
DECL_EXTERNAL_CODECS_LOC_VARS
CInArchive &archive, const CItemEx &item,
ISequentialOutStream *realOutStream,
IArchiveExtractCallback *extractCallback,
ICompressProgressInfo *compressProgress,
UInt32 numThreads, Int32 &res)
{
res = NExtract::NOperationResult::kDataError;
CInStreamReleaser inStreamReleaser;
bool needCRC = true;
bool wzAesMode = false;
bool pkAesMode = false;
UInt16 methodId = item.CompressionMethod;
if (item.IsEncrypted())
{
if (item.IsStrongEncrypted())
{
CStrongCryptoField f;
if (item.CentralExtra.GetStrongCryptoField(f))
{
pkAesMode = true;
}
if (!pkAesMode)
{
res = NExtract::NOperationResult::kUnSupportedMethod;
return S_OK;
}
}
if (methodId == NFileHeader::NCompressionMethod::kWzAES)
{
CWzAesExtraField aesField;
if (item.CentralExtra.GetWzAesField(aesField))
{
wzAesMode = true;
needCRC = aesField.NeedCrc();
}
}
}
COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC;
CMyComPtr<ISequentialOutStream> outStream = outStreamSpec;
outStreamSpec->SetStream(realOutStream);
outStreamSpec->Init(needCRC);
UInt64 authenticationPos;
CMyComPtr<ISequentialInStream> inStream;
{
UInt64 packSize = item.PackSize;
if (wzAesMode)
{
if (packSize < NCrypto::NWzAes::kMacSize)
return S_OK;
packSize -= NCrypto::NWzAes::kMacSize;
}
UInt64 dataPos = item.GetDataPosition();
inStream.Attach(archive.CreateLimitedStream(dataPos, packSize));
authenticationPos = dataPos + packSize;
}
CMyComPtr<ICompressFilter> cryptoFilter;
if (item.IsEncrypted())
{
if (wzAesMode)
{
CWzAesExtraField aesField;
if (!item.CentralExtra.GetWzAesField(aesField))
return S_OK;
methodId = aesField.Method;
if (!_wzAesDecoder)
{
_wzAesDecoderSpec = new NCrypto::NWzAes::CDecoder;
_wzAesDecoder = _wzAesDecoderSpec;
}
cryptoFilter = _wzAesDecoder;
Byte properties = aesField.Strength;
RINOK(_wzAesDecoderSpec->SetDecoderProperties2(&properties, 1));
}
else if (pkAesMode)
{
if (!_pkAesDecoder)
{
_pkAesDecoderSpec = new NCrypto::NZipStrong::CDecoder;
_pkAesDecoder = _pkAesDecoderSpec;
}
cryptoFilter = _pkAesDecoder;
}
else
{
if (!_zipCryptoDecoder)
{
_zipCryptoDecoderSpec = new NCrypto::NZip::CDecoder;
_zipCryptoDecoder = _zipCryptoDecoderSpec;
}
cryptoFilter = _zipCryptoDecoder;
}
CMyComPtr<ICryptoSetPassword> cryptoSetPassword;
RINOK(cryptoFilter.QueryInterface(IID_ICryptoSetPassword, &cryptoSetPassword));
if (!getTextPassword)
extractCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getTextPassword);
if (getTextPassword)
{
UString password;
RINOK(getTextPassword->CryptoGetTextPassword(password));
AString charPassword;
if (wzAesMode || pkAesMode)
{
charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_ACP);
}
else
{
// we use OEM. WinZip/Windows probably use ANSI for some files
charPassword = UnicodeStringToMultiByte((const wchar_t *)password, CP_OEMCP);
}
HRESULT result = cryptoSetPassword->CryptoSetPassword(
(const Byte *)(const char *)charPassword, charPassword.Length());
if (result != S_OK)
return S_OK;
}
else
{
RINOK(cryptoSetPassword->CryptoSetPassword(0, 0));
}
}
int m;
for (m = 0; m < methodItems.Size(); m++)
if (methodItems[m].ZipMethod == methodId)
break;
if (m == methodItems.Size())
{
CMethodItem mi;
mi.ZipMethod = methodId;
if (methodId == NFileHeader::NCompressionMethod::kStored)
mi.Coder = new NCompress::CCopyCoder;
else if (methodId == NFileHeader::NCompressionMethod::kShrunk)
mi.Coder = new NCompress::NShrink::CDecoder;
else if (methodId == NFileHeader::NCompressionMethod::kImploded)
mi.Coder = new NCompress::NImplode::NDecoder::CCoder;
else if (methodId == NFileHeader::NCompressionMethod::kLZMA)
mi.Coder = new CLzmaDecoder;
else if (methodId == NFileHeader::NCompressionMethod::kPPMd)
mi.Coder = new NCompress::NPpmdZip::CDecoder(true);
else
{
CMethodId szMethodID;
if (methodId == NFileHeader::NCompressionMethod::kBZip2)
szMethodID = kMethodId_BZip2;
else
{
if (methodId > 0xFF)
{
res = NExtract::NOperationResult::kUnSupportedMethod;
return S_OK;
}
szMethodID = kMethodId_ZipBase + (Byte)methodId;
}
RINOK(CreateCoder(EXTERNAL_CODECS_LOC_VARS szMethodID, mi.Coder, false));
if (mi.Coder == 0)
{
res = NExtract::NOperationResult::kUnSupportedMethod;
return S_OK;
}
}
m = methodItems.Add(mi);
}
ICompressCoder *coder = methodItems[m].Coder;
{
CMyComPtr<ICompressSetDecoderProperties2> setDecoderProperties;
coder->QueryInterface(IID_ICompressSetDecoderProperties2, (void **)&setDecoderProperties);
if (setDecoderProperties)
{
Byte properties = (Byte)item.Flags;
RINOK(setDecoderProperties->SetDecoderProperties2(&properties, 1));
}
}
#ifndef _7ZIP_ST
{
CMyComPtr<ICompressSetCoderMt> setCoderMt;
coder->QueryInterface(IID_ICompressSetCoderMt, (void **)&setCoderMt);
if (setCoderMt)
{
RINOK(setCoderMt->SetNumberOfThreads(numThreads));
}
}
#endif
{
HRESULT result = S_OK;
CMyComPtr<ISequentialInStream> inStreamNew;
if (item.IsEncrypted())
{
if (!filterStream)
{
filterStreamSpec = new CFilterCoder;
filterStream = filterStreamSpec;
}
filterStreamSpec->Filter = cryptoFilter;
if (wzAesMode)
{
result = _wzAesDecoderSpec->ReadHeader(inStream);
}
else if (pkAesMode)
{
result =_pkAesDecoderSpec->ReadHeader(inStream, item.FileCRC, item.UnPackSize);
if (result == S_OK)
{
bool passwOK;
result = _pkAesDecoderSpec->CheckPassword(passwOK);
if (result == S_OK && !passwOK)
result = S_FALSE;
}
}
else
{
result = _zipCryptoDecoderSpec->ReadHeader(inStream);
}
if (result == S_OK)
{
RINOK(filterStreamSpec->SetInStream(inStream));
inStreamReleaser.FilterCoder = filterStreamSpec;
inStreamNew = filterStream;
if (wzAesMode)
{
if (!_wzAesDecoderSpec->CheckPasswordVerifyCode())
result = S_FALSE;
}
}
}
else
inStreamNew = inStream;
if (result == S_OK)
result = coder->Code(inStreamNew, outStream, NULL, &item.UnPackSize, compressProgress);
if (result == S_FALSE)
return S_OK;
if (result == E_NOTIMPL)
{
res = NExtract::NOperationResult::kUnSupportedMethod;
return S_OK;
}
RINOK(result);
}
bool crcOK = true;
bool authOk = true;
if (needCRC)
crcOK = (outStreamSpec->GetCRC() == item.FileCRC);
if (wzAesMode)
{
inStream.Attach(archive.CreateLimitedStream(authenticationPos, NCrypto::NWzAes::kMacSize));
if (_wzAesDecoderSpec->CheckMac(inStream, authOk) != S_OK)
authOk = false;
}
if (!authOk) {
res = NExtract::NOperationResult::kAuthError;
} else if (!crcOK) {
res = NExtract::NOperationResult::kCRCError;
} else {
res = NExtract::NOperationResult::kOK;
}
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
CZipDecoder myDecoder;
UInt64 totalUnPacked = 0, totalPacked = 0;
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = m_Items.Size();
if(numItems == 0)
return S_OK;
UInt32 i;
for (i = 0; i < numItems; i++)
{
const CItemEx &item = m_Items[allFilesMode ? i : indices[i]];
totalUnPacked += item.UnPackSize;
totalPacked += item.PackSize;
}
RINOK(extractCallback->SetTotal(totalUnPacked));
UInt64 currentTotalUnPacked = 0, currentTotalPacked = 0;
UInt64 currentItemUnPacked, currentItemPacked;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
for (i = 0; i < numItems; i++, currentTotalUnPacked += currentItemUnPacked,
currentTotalPacked += currentItemPacked)
{
currentItemUnPacked = 0;
currentItemPacked = 0;
lps->InSize = currentTotalPacked;
lps->OutSize = currentTotalUnPacked;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
CItemEx item = m_Items[index];
if (!item.FromLocal)
{
HRESULT res = m_Archive.ReadLocalItemAfterCdItem(item);
if (res == S_FALSE)
{
if (item.IsDir() || realOutStream || testMode)
{
RINOK(extractCallback->PrepareOperation(askMode));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
}
continue;
}
RINOK(res);
}
if (item.IsDir() || item.IgnoreItem())
{
// if (!testMode)
{
RINOK(extractCallback->PrepareOperation(askMode));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
}
continue;
}
currentItemUnPacked = item.UnPackSize;
currentItemPacked = item.PackSize;
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
Int32 res = 0;
RINOK(myDecoder.Decode(
EXTERNAL_CODECS_VARS
m_Archive, item, realOutStream, extractCallback,
progress, _numThreads, res));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(res))
}
return S_OK;
COM_TRY_END
}
IMPL_ISetCompressCodecsInfo
}}
| [
"leo.kuznetsov@gmail.com"
] | leo.kuznetsov@gmail.com |
46294477b577a9f3f071d0486e106a594deb318f | 05bc027e448301357f54be1d7a60712307eef259 | /include/Key.h | f23d886c25201d989f698cf55e41862ac71243a0 | [] | no_license | mgoetschius/Platformer1 | 54f72d7015ad509c8b22df376c3b3a901329edfc | 0a2887b924c0433140bc2f13a3aaaebe5f8ae8f7 | refs/heads/master | 2021-01-02T22:17:28.899591 | 2015-05-10T00:59:30 | 2015-05-10T00:59:30 | 30,471,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | #ifndef KEY_HH
#define KEY_HH
#include "Shader.h"
#include "Texture.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "vector"
class Key
{
public:
Key();
void Setup(Shader &shader, int x, int y, int size);
void render();
virtual ~Key();
protected:
private:
void SetupMesh(const char *filename, int size);
int xPos, yPos;
GLuint transUniform;
GLuint vao, vbo, tbo;
glm::vec3 translation, rotation, scale;
glm::mat4 transMatrix;
float rotationAmount;
Texture *texture;
std::vector<std::vector<float>> texCoords;
};
#endif // KEY_HH
| [
"mgoetschius@googlemail.com"
] | mgoetschius@googlemail.com |
139465221125b90a9427078c718004046368cc91 | 830541d9198c2151c1325d1ad98dd10f9c245805 | /test/stable_sort.cpp | dd150daddc49c36092eb5b019d3a240ae1b2ac3f | [] | no_license | colinhp/MiniSearchEngine | f0cc818d32ec1bae4115dab3798cde79a8e1d252 | dbae31ca2915115f2045a5962bf37652b54e9091 | refs/heads/master | 2021-10-30T08:19:40.532150 | 2019-04-26T02:28:53 | 2019-04-26T02:28:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | cpp | ///
/// @file stable_sort.cpp
/// @author kkmjy(mjy332528@163.com)
/// @date 2017-09-06 10:02:57
///
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Employee
{
Employee(int age, std::string name)
: age(age)
, name(name)
{ }
int age;
std::string name; // Does not participate in comparisons
};
struct Compare
{
bool operator()(const Employee &lhs, const Employee &rhs)
{
if(lhs.age > rhs.age)
return true;
else
return false;
}
}cmp;
int main()
{
std::vector<Employee> v = {
Employee(108, "Zaphod"),
Employee(32, "Arthur"),
Employee(108, "Ford"),
};
std::stable_sort(v.begin(), v.end(),cmp);
for (const Employee &e : v) {
std::cout << e.age << ", " << e.name << '\n';
}
}
| [
"mjy332528@163.com"
] | mjy332528@163.com |
54c80f7524e37c6fd59992629fd54785613d2292 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_3869_squid-3.1.23.cpp | 2227e9bb9bb2d6cf819569390ed81172a5571872 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | void
Adaptation::Ecap::XactionRep::noteMoreBodyDataAvailable(RefCount<BodyPipe> bp)
{
Must(proxyingVb == opOn);
Must(theMaster);
theMaster->noteVbContentAvailable();
} | [
"993273596@qq.com"
] | 993273596@qq.com |
b285f1f8ef80adccb599399700e45a2d5dbfb609 | 2348000ede440b3513010c29a154ca70b22eb88e | /src/CPP/src/leetcode/CombinationSumIII.cpp | 0908bc160c754af94b3067bdec2d91b4c921732c | [] | no_license | ZhenyingZhu/ClassicAlgorithms | 76438e02ecc813b75646df87f56d9588ffa256df | 86c90c23ea7ed91e8ce5278f334f0ce6e034a38c | refs/heads/master | 2023-08-27T20:34:18.427614 | 2023-08-25T06:08:00 | 2023-08-25T06:08:00 | 24,016,875 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | cpp | /*
* [Source] https://leetcode.com/problems/combination-sum-iii/
* [Difficulty]: Medium
* [Tag]: Array
* [Tag]: Backtracking
*/
#include <iostream>
#include <vector>
using namespace std;
// [Solution]:
// [Corner Case]:
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> res;
vector<int> partial;
sumHelper(1, partial, k, n, res);
return res;
}
void sumHelper(int st, vector<int>& partial, int size, int sum, vector<vector<int>>& res) {
if ((int)partial.size() == size - 1) {
if (sum >= st && sum <= 9) {
partial.push_back(sum);
res.push_back(partial);
partial.pop_back();
}
return;
}
for (int i = st; i < sum; ++i) {
partial.push_back(i);
sumHelper(i + 1, partial, size, sum - i, res);
partial.pop_back();
}
}
};
// [Solution]:
/* Java solution
*/
int main() {
Solution sol;
//vector<vector<int>> res = sol.combinationSum3(3, 7);
vector<vector<int>> res = sol.combinationSum3(3, 9);
for (vector<int>& vec : res) {
for (int& num : vec)
cout << num << " ";
cout << endl;
}
return 0;
}
| [
"zz2283@columbia.edu"
] | zz2283@columbia.edu |
7020aeaa16d7c68d58d4e50d007037c6171ec848 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/LArCalorimeter/LArG4/LArG4EC/src/LArEndcapPresamplerCalculator.cc | c6ed07a808cf6a3aaa4aea88336ec62291cd99bb | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,755 | cc | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// LArEndcapPresamplerCalculator
// 27-Dec-2002 Bill Seligman
// This singleton class provides detector-description information and
// calculations for the Geant4 simulation.
// 2-July-2003 Mikhail Leltchouk: local coordinates for determination
// of etaBin, phiBin at any Endcap Presamplerposition.
// 17-Aug-2004 WGS: Use a "common geometry" routine for both the
// standard calculator and the calibration hits.
#include "LArEndcapPresamplerCalculator.h"
#include "LArG4EC/IECPresamplerGeometry.h"
#include "LArG4Code/LArG4Identifier.h"
#include "LArG4Code/LArVG4DetectorParameters.h"
#include "LArG4Code/LArG4BirksLaw.h"
#include "G4ThreeVector.hh"
#include "G4StepPoint.hh"
#include "G4Step.hh"
#include "G4AffineTransform.hh"
#include "G4NavigationHistory.hh"
#include "G4VTouchable.hh"
#include "G4TouchableHistory.hh"
#include "GaudiKernel/ISvcLocator.h"
#include "GaudiKernel/Bootstrap.h"
#include "StoreGate/StoreGateSvc.h"
#include "globals.hh"
#include "AthenaKernel/Units.h"
// 03-Jan-2002 WGS: For 'copysign'.
#include <cmath>
#include <climits>
namespace Units = Athena::Units;
LArEndcapPresamplerCalculator::LArEndcapPresamplerCalculator(const std::string& name, ISvcLocator *pSvcLocator)
: LArCalculatorSvcImp(name, pSvcLocator)
, m_geometry("EMECPresamplerGeometry", name) // LArG4::EC::PresamplerGeometry
, m_birksLaw(nullptr)
{
declareProperty("GeometryCalculator", m_geometry);
}
StatusCode LArEndcapPresamplerCalculator::initialize()
{
if(m_BirksLaw)
{
const double Birks_LAr_density = 1.396;
m_birksLaw = new LArG4BirksLaw(Birks_LAr_density,m_Birksk);
ATH_MSG_INFO(" LArEndcapPresamplerCalculator: Birks' law ON ");
ATH_MSG_INFO(" LArEndcapPresamplerCalculator: parameter k " << m_birksLaw->k());
}
else
{
ATH_MSG_INFO(" LArEndcapPresamplerCalculator: Birks' law OFF");
}
// Get the geometry routine.
ATH_CHECK(m_geometry.retrieve());
return StatusCode::SUCCESS;
}
StatusCode LArEndcapPresamplerCalculator::finalize()
{
if (m_birksLaw) delete m_birksLaw;
return StatusCode::SUCCESS;
}
G4bool LArEndcapPresamplerCalculator::Process(const G4Step* a_step, std::vector<LArHitData>& hdata) const
{
// make sure hdata is reset
hdata.resize(1);
// Given a G4Step, find the identifier in the LAr EMEC associated
// with that point.
// 29-Mar-2002 WGS: this method now returns a boolean. If it's
// true, the hit is valid; if it's false, there was some problem
// with the hit and it should be ignored.
double energy = a_step->GetTotalEnergyDeposit();
if (m_birksLaw) {
G4double wholeStepLengthCm = a_step->GetStepLength() / Units::cm;
G4double efield = 10.; // 10 kV/cm simple approximation of electric field
energy = (*m_birksLaw)(energy, wholeStepLengthCm,efield);
}
// First, get the energy.
hdata[0].energy = energy;
// Find out how long it took the energy to get here.
G4StepPoint* pre_step_point = a_step->GetPreStepPoint();
G4StepPoint* post_step_point = a_step->GetPostStepPoint();
G4double timeOfFlight = (pre_step_point->GetGlobalTime() +
post_step_point->GetGlobalTime()) * 0.5;
G4ThreeVector startPoint = pre_step_point->GetPosition();
G4ThreeVector endPoint = post_step_point->GetPosition();
G4ThreeVector p = (startPoint + endPoint) * 0.5;
// Determine if the hit was in-time.
hdata[0].time = timeOfFlight/Units::ns - p.mag()/CLHEP::c_light/Units::ns;
// Use the geometry routine to determine the identifier.
hdata[0].id = m_geometry->CalculateIdentifier( a_step );
if ( hdata[0].id == LArG4Identifier() )
return false;
else
return true;
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
2428b7b37ef45d80deb454e095939c5be5ade4ff | 55540f3e86f1d5d86ef6b5d295a63518e274efe3 | /toolchain/riscv/MSYS/riscv64-unknown-elf/include/c++/10.2.0/bits/stl_algobase.h | b1546521dfd0ac3640cd4fb1b81c21d566d55537 | [
"Apache-2.0"
] | permissive | bouffalolab/bl_iot_sdk | bc5eaf036b70f8c65dd389439062b169f8d09daa | b90664de0bd4c1897a9f1f5d9e360a9631d38b34 | refs/heads/master | 2023-08-31T03:38:03.369853 | 2023-08-16T08:50:33 | 2023-08-18T09:13:27 | 307,347,250 | 244 | 101 | Apache-2.0 | 2023-08-28T06:29:02 | 2020-10-26T11:16:30 | C | UTF-8 | C++ | false | false | 71,977 | h | // Core algorithmic facilities -*- C++ -*-
// Copyright (C) 2001-2020 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1996-1998
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
/** @file bits/stl_algobase.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{algorithm}
*/
#ifndef _STL_ALGOBASE_H
#define _STL_ALGOBASE_H 1
#include <bits/c++config.h>
#include <bits/functexcept.h>
#include <bits/cpp_type_traits.h>
#include <ext/type_traits.h>
#include <ext/numeric_traits.h>
#include <bits/stl_pair.h>
#include <bits/stl_iterator_base_types.h>
#include <bits/stl_iterator_base_funcs.h>
#include <bits/stl_iterator.h>
#include <bits/concept_check.h>
#include <debug/debug.h>
#include <bits/move.h> // For std::swap
#include <bits/predefined_ops.h>
#if __cplusplus >= 201103L
# include <type_traits>
#endif
#if __cplusplus > 201703L
# include <compare>
#endif
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/*
* A constexpr wrapper for __builtin_memcmp.
* @param __num The number of elements of type _Tp (not bytes).
*/
template<typename _Tp, typename _Up>
_GLIBCXX14_CONSTEXPR
inline int
__memcmp(const _Tp* __first1, const _Up* __first2, size_t __num)
{
#if __cplusplus >= 201103L
static_assert(sizeof(_Tp) == sizeof(_Up), "can be compared with memcmp");
#endif
#ifdef __cpp_lib_is_constant_evaluated
if (std::is_constant_evaluated())
{
for(; __num > 0; ++__first1, ++__first2, --__num)
if (*__first1 != *__first2)
return *__first1 < *__first2 ? -1 : 1;
return 0;
}
else
#endif
return __builtin_memcmp(__first1, __first2, sizeof(_Tp) * __num);
}
#if __cplusplus < 201103L
// See http://gcc.gnu.org/ml/libstdc++/2004-08/msg00167.html: in a
// nutshell, we are partially implementing the resolution of DR 187,
// when it's safe, i.e., the value_types are equal.
template<bool _BoolType>
struct __iter_swap
{
template<typename _ForwardIterator1, typename _ForwardIterator2>
static void
iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b)
{
typedef typename iterator_traits<_ForwardIterator1>::value_type
_ValueType1;
_ValueType1 __tmp = *__a;
*__a = *__b;
*__b = __tmp;
}
};
template<>
struct __iter_swap<true>
{
template<typename _ForwardIterator1, typename _ForwardIterator2>
static void
iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b)
{
swap(*__a, *__b);
}
};
#endif // C++03
/**
* @brief Swaps the contents of two iterators.
* @ingroup mutating_algorithms
* @param __a An iterator.
* @param __b Another iterator.
* @return Nothing.
*
* This function swaps the values pointed to by two iterators, not the
* iterators themselves.
*/
template<typename _ForwardIterator1, typename _ForwardIterator2>
_GLIBCXX20_CONSTEXPR
inline void
iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b)
{
// concept requirements
__glibcxx_function_requires(_Mutable_ForwardIteratorConcept<
_ForwardIterator1>)
__glibcxx_function_requires(_Mutable_ForwardIteratorConcept<
_ForwardIterator2>)
#if __cplusplus < 201103L
typedef typename iterator_traits<_ForwardIterator1>::value_type
_ValueType1;
typedef typename iterator_traits<_ForwardIterator2>::value_type
_ValueType2;
__glibcxx_function_requires(_ConvertibleConcept<_ValueType1,
_ValueType2>)
__glibcxx_function_requires(_ConvertibleConcept<_ValueType2,
_ValueType1>)
typedef typename iterator_traits<_ForwardIterator1>::reference
_ReferenceType1;
typedef typename iterator_traits<_ForwardIterator2>::reference
_ReferenceType2;
std::__iter_swap<__are_same<_ValueType1, _ValueType2>::__value
&& __are_same<_ValueType1&, _ReferenceType1>::__value
&& __are_same<_ValueType2&, _ReferenceType2>::__value>::
iter_swap(__a, __b);
#else
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 187. iter_swap underspecified
swap(*__a, *__b);
#endif
}
/**
* @brief Swap the elements of two sequences.
* @ingroup mutating_algorithms
* @param __first1 A forward iterator.
* @param __last1 A forward iterator.
* @param __first2 A forward iterator.
* @return An iterator equal to @p first2+(last1-first1).
*
* Swaps each element in the range @p [first1,last1) with the
* corresponding element in the range @p [first2,(last1-first1)).
* The ranges must not overlap.
*/
template<typename _ForwardIterator1, typename _ForwardIterator2>
_GLIBCXX20_CONSTEXPR
_ForwardIterator2
swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2)
{
// concept requirements
__glibcxx_function_requires(_Mutable_ForwardIteratorConcept<
_ForwardIterator1>)
__glibcxx_function_requires(_Mutable_ForwardIteratorConcept<
_ForwardIterator2>)
__glibcxx_requires_valid_range(__first1, __last1);
for (; __first1 != __last1; ++__first1, (void)++__first2)
std::iter_swap(__first1, __first2);
return __first2;
}
/**
* @brief This does what you think it does.
* @ingroup sorting_algorithms
* @param __a A thing of arbitrary type.
* @param __b Another thing of arbitrary type.
* @return The lesser of the parameters.
*
* This is the simple classic generic implementation. It will work on
* temporary expressions, since they are only evaluated once, unlike a
* preprocessor macro.
*/
template<typename _Tp>
_GLIBCXX14_CONSTEXPR
inline const _Tp&
min(const _Tp& __a, const _Tp& __b)
{
// concept requirements
__glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
//return __b < __a ? __b : __a;
if (__b < __a)
return __b;
return __a;
}
/**
* @brief This does what you think it does.
* @ingroup sorting_algorithms
* @param __a A thing of arbitrary type.
* @param __b Another thing of arbitrary type.
* @return The greater of the parameters.
*
* This is the simple classic generic implementation. It will work on
* temporary expressions, since they are only evaluated once, unlike a
* preprocessor macro.
*/
template<typename _Tp>
_GLIBCXX14_CONSTEXPR
inline const _Tp&
max(const _Tp& __a, const _Tp& __b)
{
// concept requirements
__glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
//return __a < __b ? __b : __a;
if (__a < __b)
return __b;
return __a;
}
/**
* @brief This does what you think it does.
* @ingroup sorting_algorithms
* @param __a A thing of arbitrary type.
* @param __b Another thing of arbitrary type.
* @param __comp A @link comparison_functors comparison functor@endlink.
* @return The lesser of the parameters.
*
* This will work on temporary expressions, since they are only evaluated
* once, unlike a preprocessor macro.
*/
template<typename _Tp, typename _Compare>
_GLIBCXX14_CONSTEXPR
inline const _Tp&
min(const _Tp& __a, const _Tp& __b, _Compare __comp)
{
//return __comp(__b, __a) ? __b : __a;
if (__comp(__b, __a))
return __b;
return __a;
}
/**
* @brief This does what you think it does.
* @ingroup sorting_algorithms
* @param __a A thing of arbitrary type.
* @param __b Another thing of arbitrary type.
* @param __comp A @link comparison_functors comparison functor@endlink.
* @return The greater of the parameters.
*
* This will work on temporary expressions, since they are only evaluated
* once, unlike a preprocessor macro.
*/
template<typename _Tp, typename _Compare>
_GLIBCXX14_CONSTEXPR
inline const _Tp&
max(const _Tp& __a, const _Tp& __b, _Compare __comp)
{
//return __comp(__a, __b) ? __b : __a;
if (__comp(__a, __b))
return __b;
return __a;
}
// Fallback implementation of the function in bits/stl_iterator.h used to
// remove the __normal_iterator wrapper. See copy, fill, ...
template<typename _Iterator>
_GLIBCXX20_CONSTEXPR
inline _Iterator
__niter_base(_Iterator __it)
_GLIBCXX_NOEXCEPT_IF(std::is_nothrow_copy_constructible<_Iterator>::value)
{ return __it; }
// Reverse the __niter_base transformation to get a
// __normal_iterator back again (this assumes that __normal_iterator
// is only used to wrap random access iterators, like pointers).
template<typename _From, typename _To>
_GLIBCXX20_CONSTEXPR
inline _From
__niter_wrap(_From __from, _To __res)
{ return __from + (__res - std::__niter_base(__from)); }
// No need to wrap, iterator already has the right type.
template<typename _Iterator>
_GLIBCXX20_CONSTEXPR
inline _Iterator
__niter_wrap(const _Iterator&, _Iterator __res)
{ return __res; }
// All of these auxiliary structs serve two purposes. (1) Replace
// calls to copy with memmove whenever possible. (Memmove, not memcpy,
// because the input and output ranges are permitted to overlap.)
// (2) If we're using random access iterators, then write the loop as
// a for loop with an explicit count.
template<bool _IsMove, bool _IsSimple, typename _Category>
struct __copy_move
{
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
static _OI
__copy_m(_II __first, _II __last, _OI __result)
{
for (; __first != __last; ++__result, (void)++__first)
*__result = *__first;
return __result;
}
};
#if __cplusplus >= 201103L
template<typename _Category>
struct __copy_move<true, false, _Category>
{
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
static _OI
__copy_m(_II __first, _II __last, _OI __result)
{
for (; __first != __last; ++__result, (void)++__first)
*__result = std::move(*__first);
return __result;
}
};
#endif
template<>
struct __copy_move<false, false, random_access_iterator_tag>
{
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
static _OI
__copy_m(_II __first, _II __last, _OI __result)
{
typedef typename iterator_traits<_II>::difference_type _Distance;
for(_Distance __n = __last - __first; __n > 0; --__n)
{
*__result = *__first;
++__first;
++__result;
}
return __result;
}
};
#if __cplusplus >= 201103L
template<>
struct __copy_move<true, false, random_access_iterator_tag>
{
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
static _OI
__copy_m(_II __first, _II __last, _OI __result)
{
typedef typename iterator_traits<_II>::difference_type _Distance;
for(_Distance __n = __last - __first; __n > 0; --__n)
{
*__result = std::move(*__first);
++__first;
++__result;
}
return __result;
}
};
#endif
template<bool _IsMove>
struct __copy_move<_IsMove, true, random_access_iterator_tag>
{
template<typename _Tp>
_GLIBCXX20_CONSTEXPR
static _Tp*
__copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result)
{
#if __cplusplus >= 201103L
using __assignable = conditional<_IsMove,
is_move_assignable<_Tp>,
is_copy_assignable<_Tp>>;
// trivial types can have deleted assignment
static_assert( __assignable::type::value, "type is not assignable" );
#endif
const ptrdiff_t _Num = __last - __first;
if (_Num)
__builtin_memmove(__result, __first, sizeof(_Tp) * _Num);
return __result + _Num;
}
};
// Helpers for streambuf iterators (either istream or ostream).
// NB: avoid including <iosfwd>, relatively large.
template<typename _CharT>
struct char_traits;
template<typename _CharT, typename _Traits>
class istreambuf_iterator;
template<typename _CharT, typename _Traits>
class ostreambuf_iterator;
template<bool _IsMove, typename _CharT>
typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value,
ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type
__copy_move_a2(_CharT*, _CharT*,
ostreambuf_iterator<_CharT, char_traits<_CharT> >);
template<bool _IsMove, typename _CharT>
typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value,
ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type
__copy_move_a2(const _CharT*, const _CharT*,
ostreambuf_iterator<_CharT, char_traits<_CharT> >);
template<bool _IsMove, typename _CharT>
typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value,
_CharT*>::__type
__copy_move_a2(istreambuf_iterator<_CharT, char_traits<_CharT> >,
istreambuf_iterator<_CharT, char_traits<_CharT> >, _CharT*);
template<bool _IsMove, typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
__copy_move_a2(_II __first, _II __last, _OI __result)
{
typedef typename iterator_traits<_II>::iterator_category _Category;
#ifdef __cpp_lib_is_constant_evaluated
if (std::is_constant_evaluated())
return std::__copy_move<_IsMove, false, _Category>::
__copy_m(__first, __last, __result);
#endif
return std::__copy_move<_IsMove, __memcpyable<_OI, _II>::__value,
_Category>::__copy_m(__first, __last, __result);
}
_GLIBCXX_BEGIN_NAMESPACE_CONTAINER
template<typename _Tp, typename _Ref, typename _Ptr>
struct _Deque_iterator;
_GLIBCXX_END_NAMESPACE_CONTAINER
template<bool _IsMove,
typename _Tp, typename _Ref, typename _Ptr, typename _OI>
_OI
__copy_move_a1(_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_OI);
template<bool _IsMove,
typename _ITp, typename _IRef, typename _IPtr, typename _OTp>
_GLIBCXX_STD_C::_Deque_iterator<_OTp, _OTp&, _OTp*>
__copy_move_a1(_GLIBCXX_STD_C::_Deque_iterator<_ITp, _IRef, _IPtr>,
_GLIBCXX_STD_C::_Deque_iterator<_ITp, _IRef, _IPtr>,
_GLIBCXX_STD_C::_Deque_iterator<_OTp, _OTp&, _OTp*>);
template<bool _IsMove, typename _II, typename _Tp>
typename __gnu_cxx::__enable_if<
__is_random_access_iter<_II>::__value,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*> >::__type
__copy_move_a1(_II, _II, _GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*>);
template<bool _IsMove, typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
__copy_move_a1(_II __first, _II __last, _OI __result)
{ return std::__copy_move_a2<_IsMove>(__first, __last, __result); }
template<bool _IsMove, typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
__copy_move_a(_II __first, _II __last, _OI __result)
{
return std::__niter_wrap(__result,
std::__copy_move_a1<_IsMove>(std::__niter_base(__first),
std::__niter_base(__last),
std::__niter_base(__result)));
}
template<bool _IsMove,
typename _Ite, typename _Seq, typename _Cat, typename _OI>
_OI
__copy_move_a(const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
_OI);
template<bool _IsMove,
typename _II, typename _Ite, typename _Seq, typename _Cat>
__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>
__copy_move_a(_II, _II,
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&);
template<bool _IsMove,
typename _IIte, typename _ISeq, typename _ICat,
typename _OIte, typename _OSeq, typename _OCat>
::__gnu_debug::_Safe_iterator<_OIte, _OSeq, _OCat>
__copy_move_a(const ::__gnu_debug::_Safe_iterator<_IIte, _ISeq, _ICat>&,
const ::__gnu_debug::_Safe_iterator<_IIte, _ISeq, _ICat>&,
const ::__gnu_debug::_Safe_iterator<_OIte, _OSeq, _OCat>&);
/**
* @brief Copies the range [first,last) into result.
* @ingroup mutating_algorithms
* @param __first An input iterator.
* @param __last An input iterator.
* @param __result An output iterator.
* @return result + (first - last)
*
* This inline function will boil down to a call to @c memmove whenever
* possible. Failing that, if random access iterators are passed, then the
* loop count will be known (and therefore a candidate for compiler
* optimizations such as unrolling). Result may not be contained within
* [first,last); the copy_backward function should be used instead.
*
* Note that the end of the output range is permitted to be contained
* within [first,last).
*/
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
copy(_II __first, _II __last, _OI __result)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_II>)
__glibcxx_function_requires(_OutputIteratorConcept<_OI,
typename iterator_traits<_II>::value_type>)
__glibcxx_requires_can_increment_range(__first, __last, __result);
return std::__copy_move_a<__is_move_iterator<_II>::__value>
(std::__miter_base(__first), std::__miter_base(__last), __result);
}
#if __cplusplus >= 201103L
/**
* @brief Moves the range [first,last) into result.
* @ingroup mutating_algorithms
* @param __first An input iterator.
* @param __last An input iterator.
* @param __result An output iterator.
* @return result + (first - last)
*
* This inline function will boil down to a call to @c memmove whenever
* possible. Failing that, if random access iterators are passed, then the
* loop count will be known (and therefore a candidate for compiler
* optimizations such as unrolling). Result may not be contained within
* [first,last); the move_backward function should be used instead.
*
* Note that the end of the output range is permitted to be contained
* within [first,last).
*/
template<typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
move(_II __first, _II __last, _OI __result)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_II>)
__glibcxx_function_requires(_OutputIteratorConcept<_OI,
typename iterator_traits<_II>::value_type>)
__glibcxx_requires_can_increment_range(__first, __last, __result);
return std::__copy_move_a<true>(std::__miter_base(__first),
std::__miter_base(__last), __result);
}
#define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::move(_Tp, _Up, _Vp)
#else
#define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::copy(_Tp, _Up, _Vp)
#endif
template<bool _IsMove, bool _IsSimple, typename _Category>
struct __copy_move_backward
{
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
static _BI2
__copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result)
{
while (__first != __last)
*--__result = *--__last;
return __result;
}
};
#if __cplusplus >= 201103L
template<typename _Category>
struct __copy_move_backward<true, false, _Category>
{
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
static _BI2
__copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result)
{
while (__first != __last)
*--__result = std::move(*--__last);
return __result;
}
};
#endif
template<>
struct __copy_move_backward<false, false, random_access_iterator_tag>
{
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
static _BI2
__copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result)
{
typename iterator_traits<_BI1>::difference_type
__n = __last - __first;
for (; __n > 0; --__n)
*--__result = *--__last;
return __result;
}
};
#if __cplusplus >= 201103L
template<>
struct __copy_move_backward<true, false, random_access_iterator_tag>
{
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
static _BI2
__copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result)
{
typename iterator_traits<_BI1>::difference_type
__n = __last - __first;
for (; __n > 0; --__n)
*--__result = std::move(*--__last);
return __result;
}
};
#endif
template<bool _IsMove>
struct __copy_move_backward<_IsMove, true, random_access_iterator_tag>
{
template<typename _Tp>
_GLIBCXX20_CONSTEXPR
static _Tp*
__copy_move_b(const _Tp* __first, const _Tp* __last, _Tp* __result)
{
#if __cplusplus >= 201103L
using __assignable = conditional<_IsMove,
is_move_assignable<_Tp>,
is_copy_assignable<_Tp>>;
// trivial types can have deleted assignment
static_assert( __assignable::type::value, "type is not assignable" );
#endif
const ptrdiff_t _Num = __last - __first;
if (_Num)
__builtin_memmove(__result - _Num, __first, sizeof(_Tp) * _Num);
return __result - _Num;
}
};
template<bool _IsMove, typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
inline _BI2
__copy_move_backward_a2(_BI1 __first, _BI1 __last, _BI2 __result)
{
typedef typename iterator_traits<_BI1>::iterator_category _Category;
#ifdef __cpp_lib_is_constant_evaluated
if (std::is_constant_evaluated())
return std::__copy_move_backward<_IsMove, false, _Category>::
__copy_move_b(__first, __last, __result);
#endif
return std::__copy_move_backward<_IsMove,
__memcpyable<_BI2, _BI1>::__value,
_Category>::__copy_move_b(__first,
__last,
__result);
}
template<bool _IsMove, typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
inline _BI2
__copy_move_backward_a1(_BI1 __first, _BI1 __last, _BI2 __result)
{ return std::__copy_move_backward_a2<_IsMove>(__first, __last, __result); }
template<bool _IsMove,
typename _Tp, typename _Ref, typename _Ptr, typename _OI>
_OI
__copy_move_backward_a1(_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_OI);
template<bool _IsMove,
typename _ITp, typename _IRef, typename _IPtr, typename _OTp>
_GLIBCXX_STD_C::_Deque_iterator<_OTp, _OTp&, _OTp*>
__copy_move_backward_a1(
_GLIBCXX_STD_C::_Deque_iterator<_ITp, _IRef, _IPtr>,
_GLIBCXX_STD_C::_Deque_iterator<_ITp, _IRef, _IPtr>,
_GLIBCXX_STD_C::_Deque_iterator<_OTp, _OTp&, _OTp*>);
template<bool _IsMove, typename _II, typename _Tp>
typename __gnu_cxx::__enable_if<
__is_random_access_iter<_II>::__value,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*> >::__type
__copy_move_backward_a1(_II, _II,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*>);
template<bool _IsMove, typename _II, typename _OI>
_GLIBCXX20_CONSTEXPR
inline _OI
__copy_move_backward_a(_II __first, _II __last, _OI __result)
{
return std::__niter_wrap(__result,
std::__copy_move_backward_a1<_IsMove>
(std::__niter_base(__first), std::__niter_base(__last),
std::__niter_base(__result)));
}
template<bool _IsMove,
typename _Ite, typename _Seq, typename _Cat, typename _OI>
_OI
__copy_move_backward_a(
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
_OI);
template<bool _IsMove,
typename _II, typename _Ite, typename _Seq, typename _Cat>
__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>
__copy_move_backward_a(_II, _II,
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&);
template<bool _IsMove,
typename _IIte, typename _ISeq, typename _ICat,
typename _OIte, typename _OSeq, typename _OCat>
::__gnu_debug::_Safe_iterator<_OIte, _OSeq, _OCat>
__copy_move_backward_a(
const ::__gnu_debug::_Safe_iterator<_IIte, _ISeq, _ICat>&,
const ::__gnu_debug::_Safe_iterator<_IIte, _ISeq, _ICat>&,
const ::__gnu_debug::_Safe_iterator<_OIte, _OSeq, _OCat>&);
/**
* @brief Copies the range [first,last) into result.
* @ingroup mutating_algorithms
* @param __first A bidirectional iterator.
* @param __last A bidirectional iterator.
* @param __result A bidirectional iterator.
* @return result - (first - last)
*
* The function has the same effect as copy, but starts at the end of the
* range and works its way to the start, returning the start of the result.
* This inline function will boil down to a call to @c memmove whenever
* possible. Failing that, if random access iterators are passed, then the
* loop count will be known (and therefore a candidate for compiler
* optimizations such as unrolling).
*
* Result may not be in the range (first,last]. Use copy instead. Note
* that the start of the output range may overlap [first,last).
*/
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
inline _BI2
copy_backward(_BI1 __first, _BI1 __last, _BI2 __result)
{
// concept requirements
__glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>)
__glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>)
__glibcxx_function_requires(_ConvertibleConcept<
typename iterator_traits<_BI1>::value_type,
typename iterator_traits<_BI2>::value_type>)
__glibcxx_requires_can_decrement_range(__first, __last, __result);
return std::__copy_move_backward_a<__is_move_iterator<_BI1>::__value>
(std::__miter_base(__first), std::__miter_base(__last), __result);
}
#if __cplusplus >= 201103L
/**
* @brief Moves the range [first,last) into result.
* @ingroup mutating_algorithms
* @param __first A bidirectional iterator.
* @param __last A bidirectional iterator.
* @param __result A bidirectional iterator.
* @return result - (first - last)
*
* The function has the same effect as move, but starts at the end of the
* range and works its way to the start, returning the start of the result.
* This inline function will boil down to a call to @c memmove whenever
* possible. Failing that, if random access iterators are passed, then the
* loop count will be known (and therefore a candidate for compiler
* optimizations such as unrolling).
*
* Result may not be in the range (first,last]. Use move instead. Note
* that the start of the output range may overlap [first,last).
*/
template<typename _BI1, typename _BI2>
_GLIBCXX20_CONSTEXPR
inline _BI2
move_backward(_BI1 __first, _BI1 __last, _BI2 __result)
{
// concept requirements
__glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>)
__glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>)
__glibcxx_function_requires(_ConvertibleConcept<
typename iterator_traits<_BI1>::value_type,
typename iterator_traits<_BI2>::value_type>)
__glibcxx_requires_can_decrement_range(__first, __last, __result);
return std::__copy_move_backward_a<true>(std::__miter_base(__first),
std::__miter_base(__last),
__result);
}
#define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::move_backward(_Tp, _Up, _Vp)
#else
#define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::copy_backward(_Tp, _Up, _Vp)
#endif
template<typename _ForwardIterator, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline typename
__gnu_cxx::__enable_if<!__is_scalar<_Tp>::__value, void>::__type
__fill_a1(_ForwardIterator __first, _ForwardIterator __last,
const _Tp& __value)
{
for (; __first != __last; ++__first)
*__first = __value;
}
template<typename _ForwardIterator, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline typename
__gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, void>::__type
__fill_a1(_ForwardIterator __first, _ForwardIterator __last,
const _Tp& __value)
{
const _Tp __tmp = __value;
for (; __first != __last; ++__first)
*__first = __tmp;
}
// Specialization: for char types we can use memset.
template<typename _Tp>
_GLIBCXX20_CONSTEXPR
inline typename
__gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type
__fill_a1(_Tp* __first, _Tp* __last, const _Tp& __c)
{
const _Tp __tmp = __c;
#if __cpp_lib_is_constant_evaluated
if (std::is_constant_evaluated())
{
for (; __first != __last; ++__first)
*__first = __tmp;
return;
}
#endif
if (const size_t __len = __last - __first)
__builtin_memset(__first, static_cast<unsigned char>(__tmp), __len);
}
template<typename _Ite, typename _Cont, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline void
__fill_a1(::__gnu_cxx::__normal_iterator<_Ite, _Cont> __first,
::__gnu_cxx::__normal_iterator<_Ite, _Cont> __last,
const _Tp& __value)
{ std::__fill_a1(__first.base(), __last.base(), __value); }
template<typename _Tp, typename _VTp>
void
__fill_a1(const _GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*>&,
const _GLIBCXX_STD_C::_Deque_iterator<_Tp, _Tp&, _Tp*>&,
const _VTp&);
template<typename _FIte, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline void
__fill_a(_FIte __first, _FIte __last, const _Tp& __value)
{ std::__fill_a1(__first, __last, __value); }
template<typename _Ite, typename _Seq, typename _Cat, typename _Tp>
void
__fill_a(const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>&,
const _Tp&);
/**
* @brief Fills the range [first,last) with copies of value.
* @ingroup mutating_algorithms
* @param __first A forward iterator.
* @param __last A forward iterator.
* @param __value A reference-to-const of arbitrary type.
* @return Nothing.
*
* This function fills a range with copies of the same value. For char
* types filling contiguous areas of memory, this becomes an inline call
* to @c memset or @c wmemset.
*/
template<typename _ForwardIterator, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline void
fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value)
{
// concept requirements
__glibcxx_function_requires(_Mutable_ForwardIteratorConcept<
_ForwardIterator>)
__glibcxx_requires_valid_range(__first, __last);
std::__fill_a(__first, __last, __value);
}
// Used by fill_n, generate_n, etc. to convert _Size to an integral type:
inline _GLIBCXX_CONSTEXPR int
__size_to_integer(int __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned
__size_to_integer(unsigned __n) { return __n; }
inline _GLIBCXX_CONSTEXPR long
__size_to_integer(long __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned long
__size_to_integer(unsigned long __n) { return __n; }
inline _GLIBCXX_CONSTEXPR long long
__size_to_integer(long long __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned long long
__size_to_integer(unsigned long long __n) { return __n; }
#if defined(__GLIBCXX_TYPE_INT_N_0)
inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_0
__size_to_integer(__GLIBCXX_TYPE_INT_N_0 __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned __GLIBCXX_TYPE_INT_N_0
__size_to_integer(unsigned __GLIBCXX_TYPE_INT_N_0 __n) { return __n; }
#endif
#if defined(__GLIBCXX_TYPE_INT_N_1)
inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_1
__size_to_integer(__GLIBCXX_TYPE_INT_N_1 __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned __GLIBCXX_TYPE_INT_N_1
__size_to_integer(unsigned __GLIBCXX_TYPE_INT_N_1 __n) { return __n; }
#endif
#if defined(__GLIBCXX_TYPE_INT_N_2)
inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_2
__size_to_integer(__GLIBCXX_TYPE_INT_N_2 __n) { return __n; }
inline _GLIBCXX_CONSTEXPR unsigned __GLIBCXX_TYPE_INT_N_2
__size_to_integer(unsigned __GLIBCXX_TYPE_INT_N_2 __n) { return __n; }
#endif
#if defined(__GLIBCXX_TYPE_INT_N_3)
inline _GLIBCXX_CONSTEXPR unsigned __GLIBCXX_TYPE_INT_N_3
__size_to_integer(__GLIBCXX_TYPE_INT_N_3 __n) { return __n; }
inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_3
__size_to_integer(unsigned __GLIBCXX_TYPE_INT_N_3 __n) { return __n; }
#endif
inline _GLIBCXX_CONSTEXPR long long
__size_to_integer(float __n) { return __n; }
inline _GLIBCXX_CONSTEXPR long long
__size_to_integer(double __n) { return __n; }
inline _GLIBCXX_CONSTEXPR long long
__size_to_integer(long double __n) { return __n; }
#if !defined(__STRICT_ANSI__) && defined(_GLIBCXX_USE_FLOAT128)
inline _GLIBCXX_CONSTEXPR long long
__size_to_integer(__float128 __n) { return __n; }
#endif
template<typename _OutputIterator, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline typename
__gnu_cxx::__enable_if<!__is_scalar<_Tp>::__value, _OutputIterator>::__type
__fill_n_a1(_OutputIterator __first, _Size __n, const _Tp& __value)
{
for (; __n > 0; --__n, (void) ++__first)
*__first = __value;
return __first;
}
template<typename _OutputIterator, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline typename
__gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, _OutputIterator>::__type
__fill_n_a1(_OutputIterator __first, _Size __n, const _Tp& __value)
{
const _Tp __tmp = __value;
for (; __n > 0; --__n, (void) ++__first)
*__first = __tmp;
return __first;
}
template<typename _Ite, typename _Seq, typename _Cat, typename _Size,
typename _Tp>
::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>
__fill_n_a(const ::__gnu_debug::_Safe_iterator<_Ite, _Seq, _Cat>& __first,
_Size __n, const _Tp& __value,
std::input_iterator_tag);
template<typename _OutputIterator, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline _OutputIterator
__fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value,
std::output_iterator_tag)
{
#if __cplusplus >= 201103L
static_assert(is_integral<_Size>{}, "fill_n must pass integral size");
#endif
return __fill_n_a1(__first, __n, __value);
}
template<typename _OutputIterator, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline _OutputIterator
__fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value,
std::input_iterator_tag)
{
#if __cplusplus >= 201103L
static_assert(is_integral<_Size>{}, "fill_n must pass integral size");
#endif
return __fill_n_a1(__first, __n, __value);
}
template<typename _OutputIterator, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline _OutputIterator
__fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value,
std::random_access_iterator_tag)
{
#if __cplusplus >= 201103L
static_assert(is_integral<_Size>{}, "fill_n must pass integral size");
#endif
if (__n <= 0)
return __first;
__glibcxx_requires_can_increment(__first, __n);
std::__fill_a(__first, __first + __n, __value);
return __first + __n;
}
/**
* @brief Fills the range [first,first+n) with copies of value.
* @ingroup mutating_algorithms
* @param __first An output iterator.
* @param __n The count of copies to perform.
* @param __value A reference-to-const of arbitrary type.
* @return The iterator at first+n.
*
* This function fills a range with copies of the same value. For char
* types filling contiguous areas of memory, this becomes an inline call
* to @c memset or @c wmemset.
*
* If @p __n is negative, the function does nothing.
*/
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 865. More algorithms that throw away information
// DR 426. search_n(), fill_n(), and generate_n() with negative n
template<typename _OI, typename _Size, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline _OI
fill_n(_OI __first, _Size __n, const _Tp& __value)
{
// concept requirements
__glibcxx_function_requires(_OutputIteratorConcept<_OI, _Tp>)
return std::__fill_n_a(__first, std::__size_to_integer(__n), __value,
std::__iterator_category(__first));
}
template<bool _BoolType>
struct __equal
{
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
static bool
equal(_II1 __first1, _II1 __last1, _II2 __first2)
{
for (; __first1 != __last1; ++__first1, (void) ++__first2)
if (!(*__first1 == *__first2))
return false;
return true;
}
};
template<>
struct __equal<true>
{
template<typename _Tp>
_GLIBCXX20_CONSTEXPR
static bool
equal(const _Tp* __first1, const _Tp* __last1, const _Tp* __first2)
{
if (const size_t __len = (__last1 - __first1))
return !std::__memcmp(__first1, __first2, __len);
return true;
}
};
template<typename _Tp, typename _Ref, typename _Ptr, typename _II>
typename __gnu_cxx::__enable_if<
__is_random_access_iter<_II>::__value, bool>::__type
__equal_aux1(_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>,
_II);
template<typename _Tp1, typename _Ref1, typename _Ptr1,
typename _Tp2, typename _Ref2, typename _Ptr2>
bool
__equal_aux1(_GLIBCXX_STD_C::_Deque_iterator<_Tp1, _Ref1, _Ptr1>,
_GLIBCXX_STD_C::_Deque_iterator<_Tp1, _Ref1, _Ptr1>,
_GLIBCXX_STD_C::_Deque_iterator<_Tp2, _Ref2, _Ptr2>);
template<typename _II, typename _Tp, typename _Ref, typename _Ptr>
typename __gnu_cxx::__enable_if<
__is_random_access_iter<_II>::__value, bool>::__type
__equal_aux1(_II, _II,
_GLIBCXX_STD_C::_Deque_iterator<_Tp, _Ref, _Ptr>);
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
__equal_aux1(_II1 __first1, _II1 __last1, _II2 __first2)
{
typedef typename iterator_traits<_II1>::value_type _ValueType1;
const bool __simple = ((__is_integer<_ValueType1>::__value
|| __is_pointer<_ValueType1>::__value)
&& __memcmpable<_II1, _II2>::__value);
return std::__equal<__simple>::equal(__first1, __last1, __first2);
}
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
__equal_aux(_II1 __first1, _II1 __last1, _II2 __first2)
{
return std::__equal_aux1(std::__niter_base(__first1),
std::__niter_base(__last1),
std::__niter_base(__first2));
}
template<typename _II1, typename _Seq1, typename _Cat1, typename _II2>
bool
__equal_aux(const ::__gnu_debug::_Safe_iterator<_II1, _Seq1, _Cat1>&,
const ::__gnu_debug::_Safe_iterator<_II1, _Seq1, _Cat1>&,
_II2);
template<typename _II1, typename _II2, typename _Seq2, typename _Cat2>
bool
__equal_aux(_II1, _II1,
const ::__gnu_debug::_Safe_iterator<_II2, _Seq2, _Cat2>&);
template<typename _II1, typename _Seq1, typename _Cat1,
typename _II2, typename _Seq2, typename _Cat2>
bool
__equal_aux(const ::__gnu_debug::_Safe_iterator<_II1, _Seq1, _Cat1>&,
const ::__gnu_debug::_Safe_iterator<_II1, _Seq1, _Cat1>&,
const ::__gnu_debug::_Safe_iterator<_II2, _Seq2, _Cat2>&);
template<typename, typename>
struct __lc_rai
{
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
static _II1
__newlast1(_II1, _II1 __last1, _II2, _II2)
{ return __last1; }
template<typename _II>
_GLIBCXX20_CONSTEXPR
static bool
__cnd2(_II __first, _II __last)
{ return __first != __last; }
};
template<>
struct __lc_rai<random_access_iterator_tag, random_access_iterator_tag>
{
template<typename _RAI1, typename _RAI2>
_GLIBCXX20_CONSTEXPR
static _RAI1
__newlast1(_RAI1 __first1, _RAI1 __last1,
_RAI2 __first2, _RAI2 __last2)
{
const typename iterator_traits<_RAI1>::difference_type
__diff1 = __last1 - __first1;
const typename iterator_traits<_RAI2>::difference_type
__diff2 = __last2 - __first2;
return __diff2 < __diff1 ? __first1 + __diff2 : __last1;
}
template<typename _RAI>
static _GLIBCXX20_CONSTEXPR bool
__cnd2(_RAI, _RAI)
{ return true; }
};
template<typename _II1, typename _II2, typename _Compare>
_GLIBCXX20_CONSTEXPR
bool
__lexicographical_compare_impl(_II1 __first1, _II1 __last1,
_II2 __first2, _II2 __last2,
_Compare __comp)
{
typedef typename iterator_traits<_II1>::iterator_category _Category1;
typedef typename iterator_traits<_II2>::iterator_category _Category2;
typedef std::__lc_rai<_Category1, _Category2> __rai_type;
__last1 = __rai_type::__newlast1(__first1, __last1, __first2, __last2);
for (; __first1 != __last1 && __rai_type::__cnd2(__first2, __last2);
++__first1, (void)++__first2)
{
if (__comp(__first1, __first2))
return true;
if (__comp(__first2, __first1))
return false;
}
return __first1 == __last1 && __first2 != __last2;
}
template<bool _BoolType>
struct __lexicographical_compare
{
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
static bool
__lc(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2)
{
using __gnu_cxx::__ops::__iter_less_iter;
return std::__lexicographical_compare_impl(__first1, __last1,
__first2, __last2,
__iter_less_iter());
}
};
template<>
struct __lexicographical_compare<true>
{
template<typename _Tp, typename _Up>
_GLIBCXX20_CONSTEXPR
static bool
__lc(const _Tp* __first1, const _Tp* __last1,
const _Up* __first2, const _Up* __last2)
{
const size_t __len1 = __last1 - __first1;
const size_t __len2 = __last2 - __first2;
if (const size_t __len = std::min(__len1, __len2))
if (int __result = std::__memcmp(__first1, __first2, __len))
return __result < 0;
return __len1 < __len2;
}
};
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
__lexicographical_compare_aux(_II1 __first1, _II1 __last1,
_II2 __first2, _II2 __last2)
{
typedef typename iterator_traits<_II1>::value_type _ValueType1;
typedef typename iterator_traits<_II2>::value_type _ValueType2;
const bool __simple =
(__is_byte<_ValueType1>::__value && __is_byte<_ValueType2>::__value
&& !__gnu_cxx::__numeric_traits<_ValueType1>::__is_signed
&& !__gnu_cxx::__numeric_traits<_ValueType2>::__is_signed
&& __is_pointer<_II1>::__value
&& __is_pointer<_II2>::__value
#if __cplusplus > 201703L && __cpp_lib_concepts
// For C++20 iterator_traits<volatile T*>::value_type is non-volatile
// so __is_byte<T> could be true, but we can't use memcmp with
// volatile data.
&& !is_volatile_v<remove_reference_t<iter_reference_t<_II1>>>
&& !is_volatile_v<remove_reference_t<iter_reference_t<_II2>>>
#endif
);
return std::__lexicographical_compare<__simple>::__lc(__first1, __last1,
__first2, __last2);
}
template<typename _ForwardIterator, typename _Tp, typename _Compare>
_GLIBCXX20_CONSTEXPR
_ForwardIterator
__lower_bound(_ForwardIterator __first, _ForwardIterator __last,
const _Tp& __val, _Compare __comp)
{
typedef typename iterator_traits<_ForwardIterator>::difference_type
_DistanceType;
_DistanceType __len = std::distance(__first, __last);
while (__len > 0)
{
_DistanceType __half = __len >> 1;
_ForwardIterator __middle = __first;
std::advance(__middle, __half);
if (__comp(__middle, __val))
{
__first = __middle;
++__first;
__len = __len - __half - 1;
}
else
__len = __half;
}
return __first;
}
/**
* @brief Finds the first position in which @a val could be inserted
* without changing the ordering.
* @param __first An iterator.
* @param __last Another iterator.
* @param __val The search term.
* @return An iterator pointing to the first element <em>not less
* than</em> @a val, or end() if every element is less than
* @a val.
* @ingroup binary_search_algorithms
*/
template<typename _ForwardIterator, typename _Tp>
_GLIBCXX20_CONSTEXPR
inline _ForwardIterator
lower_bound(_ForwardIterator __first, _ForwardIterator __last,
const _Tp& __val)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
__glibcxx_function_requires(_LessThanOpConcept<
typename iterator_traits<_ForwardIterator>::value_type, _Tp>)
__glibcxx_requires_partitioned_lower(__first, __last, __val);
return std::__lower_bound(__first, __last, __val,
__gnu_cxx::__ops::__iter_less_val());
}
/// This is a helper function for the sort routines and for random.tcc.
// Precondition: __n > 0.
inline _GLIBCXX_CONSTEXPR int
__lg(int __n)
{ return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); }
inline _GLIBCXX_CONSTEXPR unsigned
__lg(unsigned __n)
{ return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); }
inline _GLIBCXX_CONSTEXPR long
__lg(long __n)
{ return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); }
inline _GLIBCXX_CONSTEXPR unsigned long
__lg(unsigned long __n)
{ return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); }
inline _GLIBCXX_CONSTEXPR long long
__lg(long long __n)
{ return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); }
inline _GLIBCXX_CONSTEXPR unsigned long long
__lg(unsigned long long __n)
{ return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); }
_GLIBCXX_BEGIN_NAMESPACE_ALGO
/**
* @brief Tests a range for element-wise equality.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @return A boolean true or false.
*
* This compares the elements of two ranges using @c == and returns true or
* false depending on whether all of the corresponding elements of the
* ranges are equal.
*/
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
equal(_II1 __first1, _II1 __last1, _II2 __first2)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_II1>)
__glibcxx_function_requires(_InputIteratorConcept<_II2>)
__glibcxx_function_requires(_EqualOpConcept<
typename iterator_traits<_II1>::value_type,
typename iterator_traits<_II2>::value_type>)
__glibcxx_requires_can_increment_range(__first1, __last1, __first2);
return std::__equal_aux(__first1, __last1, __first2);
}
/**
* @brief Tests a range for element-wise equality.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __binary_pred A binary predicate @link functors
* functor@endlink.
* @return A boolean true or false.
*
* This compares the elements of two ranges using the binary_pred
* parameter, and returns true or
* false depending on whether all of the corresponding elements of the
* ranges are equal.
*/
template<typename _IIter1, typename _IIter2, typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
inline bool
equal(_IIter1 __first1, _IIter1 __last1,
_IIter2 __first2, _BinaryPredicate __binary_pred)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_IIter1>)
__glibcxx_function_requires(_InputIteratorConcept<_IIter2>)
__glibcxx_requires_valid_range(__first1, __last1);
for (; __first1 != __last1; ++__first1, (void)++__first2)
if (!bool(__binary_pred(*__first1, *__first2)))
return false;
return true;
}
#if __cplusplus >= 201103L
// 4-iterator version of std::equal<It1, It2> for use in C++11.
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
__equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2)
{
using _RATag = random_access_iterator_tag;
using _Cat1 = typename iterator_traits<_II1>::iterator_category;
using _Cat2 = typename iterator_traits<_II2>::iterator_category;
using _RAIters = __and_<is_same<_Cat1, _RATag>, is_same<_Cat2, _RATag>>;
if (_RAIters())
{
auto __d1 = std::distance(__first1, __last1);
auto __d2 = std::distance(__first2, __last2);
if (__d1 != __d2)
return false;
return _GLIBCXX_STD_A::equal(__first1, __last1, __first2);
}
for (; __first1 != __last1 && __first2 != __last2;
++__first1, (void)++__first2)
if (!(*__first1 == *__first2))
return false;
return __first1 == __last1 && __first2 == __last2;
}
// 4-iterator version of std::equal<It1, It2, BinaryPred> for use in C++11.
template<typename _II1, typename _II2, typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
inline bool
__equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2,
_BinaryPredicate __binary_pred)
{
using _RATag = random_access_iterator_tag;
using _Cat1 = typename iterator_traits<_II1>::iterator_category;
using _Cat2 = typename iterator_traits<_II2>::iterator_category;
using _RAIters = __and_<is_same<_Cat1, _RATag>, is_same<_Cat2, _RATag>>;
if (_RAIters())
{
auto __d1 = std::distance(__first1, __last1);
auto __d2 = std::distance(__first2, __last2);
if (__d1 != __d2)
return false;
return _GLIBCXX_STD_A::equal(__first1, __last1, __first2,
__binary_pred);
}
for (; __first1 != __last1 && __first2 != __last2;
++__first1, (void)++__first2)
if (!bool(__binary_pred(*__first1, *__first2)))
return false;
return __first1 == __last1 && __first2 == __last2;
}
#endif // C++11
#if __cplusplus > 201103L
#define __cpp_lib_robust_nonmodifying_seq_ops 201304
/**
* @brief Tests a range for element-wise equality.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @return A boolean true or false.
*
* This compares the elements of two ranges using @c == and returns true or
* false depending on whether all of the corresponding elements of the
* ranges are equal.
*/
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
equal(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_II1>)
__glibcxx_function_requires(_InputIteratorConcept<_II2>)
__glibcxx_function_requires(_EqualOpConcept<
typename iterator_traits<_II1>::value_type,
typename iterator_traits<_II2>::value_type>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2);
}
/**
* @brief Tests a range for element-wise equality.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @param __binary_pred A binary predicate @link functors
* functor@endlink.
* @return A boolean true or false.
*
* This compares the elements of two ranges using the binary_pred
* parameter, and returns true or
* false depending on whether all of the corresponding elements of the
* ranges are equal.
*/
template<typename _IIter1, typename _IIter2, typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
inline bool
equal(_IIter1 __first1, _IIter1 __last1,
_IIter2 __first2, _IIter2 __last2, _BinaryPredicate __binary_pred)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_IIter1>)
__glibcxx_function_requires(_InputIteratorConcept<_IIter2>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2,
__binary_pred);
}
#endif // C++14
/**
* @brief Performs @b dictionary comparison on ranges.
* @ingroup sorting_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @return A boolean true or false.
*
* <em>Returns true if the sequence of elements defined by the range
* [first1,last1) is lexicographically less than the sequence of elements
* defined by the range [first2,last2). Returns false otherwise.</em>
* (Quoted from [25.3.8]/1.) If the iterators are all character pointers,
* then this is an inline call to @c memcmp.
*/
template<typename _II1, typename _II2>
_GLIBCXX20_CONSTEXPR
inline bool
lexicographical_compare(_II1 __first1, _II1 __last1,
_II2 __first2, _II2 __last2)
{
#ifdef _GLIBCXX_CONCEPT_CHECKS
// concept requirements
typedef typename iterator_traits<_II1>::value_type _ValueType1;
typedef typename iterator_traits<_II2>::value_type _ValueType2;
#endif
__glibcxx_function_requires(_InputIteratorConcept<_II1>)
__glibcxx_function_requires(_InputIteratorConcept<_II2>)
__glibcxx_function_requires(_LessThanOpConcept<_ValueType1, _ValueType2>)
__glibcxx_function_requires(_LessThanOpConcept<_ValueType2, _ValueType1>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return std::__lexicographical_compare_aux(std::__niter_base(__first1),
std::__niter_base(__last1),
std::__niter_base(__first2),
std::__niter_base(__last2));
}
/**
* @brief Performs @b dictionary comparison on ranges.
* @ingroup sorting_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @param __comp A @link comparison_functors comparison functor@endlink.
* @return A boolean true or false.
*
* The same as the four-parameter @c lexicographical_compare, but uses the
* comp parameter instead of @c <.
*/
template<typename _II1, typename _II2, typename _Compare>
_GLIBCXX20_CONSTEXPR
inline bool
lexicographical_compare(_II1 __first1, _II1 __last1,
_II2 __first2, _II2 __last2, _Compare __comp)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_II1>)
__glibcxx_function_requires(_InputIteratorConcept<_II2>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return std::__lexicographical_compare_impl
(__first1, __last1, __first2, __last2,
__gnu_cxx::__ops::__iter_comp_iter(__comp));
}
#if __cpp_lib_three_way_comparison
// Iter points to a contiguous range of unsigned narrow character type
// or std::byte, suitable for comparison by memcmp.
template<typename _Iter>
concept __is_byte_iter = contiguous_iterator<_Iter>
&& __is_byte<iter_value_t<_Iter>>::__value != 0
&& !__gnu_cxx::__numeric_traits<iter_value_t<_Iter>>::__is_signed;
// Return a struct with two members, initialized to the smaller of x and y
// (or x if they compare equal) and the result of the comparison x <=> y.
template<typename _Tp>
constexpr auto
__min_cmp(_Tp __x, _Tp __y)
{
struct _Res {
_Tp _M_min;
decltype(__x <=> __y) _M_cmp;
};
auto __c = __x <=> __y;
if (__c > 0)
return _Res{__y, __c};
return _Res{__x, __c};
}
/**
* @brief Performs dictionary comparison on ranges.
* @ingroup sorting_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @param __comp A @link comparison_functors comparison functor@endlink.
* @return The comparison category that `__comp(*__first1, *__first2)`
* returns.
*/
template<typename _InputIter1, typename _InputIter2, typename _Comp>
constexpr auto
lexicographical_compare_three_way(_InputIter1 __first1,
_InputIter1 __last1,
_InputIter2 __first2,
_InputIter2 __last2,
_Comp __comp)
-> decltype(__comp(*__first1, *__first2))
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIter1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIter2>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
#if __cpp_lib_is_constant_evaluated
using _Cat = decltype(__comp(*__first1, *__first2));
static_assert(same_as<common_comparison_category_t<_Cat>, _Cat>);
if (!std::is_constant_evaluated())
if constexpr (same_as<_Comp, __detail::_Synth3way>
|| same_as<_Comp, compare_three_way>)
if constexpr (__is_byte_iter<_InputIter1>)
if constexpr (__is_byte_iter<_InputIter2>)
{
const auto [__len, __lencmp]
= std::__min_cmp(__last1 - __first1, __last2 - __first2);
if (__len)
{
const auto __c
= __builtin_memcmp(&*__first1, &*__first2, __len) <=> 0;
if (__c != 0)
return __c;
}
return __lencmp;
}
#endif // is_constant_evaluated
while (__first1 != __last1)
{
if (__first2 == __last2)
return strong_ordering::greater;
if (auto __cmp = __comp(*__first1, *__first2); __cmp != 0)
return __cmp;
++__first1;
++__first2;
}
return (__first2 == __last2) <=> true; // See PR 94006
}
template<typename _InputIter1, typename _InputIter2>
constexpr auto
lexicographical_compare_three_way(_InputIter1 __first1,
_InputIter1 __last1,
_InputIter2 __first2,
_InputIter2 __last2)
{
return std::lexicographical_compare_three_way(__first1, __last1,
__first2, __last2,
compare_three_way{});
}
#endif // three_way_comparison
template<typename _InputIterator1, typename _InputIterator2,
typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
pair<_InputIterator1, _InputIterator2>
__mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _BinaryPredicate __binary_pred)
{
while (__first1 != __last1 && __binary_pred(__first1, __first2))
{
++__first1;
++__first2;
}
return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
}
/**
* @brief Finds the places in ranges which don't match.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @return A pair of iterators pointing to the first mismatch.
*
* This compares the elements of two ranges using @c == and returns a pair
* of iterators. The first iterator points into the first range, the
* second iterator points into the second range, and the elements pointed
* to by the iterators are not equal.
*/
template<typename _InputIterator1, typename _InputIterator2>
_GLIBCXX20_CONSTEXPR
inline pair<_InputIterator1, _InputIterator2>
mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>)
__glibcxx_function_requires(_EqualOpConcept<
typename iterator_traits<_InputIterator1>::value_type,
typename iterator_traits<_InputIterator2>::value_type>)
__glibcxx_requires_valid_range(__first1, __last1);
return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2,
__gnu_cxx::__ops::__iter_equal_to_iter());
}
/**
* @brief Finds the places in ranges which don't match.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __binary_pred A binary predicate @link functors
* functor@endlink.
* @return A pair of iterators pointing to the first mismatch.
*
* This compares the elements of two ranges using the binary_pred
* parameter, and returns a pair
* of iterators. The first iterator points into the first range, the
* second iterator points into the second range, and the elements pointed
* to by the iterators are not equal.
*/
template<typename _InputIterator1, typename _InputIterator2,
typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
inline pair<_InputIterator1, _InputIterator2>
mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _BinaryPredicate __binary_pred)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>)
__glibcxx_requires_valid_range(__first1, __last1);
return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2,
__gnu_cxx::__ops::__iter_comp_iter(__binary_pred));
}
#if __cplusplus > 201103L
template<typename _InputIterator1, typename _InputIterator2,
typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
pair<_InputIterator1, _InputIterator2>
__mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _InputIterator2 __last2,
_BinaryPredicate __binary_pred)
{
while (__first1 != __last1 && __first2 != __last2
&& __binary_pred(__first1, __first2))
{
++__first1;
++__first2;
}
return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
}
/**
* @brief Finds the places in ranges which don't match.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @return A pair of iterators pointing to the first mismatch.
*
* This compares the elements of two ranges using @c == and returns a pair
* of iterators. The first iterator points into the first range, the
* second iterator points into the second range, and the elements pointed
* to by the iterators are not equal.
*/
template<typename _InputIterator1, typename _InputIterator2>
_GLIBCXX20_CONSTEXPR
inline pair<_InputIterator1, _InputIterator2>
mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _InputIterator2 __last2)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>)
__glibcxx_function_requires(_EqualOpConcept<
typename iterator_traits<_InputIterator1>::value_type,
typename iterator_traits<_InputIterator2>::value_type>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2,
__gnu_cxx::__ops::__iter_equal_to_iter());
}
/**
* @brief Finds the places in ranges which don't match.
* @ingroup non_mutating_algorithms
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @param __binary_pred A binary predicate @link functors
* functor@endlink.
* @return A pair of iterators pointing to the first mismatch.
*
* This compares the elements of two ranges using the binary_pred
* parameter, and returns a pair
* of iterators. The first iterator points into the first range, the
* second iterator points into the second range, and the elements pointed
* to by the iterators are not equal.
*/
template<typename _InputIterator1, typename _InputIterator2,
typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
inline pair<_InputIterator1, _InputIterator2>
mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _InputIterator2 __last2,
_BinaryPredicate __binary_pred)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2,
__gnu_cxx::__ops::__iter_comp_iter(__binary_pred));
}
#endif
_GLIBCXX_END_NAMESPACE_ALGO
/// This is an overload used by find algos for the Input Iterator case.
template<typename _InputIterator, typename _Predicate>
_GLIBCXX20_CONSTEXPR
inline _InputIterator
__find_if(_InputIterator __first, _InputIterator __last,
_Predicate __pred, input_iterator_tag)
{
while (__first != __last && !__pred(__first))
++__first;
return __first;
}
/// This is an overload used by find algos for the RAI case.
template<typename _RandomAccessIterator, typename _Predicate>
_GLIBCXX20_CONSTEXPR
_RandomAccessIterator
__find_if(_RandomAccessIterator __first, _RandomAccessIterator __last,
_Predicate __pred, random_access_iterator_tag)
{
typename iterator_traits<_RandomAccessIterator>::difference_type
__trip_count = (__last - __first) >> 2;
for (; __trip_count > 0; --__trip_count)
{
if (__pred(__first))
return __first;
++__first;
if (__pred(__first))
return __first;
++__first;
if (__pred(__first))
return __first;
++__first;
if (__pred(__first))
return __first;
++__first;
}
switch (__last - __first)
{
case 3:
if (__pred(__first))
return __first;
++__first;
// FALLTHRU
case 2:
if (__pred(__first))
return __first;
++__first;
// FALLTHRU
case 1:
if (__pred(__first))
return __first;
++__first;
// FALLTHRU
case 0:
default:
return __last;
}
}
template<typename _Iterator, typename _Predicate>
_GLIBCXX20_CONSTEXPR
inline _Iterator
__find_if(_Iterator __first, _Iterator __last, _Predicate __pred)
{
return __find_if(__first, __last, __pred,
std::__iterator_category(__first));
}
template<typename _InputIterator, typename _Predicate>
_GLIBCXX20_CONSTEXPR
typename iterator_traits<_InputIterator>::difference_type
__count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
{
typename iterator_traits<_InputIterator>::difference_type __n = 0;
for (; __first != __last; ++__first)
if (__pred(__first))
++__n;
return __n;
}
#if __cplusplus >= 201103L
template<typename _ForwardIterator1, typename _ForwardIterator2,
typename _BinaryPredicate>
_GLIBCXX20_CONSTEXPR
bool
__is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2, _BinaryPredicate __pred)
{
// Efficiently compare identical prefixes: O(N) if sequences
// have the same elements in the same order.
for (; __first1 != __last1; ++__first1, (void)++__first2)
if (!__pred(__first1, __first2))
break;
if (__first1 == __last1)
return true;
// Establish __last2 assuming equal ranges by iterating over the
// rest of the list.
_ForwardIterator2 __last2 = __first2;
std::advance(__last2, std::distance(__first1, __last1));
for (_ForwardIterator1 __scan = __first1; __scan != __last1; ++__scan)
{
if (__scan != std::__find_if(__first1, __scan,
__gnu_cxx::__ops::__iter_comp_iter(__pred, __scan)))
continue; // We've seen this one before.
auto __matches
= std::__count_if(__first2, __last2,
__gnu_cxx::__ops::__iter_comp_iter(__pred, __scan));
if (0 == __matches ||
std::__count_if(__scan, __last1,
__gnu_cxx::__ops::__iter_comp_iter(__pred, __scan))
!= __matches)
return false;
}
return true;
}
/**
* @brief Checks whether a permutation of the second sequence is equal
* to the first sequence.
* @ingroup non_mutating_algorithms
* @param __first1 Start of first range.
* @param __last1 End of first range.
* @param __first2 Start of second range.
* @return true if there exists a permutation of the elements in the range
* [__first2, __first2 + (__last1 - __first1)), beginning with
* ForwardIterator2 begin, such that equal(__first1, __last1, begin)
* returns true; otherwise, returns false.
*/
template<typename _ForwardIterator1, typename _ForwardIterator2>
_GLIBCXX20_CONSTEXPR
inline bool
is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
_ForwardIterator2 __first2)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>)
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>)
__glibcxx_function_requires(_EqualOpConcept<
typename iterator_traits<_ForwardIterator1>::value_type,
typename iterator_traits<_ForwardIterator2>::value_type>)
__glibcxx_requires_valid_range(__first1, __last1);
return std::__is_permutation(__first1, __last1, __first2,
__gnu_cxx::__ops::__iter_equal_to_iter());
}
#endif // C++11
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std
// NB: This file is included within many other C++ includes, as a way
// of getting the base algorithms. So, make sure that parallel bits
// come in too if requested.
#ifdef _GLIBCXX_PARALLEL
# include <parallel/algobase.h>
#endif
#endif
| [
"jczhang@bouffalolab.com"
] | jczhang@bouffalolab.com |
d2feaa76c5df77e212ad1e8249fd84fb5643fc7f | 5f67658f61d03a786005752583077a40b42d03b1 | /Sound/UserSoundChannel.cc | 95c60700683b7f19492f05b8f53ea2167c8be95c | [] | no_license | newtonresearch/newton-framework | d0e5c23dfdc5394e0c94e7e1b7de756eac4ed212 | f922bb3ac508c295b155baa0d4dc7c7982b9e2a2 | refs/heads/master | 2022-06-26T21:20:18.121059 | 2022-06-01T17:39:47 | 2022-06-01T17:39:47 | 31,951,762 | 22 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 20,504 | cc | /*
File: SoundChannel.cc
Contains: Sound channel implementation.
We render sound using the AudioUnit framework.
Written by: Newton Research Group, 2007.
*/
#include "UserSoundChannel.h"
#include "SoundErrors.h"
#include "Globals.h"
#include "ROMResources.h"
#include "Lookup.h"
#include "NewtonScript.h"
#include "Unicode.h"
extern Ref ConvertToSoundFrame(RefArg inSound);
extern float VolumeToDecibels(int inVolume);
extern "C" Ref FStrEqual(RefArg inRcvr, RefArg inStr1, RefArg inStr2);
/*------------------------------------------------------------------------------
D a t a
------------------------------------------------------------------------------*/
CFrameSoundChannel * gSoundChannel = NULL;
/*------------------------------------------------------------------------------
G l o b a l S o u n d C h a n n e l
------------------------------------------------------------------------------*/
CFrameSoundChannel *
GlobalSoundChannel(void)
{
if (gSoundChannel == NULL)
{
NewtonErr err;
gSoundChannel = new CFrameSoundChannel;
if ((err = MemError()) != noErr)
ThrowErr(exFrames, err);
int outputDeviceNumber = kSoundDefaultDevice;
RefVar outputDevice(GetGlobalVar(SYMA(userConfiguration)));
outputDevice = GetProtoVariable(outputDevice, SYMA(outputDevice), NULL);
if (ISINT(outputDevice))
outputDeviceNumber = RINT(outputDevice);
if ((err = gSoundChannel->open(0, outputDeviceNumber)) != noErr)
{
delete gSoundChannel;
gSoundChannel = NULL;
ThrowErr(exFrames, err);
}
}
return gSoundChannel;
}
NewtonErr
SafeCodecInit(CSoundCodec * inCodec, CodecBlock * inParms)
{
NewtonErr err = noErr;
newton_try
{
err = inCodec->init(inParms);
}
newton_catch_all
{
err = kSndErrGeneric;
}
end_try;
return err;
}
NewtonErr
SafeCodecDelete(CSoundCodec * inCodec)
{
NewtonErr err = noErr;
newton_try
{
inCodec->destroy();
}
newton_catch_all
{
err = kSndErrGeneric;
}
end_try;
return err;
}
void
ConvertCodecBlock(SoundBlock * inSound, CodecBlock * outCodec)
{
outCodec->x00 = 0;
outCodec->data = inSound->data;
outCodec->dataSize = inSound->dataSize;
outCodec->dataType = inSound->dataType;
outCodec->comprType = inSound->comprType;
outCodec->sampleRate = inSound->sampleRate;
outCodec->frame = inSound->frame;
}
void
ConvertCodecBlock(CodecBlock * inCodec, SoundBlock * outSound)
{
if (inCodec->x00 >= 0)
{
outSound->data = inCodec->data;
outSound->dataSize = inCodec->dataSize;
outSound->dataType = inCodec->dataType;
outSound->comprType = inCodec->comprType;
outSound->sampleRate = inCodec->sampleRate;
outSound->frame = inCodec->frame;
}
}
#pragma mark -
/*------------------------------------------------------------------------------
C U S o u n d C a l l b a c k
------------------------------------------------------------------------------*/
CUSoundCallback::CUSoundCallback()
{ }
CUSoundCallback::~CUSoundCallback()
{ }
CUSoundCallbackProc::CUSoundCallbackProc()
: fCallback(NULL)
{ }
CUSoundCallbackProc::~CUSoundCallbackProc()
{ }
void
CUSoundCallbackProc::setCallback(SoundCallbackProcPtr inCallback)
{
fCallback = inCallback;
}
void
CUSoundCallbackProc::complete(SoundBlock * inSound, int inState, NewtonErr inResult)
{
if (fCallback != NULL)
fCallback(inSound, inState, inResult);
}
#pragma mark -
/*------------------------------------------------------------------------------
C U S o u n d C h a n n e l
------------------------------------------------------------------------------*/
CUSoundChannel::CUSoundChannel()
{
fState = 0;
fChannelId = 0;
fCodecChannelId = 0;
fUniqueId = 0;
fActiveNodes = NULL;
fRecycledNodes = NULL;
fVolume = INFINITY; // huh? in decibels, surely, => 0
fGain = 128;
f34 = 0;
f38 = 0;
#if defined(correct)
GestaltVolumeInfo volumeInfo;
CUGestalt gestalt;
gestalt.gestalt(kGestalt_Ext_VolumeInfo, &gestaltInfo, sizeof(gestaltInfo));
if (volumeInfo.x02)
fState |= 0x80;
#endif
}
CUSoundChannel::~CUSoundChannel()
{
close();
for (SoundNode * node = fRecycledNodes, * next; node != NULL; node = next)
{
next = node->next;
delete node;
}
}
NewtonErr
CUSoundChannel::open(int inInputDevice, int inOutputDevice)
{
NewtonErr err;
XTRY
{
init(kUserSndId); // CEventHandler base class function
XFAILNOT(gSoundPort, err = kSndErrGeneric;)
int channelSelector, codecSelector;
CUSoundReply reply;
if (inInputDevice == 0)
{
fState |= kSoundInactive;
channelSelector = kSndOpenOutputChannel;
codecSelector = kSndOpenDecompressorChannel;
}
else
{
fState |= kSoundRecording;
channelSelector = kSndOpenInputChannel;
codecSelector = kSndOpenCompressorChannel;
}
XFAIL(err = sendImmediate(channelSelector, 0, inOutputDevice, &reply, sizeof(reply)))
XFAIL(err = reply.fError)
fChannelId = reply.fChannel;
XFAIL(err = sendImmediate(codecSelector, 0, fChannelId, &reply, sizeof(reply)))
XFAILIF(err = reply.fError, close();) // no codec required for this channel
fCodecChannelId = reply.fChannel;
}
XENDTRY;
return err;
}
NewtonErr
CUSoundChannel::close(void)
{
NewtonErr err;
XTRY
{
NewtonErr err1 = noErr, err2 = noErr;
CUSoundReply reply;
if (fCodecChannelId != 0)
err1 = sendImmediate(kSndCloseChannel, fCodecChannelId, 0, &reply, sizeof(reply));
if (fChannelId != 0)
err2 = sendImmediate(kSndCloseChannel, fChannelId, 0, &reply, sizeof(reply));
XFAIL((err = err1) != noErr || (err = err2) != noErr)
err = reply.fError;
fChannelId = 0;
fCodecChannelId = 0;
abortBusy();
}
XENDTRY;
return err;
}
NewtonErr
CUSoundChannel::schedule(SoundBlock * inSound, CUSoundCallback * inCallback)
{
NewtonErr err;
SoundNode * theNode = NULL;
XTRY
{
if (fVolume == -INFINITY && (fState & 0x80) != 0)
fVolume = getVolume();
ULong channelId = (inSound->codec == NULL) ? fChannelId : fCodecChannelId;
XFAILNOT(inSound->comprType == kSampleStandard || inSound->comprType == kSampleLinear || inSound->comprType == kSampleMuLaw, err = kSndErrBadConfiguration;)
XFAILIF(channelId == 0, err = kSndErrChannelIsClosed;)
XFAIL(err = makeNode(&theNode))
theNode->cb = inCallback;
theNode->request.fChannel = channelId;
theNode->request.fSelector = kSndScheduleNode;
theNode->request.fValue = theNode->id;
theNode->request.fSound = *inSound;
theNode->request.fVolume = fVolume;
int offset = inSound->start;
int count = inSound->count;
int length = inSound->dataSize;
if (offset < 0 || offset > length)
offset = 0;
if (count <= 0 || offset + count > length)
count = length - offset;
theNode->request.fSound.start = offset;
theNode->request.fSound.count = count;
theNode->request.fSound.data = (char *)inSound->data + (offset * inSound->dataType) / 8;
#if !defined(forFramework)
XFAIL(err = gSoundPort->sendRPC(&theNode->msg, &theNode->request, sizeof(CUSoundNodeRequest), &theNode->reply, sizeof(CUSoundNodeReply)))
#endif
theNode->next = fActiveNodes;
fActiveNodes = theNode;
}
XENDTRY;
XDOFAIL(err)
{
if (theNode != NULL)
freeNode(theNode);
}
XENDFAIL;
return err;
}
NewtonErr
CUSoundChannel::cancel(ULong inRefCon)
{
NewtonErr err;
XTRY
{
XFAILNOT(fChannelId, err = kSndErrChannelIsClosed;)
SoundNode * node = findRefCon(inRefCon);
XFAILNOT(node, err = kSndErrNoSamples;)
CUSoundReply reply;
err = sendImmediate(kSndCancelNode, fChannelId, node->id, &reply, sizeof(reply));
if (err == noErr)
err = reply.fError;
}
XENDTRY;
return err;
}
NewtonErr
CUSoundChannel::start(bool inAsync)
{
NewtonErr err;
XTRY
{
XFAILNOT(fCodecChannelId, err = kSndErrChannelIsClosed;)
CUSoundReply reply;
err = sendImmediate(inAsync ? kSndStartChannel : kSndStartChannelSync, fCodecChannelId, 0, &reply, sizeof(reply));
if (err == noErr)
err = reply.fError;
XFAIL(err)
fState &= ~kSoundPaused;
if (inAsync)
fState |= kSoundPlaying;
}
XENDTRY;
return err;
}
NewtonErr
CUSoundChannel::pause(SoundBlock * outSound, long * outIndex)
{
NewtonErr err;
XTRY
{
if (outIndex != NULL)
*outIndex = -1;
XFAILNOT(fChannelId, err = kSndErrChannelIsClosed;)
if ((fState & kSoundPlayPaused) != 0)
err = start(true);
else
{
CUSoundNodeReply reply;
err = sendImmediate(kSndPauseChannel, fCodecChannelId, 0, &reply, sizeof(reply));
if (err == noErr)
err = reply.fError;
XFAIL(err)
fState |= kSoundPlayPaused;
SoundNode * node = findNode(reply.f14);
if (node != NULL)
{
if (outSound != NULL)
*outSound = node->request.fSound;
if (outIndex != NULL)
*outIndex = node->request.fSound.start + reply.f1C;
}
}
}
XENDTRY;
return err;
}
NewtonErr
CUSoundChannel::stop(SoundBlock * outSound, long * outIndex)
{
NewtonErr err = noErr;
XTRY
{
if (outIndex != NULL)
*outIndex = -1;
XFAILNOT(fChannelId, err = kSndErrChannelIsClosed;)
if ((fState & kSoundPlaying) != 0)
{
CUSoundNodeReply reply;
err = sendImmediate(kSndStopChannel, fCodecChannelId, 0, &reply, sizeof(reply));
if (err == noErr)
err = reply.fError;
XFAIL(err)
fState &= ~(kSoundPlaying|kSoundPlayPaused);
SoundNode * node = findNode(reply.f14);
if (node != NULL)
{
if (outSound != NULL)
*outSound = node->request.fSound;
if (outIndex != NULL)
*outIndex = node->request.fSound.start + reply.f1C;
}
abortBusy();
}
}
XENDTRY;
return err;
}
void
CUSoundChannel::abortBusy(void)
{
for (SoundNode * node = fActiveNodes, * next; node != NULL; node = next)
{
CUSoundCallback * callback;
#if !defined(forFramework)
node->msg.abort();
#endif
next = node->next;
if ((callback = node->cb) != NULL)
callback->complete(&node->request.fSound, kSoundAborted, kSndErrCancelled);
freeNode(node);
}
fActiveNodes = NULL;
}
void
CUSoundChannel::setOutputDevice(int inDevice)
{
f38 = inDevice;
if (fChannelId != 0)
{
CUSoundReply reply;
sendImmediate(kSndSetOutputDevice, fChannelId, inDevice, &reply, sizeof(reply));
}
}
/* -----------------------------------------------------------------------------
Watch that float does not get silently converted to int!
----------------------------------------------------------------------------- */
float
CUSoundChannel::setVolume(float inDecibels)
{
fVolume = inDecibels;
if (fActiveNodes != NULL || this == gSoundChannel)
{
CUSoundReply reply;
if (sendImmediate(kSndSetVolume, 0, *(ULong *)&inDecibels, &reply, sizeof(reply)) == noErr)
inDecibels = *(float *)&reply.fValue;
}
return inDecibels;
}
float
CUSoundChannel::getVolume(void)
{
float db = fVolume;
if ((fActiveNodes != NULL || this == gSoundChannel)
&& (fState & 0x80) != 0)
{
CUSoundReply reply;
if (sendImmediate(kSndGetVolume, 0, 0, &reply, sizeof(reply)) == noErr)
db = *(float *)&reply.fValue;
}
return db;
}
void
CUSoundChannel::setInputGain(int inGain)
{
fGain = inGain;
CUSoundReply reply;
sendImmediate(kSndSetInputGain, fChannelId, inGain, &reply, sizeof(reply));
}
int
CUSoundChannel::getInputGain(void)
{
return fGain;
}
NewtonErr
CUSoundChannel::sendImmediate(int inSelector, ULong inChannel, ULong inValue, CUSoundReply * ioReply, size_t inReplySize)
{
size_t size;
CUSoundRequest request(inChannel, inSelector, inValue);
return gSoundPort->sendRPC(&size, &request, sizeof(request), ioReply, inReplySize);
}
void
CUSoundChannel::eventCompletionProc(CUMsgToken * inToken, size_t * inSize, CEvent * inEvent)
{
for (SoundNode * node = fActiveNodes, * prev = NULL; node != NULL; prev = node, node = node->next)
{
// look for node
if (node->id == ((CUSoundNodeReply *)inEvent)->f14)
{
CUSoundCallback * callback;
// remove node from active list
if (prev != NULL)
prev->next = node->next;
else
fActiveNodes = node->next;
// call back
if ((callback = node->cb) != NULL)
callback->complete(&node->request.fSound, ((CUSoundNodeReply *)inEvent)->fError, ((CUSoundNodeReply *)inEvent)->fError); // sic; surely state == kSoundCompleted?
// free node resources
freeNode(node);
break;
}
}
}
NewtonErr
CUSoundChannel::makeNode(SoundNode ** outNode)
{
NewtonErr err = noErr;
SoundNode * theNode;
if ((theNode = fRecycledNodes) != NULL)
{
fRecycledNodes = fRecycledNodes->next;
}
else
{
XTRY
{
theNode = new SoundNode;
XFAILIF(theNode == NULL, err = MemError();)
#if !defined(forFramework)
XFAIL(err = theNode->msg.init(true))
XFAIL(err = theNode->msg.setCollectorPort(*gAppWorld->getMyPort()))
err = theNode->msg.setUserRefCon((OpaqueRef)this);
#endif
}
XENDTRY;
}
theNode->id = uniqueId();
theNode->next = NULL;
theNode->cb = NULL;
*outNode = theNode;
return err;
}
SoundNode *
CUSoundChannel::findNode(ULong inId)
{
SoundNode * node;
for (node = fActiveNodes; node != NULL; node = node->next)
if (node->id == inId)
break;
return node;
}
SoundNode *
CUSoundChannel::findRefCon(OpaqueRef inRefCon)
{
SoundNode * node;
for (node = fActiveNodes; node != NULL; node = node->next)
if ((OpaqueRef)node->request.fSound.frame == inRefCon) // x44
break;
return node;
}
void
CUSoundChannel::freeNode(SoundNode * inNode)
{
unsigned count = 0;
SoundNode * node;
for (node = fRecycledNodes; node != NULL; node = node->next)
count++;
if (count < 2)
{
inNode->next = fRecycledNodes;
fRecycledNodes = inNode;
}
else if (inNode != NULL)
delete inNode;
if (fActiveNodes == NULL)
fState &= ~(kSoundPlaying|kSoundPlayPaused);
}
ULong
CUSoundChannel::uniqueId(void)
{
do {
if (++fUniqueId == 0) fUniqueId = 1;
} while (findNode(fUniqueId) != NULL);
return fUniqueId;
}
#pragma mark -
/*------------------------------------------------------------------------------
C F r a m e S o u n d C a l l b a c k
------------------------------------------------------------------------------*/
CFrameSoundCallback::~CFrameSoundCallback()
{ }
void
CFrameSoundCallback::complete(SoundBlock * inSound, int inState, NewtonErr inResult)
{
RefVar context(*inSound->frame);
delete inSound->frame;
UnlockRef(GetProtoVariable(context, SYMA(samples), NULL));
fChannel->deleteCodec(inSound);
newton_try
{
RefVar callback(GetProtoVariable(context, SYMA(callback), NULL));
if (NOTNIL(callback))
NSSendProto(context, SYMA(callback), MAKEINT(inState), MAKEINT(inResult));
}
newton_catch_all
{ }
end_try;
}
#pragma mark -
/*------------------------------------------------------------------------------
C F r a m e S o u n d C h a n n e l
------------------------------------------------------------------------------*/
CFrameSoundChannel::CFrameSoundChannel()
: fCodec(NULL), fIsCodecReady(false), fCallback(this)
{ }
CFrameSoundChannel::~CFrameSoundChannel()
{ }
NewtonErr
CFrameSoundChannel::open(int inInputDevice, int inOutputDevice)
{
NewtonErr err;
err = CUSoundChannel::open(inInputDevice, inOutputDevice);
if (IsString(fCodecName))
{
char codecName[128];
ConvertFromUnicode(GetUString(fCodecName), codecName);
if (codecName[0] == 'T') codecName[0] = 'C';
fCodec = (CSoundCodec *)MakeByName("CSoundCodec", codecName);
}
return err;
}
void
CFrameSoundChannel::close(void)
{
CUSoundChannel::close();
if (fCodec != NULL)
{
SafeCodecDelete(fCodec);
fCodec = NULL;
fIsCodecReady = false;
}
}
NewtonErr
CFrameSoundChannel::schedule(RefArg inSound)
{
SoundBlock snd;
convert(inSound, &snd);
return CUSoundChannel::schedule(&snd, &fCallback);
}
NewtonErr
CFrameSoundChannel::convert(RefArg inSound, SoundBlock * outParms)
{
NewtonErr err;
RefVar item;
RefVar sndFrame(ConvertToSoundFrame(inSound));
outParms->frame = NULL;
outParms->codec = NULL;
XTRY
{
item = GetProtoVariable(sndFrame, SYMA(sndFrameType), NULL);
XFAILNOT(EQ(item, SYMA(codec)) || EQ(item, SYMA(simpleSound)), err = kSndErrBadConfiguration;)
if (EQ(item, SYMA(codec)))
openCodec(sndFrame, outParms);
item = GetProtoVariable(sndFrame, SYMA(compressionType), NULL);
outParms->comprType = NOTNIL(item) ? RINT(item) : kSampleStandard;
XFAILNOT(outParms->comprType == kSampleStandard || outParms->comprType == kSampleLinear || outParms->comprType == kSampleMuLaw, err = kSndErrBadConfiguration;)
int dataType;
item = GetProtoVariable(sndFrame, SYMA(dataType), NULL);
if (NOTNIL(item))
{
dataType = RINT(item);
if (dataType == 8 || dataType == 1)
dataType = k8Bit;
else if (dataType == 16 || dataType == 2)
dataType = k16Bit;
else
XFAIL(err = kSndErrBadConfiguration)
}
else
dataType = (outParms->comprType == kSampleStandard) ? k8Bit : k16Bit;
outParms->dataType = dataType;
item = GetProtoVariable(sndFrame, SYMA(samples), NULL);
LockRef(item);
outParms->data = BinaryData(item);
if (outParms->codec != NULL)
outParms->dataSize = Length(item);
else
outParms->dataSize = Length(item) / (dataType/8); // for simpleSound, dataSize is number of samples
item = GetProtoVariable(sndFrame, SYMA(Length), NULL);
if (NOTNIL(item))
outParms->dataSize = RINT(item);
item = GetProtoVariable(sndFrame, SYMA(samplingRate), NULL); // can be int, Fixed or double
if (IsReal(item))
outParms->sampleRate = CDouble(item);
else if (ISINT(item))
outParms->sampleRate = (float)RINT(item);
else if (IsBinary(item)) {
#if defined(hasByteSwapping)
// assume sound is imported from NTK and is therefore BIG-ENDIAN
// it’s only binary so we can’t detect it and fix it at init
Fixed rate = *(Fixed *)BinaryData(item);
rate = BYTE_SWAP_LONG(rate);
outParms->sampleRate = rate / (Fixed)0x00010000;
#else
outParms->sampleRate = *(Fixed *)BinaryData(item) / (Fixed)0x00010000; // FixedToFloat
#endif
} else
outParms->sampleRate = 22026.43;
XFAILIF(outParms->sampleRate < 0, err = kSndErrBadConfiguration;)
outParms->frame = new RefStruct(sndFrame);
XFAIL(err = MemError())
item = GetProtoVariable(sndFrame, SYMA(start), NULL);
outParms->start = ISINT(item) ? RINT(item) : 0;
item = GetProtoVariable(sndFrame, SYMA(count), NULL);
outParms->count = ISINT(item) ? RINT(item) : outParms->dataSize;
item = GetProtoVariable(sndFrame, SYMA(loops), NULL);
outParms->loops = ISINT(item) ? RINT(item) : 0;
item = GetProtoVariable(sndFrame, SYMA(volume), NULL); // can be int or double
if (ISINT(item))
outParms->volume = VolumeToDecibels(RINT(item));
else if (IsReal(item))
outParms->volume = CDouble(item);
else
outParms->volume = INFINITY;
err = initCodec(outParms);
}
XENDTRY;
XDOFAIL(err)
{
deleteCodec(outParms);
if (outParms->frame != NULL)
{
RefVar samples(GetProtoVariable(sndFrame, SYMA(samples), NULL));
UnlockRef(samples);
delete outParms->frame;
}
ThrowErr(exFrames, err);
}
XENDFAIL;
return noErr;
}
NewtonErr
CFrameSoundChannel::openCodec(RefArg inSound, SoundBlock * outParms)
{
NewtonErr err = noErr;
XTRY
{
RefVar item;
item = GetProtoVariable(inSound, SYMA(bufferSize), NULL);
outParms->bufferSize = ISINT(item) ? RINT(item) : 0;
item = GetProtoVariable(inSound, SYMA(bufferCount), NULL);
outParms->bufferCount = ISINT(item) ? RINT(item) : 0;
item = GetProtoVariable(inSound, SYMA(codecName), NULL);
XFAILNOT(IsString(item), err = kNSErrNotAString;)
if (IsString(fCodecName) && NOTNIL(FStrEqual(RA(NILREF), item, fCodecName)))
outParms->codec = fCodec;
else
{
char codecName[128];
ConvertFromUnicode(GetUString(item), codecName);
if (codecName[0] == 'T') codecName[0] = 'C';
outParms->codec = (CSoundCodec *)MakeByName("CSoundCodec", codecName);
XFAILNOT(outParms->codec, if ((err = MemError()) == noErr) err = kSndErrBadConfiguration;)
}
}
XENDTRY;
return err;
}
NewtonErr
CFrameSoundChannel::initCodec(SoundBlock * ioParms)
{
NewtonErr err = noErr;
XTRY
{
if (ioParms->codec != NULL)
{
CodecBlock codecParms;
bool isThisCodec = (ioParms->codec == fCodec);
ConvertCodecBlock(ioParms, &codecParms);
if (isThisCodec && fIsCodecReady)
{
codecParms.dataType = fDataType;
codecParms.comprType = fComprType;
codecParms.sampleRate = fSampleRate;
}
else
{
XFAIL(err = SafeCodecInit(ioParms->codec, &codecParms))
if (isThisCodec)
{
fCodecParms = codecParms;
fIsCodecReady = true;
}
}
ConvertCodecBlock(&codecParms, ioParms);
}
}
XENDTRY;
return err;
}
NewtonErr
CFrameSoundChannel::deleteCodec(SoundBlock * inParms)
{
NewtonErr err = noErr;
if (inParms->codec != fCodec)
err = SafeCodecDelete(inParms->codec);
inParms->codec = NULL;
return err;
}
| [
"simon@newtonresearch.org"
] | simon@newtonresearch.org |
45604b617d97b904063081eac31fa70a4b42a282 | bbf09754891dd483c27c70559ff2ab1dedd822f5 | /Lab2/time.cpp | 6099eac49b81136ae888ceb8ece2d08fc9bbc9e6 | [] | no_license | nolandonley14/csc245 | 4b5b0e790cab1182c41211b6ca260199d627554f | 373a07ce1c974ead89645b8982605dcb82a26135 | refs/heads/main | 2023-02-24T00:37:06.405826 | 2021-02-02T15:53:34 | 2021-02-02T15:53:34 | 335,335,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,222 | cpp | //******************************************************************
// IMPLEMENTATION FILE (time.cpp)
// This file implements the Time member functions
//******************************************************************
#include <iostream>
using namespace std;
#include "time.h"
// Private members of class:
// int hrs;
// int mins;
// int secs;
//******************************************************************
Time::Time( /* in */ int initHrs,
/* in */ int initMins,
/* in */ int initSecs )
// Constructor
// Precondition:
// 0 <= initHrs <= 23 && 0 <= initMins <= 59
// && 0 <= initSecs <= 59
// Postcondition:
// hrs == initHrs && mins == initMins && secs == initSecs
{
hrs = initHrs;
mins = initMins;
secs = initSecs;
}
//******************************************************************
Time::Time()
// Default constructor
// Postcondition:
// hrs == 0 && mins == 0 && secs == 0
{
hrs = 0;
mins = 0;
secs = 0;
}
//******************************************************************
void Time::WriteAmPm() const {
bool am;
int tempHrs;
am = (hrs <= 11);
if (hrs == 0)
tempHrs = 12;
else if (hrs >= 13)
tempHrs = hrs -12;
else
tempHrs = hrs;
if (tempHrs < 10)
cout << '0';
cout << tempHrs << ':';
if (mins < 10)
cout << '0';
cout << mins << ':';
if (secs < 10)
cout << '0';
cout << secs;
if (am)
cout << " AM";
else
cout << " PM";
cout << endl;
}
//******************************************************************
Time::~Time()
{
cout << "Destructor Called" << endl;
}
//******************************************************************
void Time::Mealtime() const {
if (hrs == 8 && mins == 0 && secs == 0)
cout << "Breakfast" << endl;
if (hrs == 12 && mins == 0 && secs == 0)
cout << "Lunch" << endl;
if (hrs == 19 && mins == 0 && secs == 0)
cout << "Dinner" << endl;
}
//******************************************************************
void Time::Set( /* in */ int hours,
/* in */ int minutes,
/* in */ int seconds )
// Precondition:
// 0 <= hours <= 23 && 0 <= minutes <= 59
// && 0 <= seconds <= 59
// Postcondition:
// hrs == hours && mins == minutes && secs == seconds
{
hrs = hours;
mins = minutes;
secs = seconds;
}
//******************************************************************
void Time::Increment()
// Postcondition:
// Time has been advanced by one second, with
// 23:59:59 wrapping around to 0:0:0
{
secs++;
if (secs > 59)
{
secs = 0;
mins++;
if (mins > 59)
{
mins = 0;
hrs++;
if (hrs > 23)
hrs = 0;
}
}
}
//******************************************************************
void Time::Write() const
// Postcondition:
// Time has been output in the form HH:MM:SS
{
if (hrs < 10)
cout << '0';
cout << hrs << ':';
if (mins < 10)
cout << '0';
cout << mins << ':';
if (secs < 10)
cout << '0';
cout << secs << endl;
}
//******************************************************************
bool Time::Equal( /* in */ Time otherTime ) const
// Postcondition:
// Function value == TRUE, if this time equals otherTime
// == FALSE, otherwise
{
return (hrs == otherTime.hrs && mins == otherTime.mins &&
secs == otherTime.secs);
}
//******************************************************************
bool Time::LessThan( /* in */ Time otherTime ) const
// Precondition:
// This time and otherTime represent times in the
// same day
// Postcondition:
// Function value == TRUE, if this time is earlier
// in the day than otherTime
// == FALSE, otherwise
{
return (hrs < otherTime.hrs ||
hrs == otherTime.hrs && mins < otherTime.mins ||
hrs == otherTime.hrs && mins == otherTime.mins
&& secs < otherTime.secs);
}
| [
"nolandonley14@gmail.com"
] | nolandonley14@gmail.com |
799d8e1c956ac81b50e889b6b8efae302f1cc5e8 | ae1bb960e93468819ab8fa14e6b07cd111b885c0 | /First_year/Triannual1/Classwork/Parte 1/5.cpp | 05ecfca41c3e8427790520589746e9fefdb32578 | [] | no_license | Asmilex/CppUniversityProjects | b50deb5a0e480e35834ba832234f0df98923505e | 37d074b32d0e9daed4c03b15b212e9ebe13c9555 | refs/heads/master | 2021-10-11T18:16:56.572056 | 2019-01-28T23:30:03 | 2019-01-28T23:30:03 | 114,488,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int a,b,c,e,p //no están bien declaradas las variables con respecto al ejercicio 13, esto y el cout
cout <<"Valores de a,b,c,d,e respectivamente: \n";
cin >>a; cin >>b; cin >>c; cin >>e; cin >>e;
double result=atan2(c+exp*(2)*b*,);
cout <<"resultado" <<result;
}
| [
"andresmm@outlook.com"
] | andresmm@outlook.com |
c7ee5a9d2490573993395e512e44e758854cff21 | c1c292d122b6cbccd5d1cb428d14573393df1943 | /game_logic_lib/include/MainLoopData.h | 33774c625b62365570f8bd402174b2405759c696 | [] | no_license | ChausV/pacman | 272591c6169a433d0083e2e3ad6f8d3d907e5f31 | 10a46f97f2e95cce48aa57f5386d2c162c617854 | refs/heads/master | 2020-04-11T18:29:01.942172 | 2018-12-25T08:22:25 | 2018-12-25T08:22:25 | 162,000,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h | #ifndef MAIN_LOOP_DATA_H
#define MAIN_LOOP_DATA_H
#include <chrono>
struct MainLoopData
{
int input;
unsigned frames_counter;
std::chrono::steady_clock::time_point start;
bool pause;
float game_time;
float frame_time;
MainLoopData()
: input(0),
frames_counter(0u),
start(std::chrono::steady_clock::now()),
pause(false),
game_time(0.0f),
frame_time(0.25f)
{}
};
#endif // MAIN_LOOP_DATA_H
| [
"chausvm@gmail.com"
] | chausvm@gmail.com |
1d603bd2eb9a8a70577c316c8cbda467037d51c6 | 933ca5c936441f56c9925c8e617102174c54e392 | /src/server/game/Tools/PlayerDump.h | f92c22ee96c026d0f4983041a986e63431a0e8dd | [] | no_license | FreedomEmu/FreedomEmu | 0900d088d5bde1ddcb2045080a20e195931620ac | 0b2c2db8be925d0dc623da048b058c74a3e35515 | refs/heads/master | 2020-05-18T08:50:00.575392 | 2012-06-29T12:37:30 | 2012-06-29T12:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,029 | h | /*
* Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010 - 2012 Myth Project <http://mythprojectnetwork.blogspot.com/>
*
* Myth Project's source is based on the Trinity Project source, you can find the
* link to that easily in Trinity Copyrights. Myth Project is a private community.
* To get access, you either have to donate or pass a developer test.
* You can't share Myth Project's sources! Only for personal use.
*/
#ifndef _PLAYER_DUMP_H
#define _PLAYER_DUMP_H
#include <string>
#include <map>
#include <set>
enum DumpTableType
{
DTT_CHARACTER, // // characters
DTT_CHAR_TABLE, // // character_achievement, character_achievement_progress,
// character_action, character_aura, character_homebind,
// character_queststatus, character_queststatus_rewarded, character_reputation,
// character_spell, character_spell_cooldown, character_ticket, character_talent
DTT_EQSET_TABLE, // <- guid // character_equipmentsets
DTT_INVENTORY, // -> item guids collection // character_inventory
DTT_MAIL, // -> mail ids collection // mail
// -> item_text
DTT_MAIL_ITEM, // <- mail ids // mail_items
// -> item guids collection
DTT_ITEM, // <- item guids // item_instance
// -> item_text
DTT_ITEM_GIFT, // <- item guids // character_gifts
DTT_PET, // -> pet guids collection // character_pet
DTT_PET_TABLE, // <- pet guids // pet_aura, pet_spell, pet_spell_cooldown
};
enum DumpReturn
{
DUMP_SUCCESS,
DUMP_FILE_OPEN_ERROR,
DUMP_TOO_MANY_CHARS,
DUMP_UNEXPECTED_END,
DUMP_FILE_BROKEN,
DUMP_CHARACTER_DELETED
};
class PlayerDump
{
protected:
PlayerDump() { }
};
class PlayerDumpWriter : public PlayerDump
{
public:
PlayerDumpWriter() { }
bool GetDump(uint32 guid, std::string& dump);
DumpReturn WriteDump(const std::string& file, uint32 guid);
private:
typedef std::set<uint32> GUIDs;
bool DumpTable(std::string& dump, uint32 guid, char const*tableFrom, char const*tableTo, DumpTableType type);
std::string GenerateWhereStr(char const* field, GUIDs const& guids, GUIDs::const_iterator& itr);
std::string GenerateWhereStr(char const* field, uint32 guid);
GUIDs pets;
GUIDs mails;
GUIDs items;
};
class PlayerDumpReader : public PlayerDump
{
public:
PlayerDumpReader() { }
DumpReturn LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid);
};
#endif
| [
"zulhellwow@hotmail.com"
] | zulhellwow@hotmail.com |
38fc842c56ba6ec982118a9e911df6f9540871a1 | ae894b872d52f8e367642b621f7ce2751e51ed0e | /ConsoleApplication2/ConsoleApplication2.cpp | 898730ef3539b8f55c1764bd0e4ea8c26602b531 | [] | no_license | giftchoi/test_for_vs | 5776e8d84bea678e2b609402166b81e1bb3ac911 | e0b1484bb4c96a5a62d9823b4d05b2eda1090651 | refs/heads/master | 2021-01-23T02:53:48.229115 | 2015-05-12T08:22:52 | 2015-05-12T08:22:52 | 35,473,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | cpp | // ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "ConsoleApplication2.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
void findfile(CString filename);
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
findfile(_T("*.*"));
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
void findfile(CString filename){
CFileFind finder;
BOOL bWorking = finder.FindFile(filename);
while (bWorking){
bWorking = finder.FindNextFileW();
if (finder.IsDirectory()){
filename = finder.GetFilePath() + _T("\\*");
findfile(filename);
}
else wcout << (LPCTSTR)finder.GetFileName() << endl;
}
}
| [
"giftchoi@naver.com"
] | giftchoi@naver.com |
c2f6f6bda817b73bde5d7e14a704a2fc145c395c | 35f17313b43be3d0eb569fe6fb83c95ca8ab8ef3 | /basic/Example.h | 6100dd6d38468cda598723cede8594cc9cc8957e | [] | no_license | foxlf823/nodner | 0698c1b57e35746db82e0b37502e1c3f9be10b62 | 96f1ab7d68463ca0830c6595fc2e8aac1f7c2fa6 | refs/heads/master | 2021-01-12T03:46:19.818733 | 2017-07-06T02:18:57 | 2017-07-06T02:18:57 | 78,263,198 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h | /*
* Example.h
*
* Created on: Mar 17, 2015
* Author: mszhang
*/
#ifndef SRC_EXAMPLE_H_
#define SRC_EXAMPLE_H_
#include "MyLib.h"
using namespace std;
struct Feature {
public:
vector<string> words; // actually only words[0] is used
vector<string> types; // other kinds of features, such as POS
public:
Feature() {
}
//virtual ~Feature() {
//
//}
void clear() {
words.clear();
types.clear();
}
};
class Example { // one example corresponds to one sentence
public:
vector<vector<dtype> > m_labels;
vector<dtype> m_labels_relation;
int formerStart;
int formerEnd;
int latterStart;
int latterEnd;
vector<int> _idxForSeq1;
vector<int> _idxForSeq2;
bool isRelation;
vector<Feature> m_features; // one feature corresponds to one word
public:
Example()
{
}
virtual ~Example()
{
}
void clear()
{
m_features.clear();
clearVec(m_labels);
m_labels_relation.clear();
}
};
#endif /* SRC_EXAMPLE_H_ */
| [
"foxlf823@qq.com"
] | foxlf823@qq.com |
7a46ead8e904be513070dc182f829ada6929b8fc | bc267d395c514c9c454304d0b5f187cf5ded3d93 | /src/WavDataSource.cc | c42d463652b2bbed9f331ab2849c95eb4a5620d7 | [] | no_license | greggiacovelli/audio | 1de783c4237ffc361667400bde52f5883ecebf92 | ca32cdd1a9f920c87edc681ecc67741a013cef62 | refs/heads/master | 2020-12-24T17:08:51.917855 | 2013-07-11T20:35:32 | 2013-07-11T20:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,770 | cc | /**
* @file
* Handle feeding input into the SinkPlayer
*/
/******************************************************************************
* Copyright 2013, doubleTwist Corporation and Qualcomm Innovation Center, Inc.
*
* All rights reserved.
* This file is licensed under the 3-clause BSD license in the NOTICE.txt
* file for this project. A copy of the 3-clause BSD license is found at:
*
* http://opensource.org/licenses/BSD-3-Clause.
*
* 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 <alljoyn/audio/WavDataSource.h>
#include <qcc/Debug.h>
#include <qcc/Util.h>
#define QCC_MODULE "ALLJOYN_AUDIO"
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#define DATA_IDENTIFIER 0x64617461 // 'data'
#define RIFF_IDENTIFIER 0x52494646 // 'RIFF'
#define WAVE_IDENTIFIER 0x57415645 // 'WAVE'
#define FMT_IDENTIFIER 0x666d7420 // 'fmt '
namespace ajn {
namespace services {
WavDataSource::WavDataSource() : mInputFile(NULL) {
}
WavDataSource::~WavDataSource() {
Close();
}
bool WavDataSource::Open(FILE* inputFile) {
if (mInputFile) {
QCC_LogError(ER_FAIL, ("already open"));
return false;
}
mInputFile = inputFile;
if (!ReadHeader()) {
QCC_LogError(ER_FAIL, ("file is not a PCM wave file"));
Close();
return false;
}
if (!(mSampleRate == 44100 || mSampleRate == 48000) ||
mBitsPerChannel != 16 ||
!(mChannelsPerFrame == 1 || mChannelsPerFrame == 2)) {
QCC_LogError(ER_FAIL, ("file is not s16le, 44100|48000, 1|2"));
QCC_DbgHLPrintf(("mSampleRate=%f\n" \
"mChannelsPerFrame=%d\n" \
"mBytesPerFrame=%d\n" \
"mBitsPerChannel=%d",
mSampleRate, mChannelsPerFrame,
mBytesPerFrame, mBitsPerChannel));
Close();
return false;
}
return true;
}
bool WavDataSource::Open(const char* filePath) {
if (mInputFile) {
QCC_LogError(ER_FAIL, ("already open"));
return false;
}
FILE*inputFile = fopen(filePath, "rb");
if (inputFile == NULL) {
QCC_LogError(ER_FAIL, ("can't open file '%s'", filePath));
return false;
}
return Open(inputFile);
}
void WavDataSource::Close() {
if (mInputFile != NULL) {
fclose(mInputFile);
mInputFile = NULL;
}
}
bool WavDataSource::ReadHeader() {
uint8_t buffer[20];
size_t n = fread(buffer, 1, 4, mInputFile);
if (n != 4 || betoh32(*((uint32_t*)buffer)) != RIFF_IDENTIFIER)
return false;
n = fread(buffer, 1, 8, mInputFile);
if (n != 8 || betoh32(*((uint32_t*)&buffer[4])) != WAVE_IDENTIFIER)
return false;
while (true) {
n = fread(buffer, 1, 8, mInputFile);
if (n != 8)
return false;
uint32_t chunkSize = ((int32_t)(buffer[7]) << 24) + ((int32_t)(buffer[6]) << 16) + ((int32_t)(buffer[5]) << 8) + buffer[4];
switch (betoh32(*((uint32_t*)buffer))) {
case FMT_IDENTIFIER:
n = fread(buffer, 1, 16, mInputFile);
if (n != 16 || buffer[0] != 1 || buffer[1] != 0) // if not PCM
return false;
mChannelsPerFrame = buffer[2];
mSampleRate = ((int32_t)(buffer[7]) << 24) + ((int32_t)(buffer[6]) << 16) + ((int32_t)(buffer[5]) << 8) + buffer[4];
mBitsPerChannel = buffer[14];
mBytesPerFrame = (mBitsPerChannel >> 3) * mChannelsPerFrame;
fseek(mInputFile, chunkSize - 16, SEEK_CUR);
break;
case DATA_IDENTIFIER:
mInputSize = ((int32_t)(buffer[7]) << 24) + ((int32_t)(buffer[6]) << 16) + ((int32_t)(buffer[5]) << 8) + buffer[4];
mInputDataStart = ftell(mInputFile);
return true;
default:
// skip
fseek(mInputFile, chunkSize, SEEK_CUR);
break;
}
}
return false;
}
size_t WavDataSource::ReadData(uint8_t* buffer, size_t offset, size_t length) {
mInputFileMutex.Lock();
size_t r = 0;
if (mInputFile) {
fseek(mInputFile, mInputDataStart + offset, SEEK_SET);
length = MIN(mInputSize - offset, length);
r = fread(buffer, 1, length, mInputFile);
}
mInputFileMutex.Unlock();
return r;
}
}
}
| [
"tmalsbar@quicinc.com"
] | tmalsbar@quicinc.com |
e095ca73d25d0d2fa58c5e42de14667163687c8a | 7950c4faf15ec1dc217391d839ddc21efd174ede | /cpp/2028.0_Find_Missing_Observations.cpp | 9545935c4f2a710722909c7c07ca5b3ae7ce367c | [] | no_license | lixiang2017/leetcode | f462ecd269c7157aa4f5854f8c1da97ca5375e39 | f93380721b8383817fe2b0d728deca1321c9ef45 | refs/heads/master | 2023-08-25T02:56:58.918792 | 2023-08-22T16:43:36 | 2023-08-22T16:43:36 | 153,090,613 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,420 | cpp | /*
执行用时:128 ms, 在所有 C++ 提交中击败了72.90% 的用户
内存消耗:120.8 MB, 在所有 C++ 提交中击败了31.61% 的用户
通过测试用例:64 / 64
*/
class Solution {
public:
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
int m = rolls.size();
int sum = mean * (n + m);
vector<int> ans;
for (int i = 0; i < m; i++) sum -= rolls[i];
if (sum < n || sum > 6 * n) return ans;
int remainder = sum % n, quotient = sum / n;
for (int i = 0; i < n; i++) ans.push_back(quotient);
for (int i = 0; i < remainder; i++) ans[i]++;
return ans;
}
};
/*
执行用时:124 ms, 在所有 C++ 提交中击败了80.65% 的用户
内存消耗:120.8 MB, 在所有 C++ 提交中击败了23.87% 的用户
通过测试用例:64 / 64
*/
class Solution {
public:
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
int m = rolls.size();
int sum = mean * (n + m);
vector<int> ans;
for (int i = 0; i < m; i++) sum -= rolls[i];
if (sum < n || sum > 6 * n) return ans;
int remainder = sum % n, quotient = sum / n;
for (int i = 0; i < remainder; i++) ans.push_back(quotient + 1);
for (int i = remainder; i < n; i++) ans.push_back(quotient);
return ans;
}
};
#define PB push_back
class Solution {
public:
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
int m = rolls.size();
int sum = mean * (n + m);
vector<int> ans;
for (int i = 0; i < m; i++) sum -= rolls[i];
if (sum < n || sum > 6 * n) return ans;
int remainder = sum % n, quotient = sum / n;
for (int i = 0; i < remainder; i++) ans.PB(quotient + 1);
for (int i = remainder; i < n; i++) ans.PB(quotient);
return ans;
}
};
/*
执行用时:116 ms, 在所有 C++ 提交中击败了93.55% 的用户
内存消耗:110.9 MB, 在所有 C++ 提交中击败了91.61% 的用户
通过测试用例:64 / 64
*/
class Solution {
public:
vector<int> missingRolls(vector<int>& rolls, int mean, int n) {
int left = mean * (rolls.size() + n) - accumulate(rolls.begin(), rolls.end(), 0);
if (left < n || left > 6 * n) return {};
vector<int> ans(n, left / n);
for (int i = 0; i < left % n; i++) ans[i]++;
return ans;
}
};
| [
"laoxing201314@outlook.com"
] | laoxing201314@outlook.com |
0406e0222585f91dfa7a3dfaf6750e34a381f77d | f1d0ea36f07c2ef126dec93208bd025aa78eceb7 | /Zen/Core/Utility/src/Log.cpp | 096a72580974a8c75afcc9d27341144f06e31be3 | [] | no_license | SgtFlame/indiezen | b7d6f87143b2f33abf977095755b6af77e9e7dab | 5513d5a05dc1425591ab7b9ba1b16d11b6a74354 | refs/heads/master | 2020-05-17T23:57:21.063997 | 2016-09-05T15:28:28 | 2016-09-05T15:28:28 | 33,279,102 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,337 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Core Framework
//
// Copyright (C) 2001 - 2010 Tony Richards
// Copyright (C) 2008 - 2010 Matthew Alan Gray
//
// 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.
//
// Tony Richards trichards@indiezen.com
// Matthew Alan Gray mgray@indiezen.org
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "Log.hpp"
#include "LogService.hpp"
#include "../log_stream.hpp"
#include <Zen/Core/Threading/MutexFactory.hpp>
#include <Zen/Core/Threading/CriticalSection.hpp>
#include <boost/bind.hpp>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Utility {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Log::Log(LogService& _service, const std::string& _name, bool _debuggerOutput, bool _suppressFileOutput)
: m_logName(_name)
, m_pLogMutex(Zen::Threading::MutexFactory::create())
, m_pScriptObject(NULL)
, m_debugOutput(_debuggerOutput)
, m_suppressFile(_suppressFileOutput)
, m_logLevel(LL_NORMAL)
, m_service(_service)
{
if (!m_suppressFile)
{
m_fileLog.open(m_logName.c_str());
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Log::~Log()
{
{
Zen::Threading::CriticalSection guard(m_pLogMutex);
if (!m_suppressFile)
{
m_fileLog.close();
}
}
Zen::Threading::MutexFactory::destroy(m_pLogMutex);
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Zen::Scripting::I_ObjectReference*
Log::getScriptObject()
{
if (m_pScriptObject == NULL)
{
m_pScriptObject = new ScriptWrapper_type(
getScriptModule(),
getScriptModule()->getScriptType(getScriptTypeName()),
getSelfReference().lock()
);
}
return m_pScriptObject;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Log::pScriptModule_type
Log::getScriptModule()
{
return m_service.getScriptModule();
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
const std::string&
Log::getName() const
{
return m_logName;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Log::isDebugOutputEnabled() const
{
return m_debugOutput;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Log::setDebugOutputEnabled(bool _isEnabled)
{
m_debugOutput = _isEnabled;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Log::isFileOutputSuppressed() const
{
return m_suppressFile;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Log::setFileOutputSuppressed(bool _isEnabled)
{
m_suppressFile = _isEnabled;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Log::LogLevel
Log::getLogLevel() const
{
return m_logLevel;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Log::setLogLevel(Log::LogLevel _logLevel)
{
m_logLevel = _logLevel;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Log::logMessage(const std::string& _message,
LogMessageLevel _logMessageLevel,
bool _maskDebug)
{
Zen::Threading::CriticalSection guard(m_pLogMutex);
if ((m_logLevel + _logMessageLevel) >= ZEN_LOG_THRESHOLD)
{
if (m_debugOutput && !_maskDebug)
{
std::cerr << _message;
}
if (!m_suppressFile)
{
// TODO Append time to beginning of log string.
m_fileLog << _message;
m_fileLog.flush();
}
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
log_stream_buffer
Log::getStreamBuffer(LogMessageLevel _logMessageLevel, bool _maskDebug)
{
return log_stream_buffer(getSelfReference().lock(), _logMessageLevel, _maskDebug);
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Utility
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"mgray@wintermute"
] | mgray@wintermute |
fc68effff346f24c5bd1ca2682243d6875bb7124 | 1459d71218af196799fd59c14e823fab56b43d05 | /tools/clang/include/clang/Sema/TypoCorrection.h | 5fbfba2d5d0e88af13ec23cbda3739485801aae3 | [
"NCSA"
] | permissive | omp-check/llvm-clang | 93b237c12f35baf8687e27bb2277265f09cf751c | bd40054e929d3f9acdf34a3accb39d1ef9fa8447 | refs/heads/master | 2020-05-18T02:45:43.734521 | 2015-01-28T02:31:26 | 2015-01-28T02:31:26 | 22,711,058 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,472 | h | //===--- TypoCorrection.h - Class for typo correction results ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the TypoCorrection class, which stores the results of
// Sema's typo correction (Sema::CorrectTypo).
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_TYPOCORRECTION_H
#define LLVM_CLANG_SEMA_TYPOCORRECTION_H
#include "clang/AST/DeclCXX.h"
#include "clang/Sema/DeclSpec.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
/// @brief Simple class containing the result of Sema::CorrectTypo
class TypoCorrection {
public:
// "Distance" for unusable corrections
static const unsigned InvalidDistance = ~0U;
// The largest distance still considered valid (larger edit distances are
// mapped to InvalidDistance by getEditDistance).
static const unsigned MaximumDistance = 10000U;
// Relative weightings of the "edit distance" components. The higher the
// weight, the more of a penalty to fitness the component will give (higher
// weights mean greater contribution to the total edit distance, with the
// best correction candidates having the lowest edit distance).
static const unsigned CharDistanceWeight = 100U;
static const unsigned QualifierDistanceWeight = 110U;
static const unsigned CallbackDistanceWeight = 150U;
TypoCorrection(const DeclarationName &Name, NamedDecl *NameDecl,
NestedNameSpecifier *NNS=0, unsigned CharDistance=0,
unsigned QualifierDistance=0)
: CorrectionName(Name), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(QualifierDistance),
CallbackDistance(0) {
if (NameDecl)
CorrectionDecls.push_back(NameDecl);
}
TypoCorrection(NamedDecl *Name, NestedNameSpecifier *NNS=0,
unsigned CharDistance=0)
: CorrectionName(Name->getDeclName()), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0) {
if (Name)
CorrectionDecls.push_back(Name);
}
TypoCorrection(DeclarationName Name, NestedNameSpecifier *NNS=0,
unsigned CharDistance=0)
: CorrectionName(Name), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0) {}
TypoCorrection()
: CorrectionNameSpec(0), CharDistance(0), QualifierDistance(0),
CallbackDistance(0) {}
/// \brief Gets the DeclarationName of the typo correction
DeclarationName getCorrection() const { return CorrectionName; }
IdentifierInfo* getCorrectionAsIdentifierInfo() const {
return CorrectionName.getAsIdentifierInfo();
}
/// \brief Gets the NestedNameSpecifier needed to use the typo correction
NestedNameSpecifier* getCorrectionSpecifier() const {
return CorrectionNameSpec;
}
void setCorrectionSpecifier(NestedNameSpecifier* NNS) {
CorrectionNameSpec = NNS;
}
void setQualifierDistance(unsigned ED) {
QualifierDistance = ED;
}
void setCallbackDistance(unsigned ED) {
CallbackDistance = ED;
}
// Convert the given weighted edit distance to a roughly equivalent number of
// single-character edits (typically for comparison to the length of the
// string being edited).
static unsigned NormalizeEditDistance(unsigned ED) {
if (ED > MaximumDistance)
return InvalidDistance;
return (ED + CharDistanceWeight / 2) / CharDistanceWeight;
}
/// \brief Gets the "edit distance" of the typo correction from the typo.
/// If Normalized is true, scale the distance down by the CharDistanceWeight
/// to return the edit distance in terms of single-character edits.
unsigned getEditDistance(bool Normalized = true) const {
if (CharDistance > MaximumDistance || QualifierDistance > MaximumDistance ||
CallbackDistance > MaximumDistance)
return InvalidDistance;
unsigned ED =
CharDistance * CharDistanceWeight +
QualifierDistance * QualifierDistanceWeight +
CallbackDistance * CallbackDistanceWeight;
if (ED > MaximumDistance)
return InvalidDistance;
// Half the CharDistanceWeight is added to ED to simulate rounding since
// integer division truncates the value (i.e. round-to-nearest-int instead
// of round-to-zero).
return Normalized ? NormalizeEditDistance(ED) : ED;
}
/// \brief Gets the pointer to the declaration of the typo correction
NamedDecl *getCorrectionDecl() const {
return hasCorrectionDecl() ? *(CorrectionDecls.begin()) : 0;
}
template <class DeclClass>
DeclClass *getCorrectionDeclAs() const {
return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
}
/// \brief Clears the list of NamedDecls before adding the new one.
void setCorrectionDecl(NamedDecl *CDecl) {
CorrectionDecls.clear();
addCorrectionDecl(CDecl);
}
/// \brief Add the given NamedDecl to the list of NamedDecls that are the
/// declarations associated with the DeclarationName of this TypoCorrection
void addCorrectionDecl(NamedDecl *CDecl);
std::string getAsString(const LangOptions &LO) const;
std::string getQuoted(const LangOptions &LO) const {
return "'" + getAsString(LO) + "'";
}
/// \brief Returns whether this TypoCorrection has a non-empty DeclarationName
operator bool() const { return bool(CorrectionName); }
/// \brief Mark this TypoCorrection as being a keyword.
/// Since addCorrectionDeclsand setCorrectionDecl don't allow NULL to be
/// added to the list of the correction's NamedDecl pointers, NULL is added
/// as the only element in the list to mark this TypoCorrection as a keyword.
void makeKeyword() {
CorrectionDecls.clear();
CorrectionDecls.push_back(0);
}
// Check if this TypoCorrection is a keyword by checking if the first
// item in CorrectionDecls is NULL.
bool isKeyword() const {
return !CorrectionDecls.empty() &&
CorrectionDecls.front() == 0;
}
// Check if this TypoCorrection is the given keyword.
template<std::size_t StrLen>
bool isKeyword(const char (&Str)[StrLen]) const {
return isKeyword() && getCorrectionAsIdentifierInfo()->isStr(Str);
}
// Returns true if the correction either is a keyword or has a known decl.
bool isResolved() const { return !CorrectionDecls.empty(); }
bool isOverloaded() const {
return CorrectionDecls.size() > 1;
}
void setCorrectionRange(CXXScopeSpec* SS,
const DeclarationNameInfo &TypoName) {
CorrectionRange.setBegin(CorrectionNameSpec && SS ? SS->getBeginLoc()
: TypoName.getLoc());
CorrectionRange.setEnd(TypoName.getLoc());
}
SourceRange getCorrectionRange() const {
return CorrectionRange;
}
typedef SmallVector<NamedDecl *, 1>::iterator decl_iterator;
decl_iterator begin() {
return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
}
decl_iterator end() { return CorrectionDecls.end(); }
typedef SmallVector<NamedDecl *, 1>::const_iterator const_decl_iterator;
const_decl_iterator begin() const {
return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
}
const_decl_iterator end() const { return CorrectionDecls.end(); }
private:
bool hasCorrectionDecl() const {
return (!isKeyword() && !CorrectionDecls.empty());
}
// Results.
DeclarationName CorrectionName;
NestedNameSpecifier *CorrectionNameSpec;
SmallVector<NamedDecl *, 1> CorrectionDecls;
unsigned CharDistance;
unsigned QualifierDistance;
unsigned CallbackDistance;
SourceRange CorrectionRange;
};
/// @brief Base class for callback objects used by Sema::CorrectTypo to check
/// the validity of a potential typo correction.
class CorrectionCandidateCallback {
public:
static const unsigned InvalidDistance = TypoCorrection::InvalidDistance;
CorrectionCandidateCallback()
: WantTypeSpecifiers(true), WantExpressionKeywords(true),
WantCXXNamedCasts(true), WantRemainingKeywords(true),
WantObjCSuper(false),
IsObjCIvarLookup(false) {}
virtual ~CorrectionCandidateCallback() {}
/// \brief Simple predicate used by the default RankCandidate to
/// determine whether to return an edit distance of 0 or InvalidDistance.
/// This can be overrided by validators that only need to determine if a
/// candidate is viable, without ranking potentially viable candidates.
/// Only ValidateCandidate or RankCandidate need to be overriden by a
/// callback wishing to check the viability of correction candidates.
/// The default predicate always returns true if the candidate is not a type
/// name or keyword, true for types if WantTypeSpecifiers is true, and true
/// for keywords if WantTypeSpecifiers, WantExpressionKeywords,
/// WantCXXNamedCasts, WantRemainingKeywords, or WantObjCSuper is true.
virtual bool ValidateCandidate(const TypoCorrection &candidate);
/// \brief Method used by Sema::CorrectTypo to assign an "edit distance" rank
/// to a candidate (where a lower value represents a better candidate), or
/// returning InvalidDistance if the candidate is not at all viable. For
/// validation callbacks that only need to determine if a candidate is viable,
/// the default RankCandidate returns either 0 or InvalidDistance depending
/// whether ValidateCandidate returns true or false.
virtual unsigned RankCandidate(const TypoCorrection &candidate) {
return ValidateCandidate(candidate) ? 0 : InvalidDistance;
}
// Flags for context-dependent keywords.
// TODO: Expand these to apply to non-keywords or possibly remove them.
bool WantTypeSpecifiers;
bool WantExpressionKeywords;
bool WantCXXNamedCasts;
bool WantRemainingKeywords;
bool WantObjCSuper;
// Temporary hack for the one case where a CorrectTypoContext enum is used
// when looking up results.
bool IsObjCIvarLookup;
};
/// @brief Simple template class for restricting typo correction candidates
/// to ones having a single Decl* of the given type.
template <class C>
class DeclFilterCCC : public CorrectionCandidateCallback {
public:
virtual bool ValidateCandidate(const TypoCorrection &candidate) {
return candidate.getCorrectionDeclAs<C>();
}
};
}
#endif
| [
"luisfe2007@gmail.com"
] | luisfe2007@gmail.com |
dda0ee6da5bfababf452a15376dd1c72b2894055 | a4587c1cd2932329099a3a84959923e76452b8a2 | /single-triton-tree-generator.cpp | 9f2c3a8f5d479b9177355246bf80291291e82487 | [] | no_license | jwbrummer/k600analyserPR254 | 02c164c885504d13ac883fab92500bfb4b9942ab | 5745fe7b92d0082817eef8f4fc378bc81208402b | refs/heads/master | 2021-06-09T15:38:13.877754 | 2021-05-07T14:15:56 | 2021-05-07T14:15:56 | 64,749,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | // Written by JWB (jbrummer@sun.ac.za) on 11/11/2018. This macro script receives an integer parameter so that the
// triton trees are created right after a run has been analysed so that much less disk space is needed to analyse all runs.
void single_triton_tree_generator(int runNum)
{
TFile *fin = TFile::Open("output.root");
TTree *trin = (TTree*)fin->FindObjectAny("DATA");
char rootNum[256];
sprintf(rootNum,"/home/wiggert/Desktop/triton-trees/triton_tree_run%d.root",runNum);
TFile *fout = new TFile(rootNum,"RECREATE");
char cutRun[256];
sprintf(cutRun,".x /home/wiggert/Programs/k600analyserPR254/pid/CUTpad1vstofRun%d.C",runNum);
gROOT->ProcessLine(cutRun);
char cutName[256];
sprintf(cutName,"CUTpad1vstofRun%d",runNum);
TTree *newt = trin->CopyTree(cutName);
newt->Write();
fout->Close();
fin->Close();
c1->Close();
//It is very important to close all TTrees and TFiles otherwise data analysis with the newly-generated trees won't work.
}
| [
"jbrummer@sun.ac.za"
] | jbrummer@sun.ac.za |
9e29c094faa2013b36d10cad505d1253179a9a37 | acde63ef939bc99ee20bfec182e79417aec6c347 | /SeqQueue.h | 648cc476bb12cec3909f0a9954f0cb968886d8a7 | [] | no_license | EricPro-NJU/DataStructure-Algorithm | 1f3aeebc8775625ddaaa65a7b64dc4513789472a | 725fe2c22de6d92cc16b40625c0a473a66c8fb29 | refs/heads/main | 2023-07-11T08:48:15.519826 | 2021-08-18T09:39:44 | 2021-08-18T09:39:44 | 384,650,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 944 | h | //
// Created by RUIPENG on 2021/7/28.
// Basic Data Structure 05: Queue
// Queue is a linear data structure, that data enter from rear but exit from front
// A simple way of implementation is circular array.
//
#ifndef NJU_REVIEW_SEQQUEUE_H
#define NJU_REVIEW_SEQQUEUE_H
#include "commons.h"
#include <iostream>
#include <cstdlib>
using namespace std;
class SeqQueue {
protected:
T* queue;
int rear, front;
int maxSize;
public:
SeqQueue(int size = defaultSize);
SeqQueue(const SeqQueue& table);
~SeqQueue();
int getLength() const {return (rear - front + maxSize) % maxSize;}
int getSize() const {return maxSize;}
bool empty() const {return rear == front;}
bool full() const {return (rear+1)%maxSize == front;}
bool enqueue(T x);
bool dequeue();
T getFront() const ;
friend ostream& operator << (ostream& out, SeqQueue& table);
};
void QueueDemo();
#endif //NJU_REVIEW_SEQQUEUE_H
| [
"geruipeng@smail.nju.edu.cn"
] | geruipeng@smail.nju.edu.cn |
b5e083c182f655e0f24cd56cf761b5b12e1b6c04 | f7a405cb6a534424bfd3de5cc2b6fa9abcc04734 | /src/GaussianPeakShape.cpp | ca1fb11a3f7d7f5f76538d097f11cc919f250058 | [
"MIT"
] | permissive | papacar/psf | 843d1de63735c7551d61984fa8f6fc1f3ecf4819 | 750abce6d04b3dd899ee7e440879a8a4d7e95700 | refs/heads/master | 2021-01-23T11:32:44.140682 | 2011-10-05T07:54:41 | 2011-10-05T07:54:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,831 | cpp | #include <cmath>
#include <psf/Error.h>
#include <psf/PeakShape.h>
using namespace psf;
double GaussianPeakShape::at(const double xCoordinate) const {
return std::exp(-(xCoordinate * xCoordinate) / (2 * sigma_ * sigma_));
}
double GaussianPeakShape::getSupportThreshold() const {
return this->getSigma() * this->getSigmaFactorForSupportThreshold();
}
// construction
GaussianPeakShape::GaussianPeakShape(const double sigma, const double sigmaFactorForSupportThreshold)
: sigma_(sigma), sigmaFactorForSupportThreshold_(sigmaFactorForSupportThreshold) {
psf_precondition(sigma > 0, "GaussianPeakShape::GaussianPeakShape(): sigma has to be positive.");
psf_precondition(sigmaFactorForSupportThreshold > 0, "GaussianPeakShape::GaussianPeakShape(): sigmaFactorForSupportThreshold has to be positive.");
}
// setter/getter
void GaussianPeakShape::setSigma(const double sigma) {
psf_precondition(sigma > 0, "GaussianPeakShape::GaussianPeakShape(): Parameter sigma has to be positive.");
sigma_ = sigma;
}
void GaussianPeakShape::setFwhm(const double fwhm) {
psf_precondition(fwhm > 0, "GaussianPeakShape::GaussianPeakShape(): Parameter fwhm has to be positive.");
sigma_ = fwhm / sigmaToFwhmConversionFactor();
}
double GaussianPeakShape::getFwhm() const {
return sigma_ * sigmaToFwhmConversionFactor();
}
void GaussianPeakShape::setSigmaFactorForSupportThreshold(const double factor) {
psf_precondition(factor > 0, "GaussianPeakShape::GaussianPeakShape(): sigmaFactorForSupportThreshold has to be positive.");
sigmaFactorForSupportThreshold_ = factor;
}
double GaussianPeakShape::getSigmaFactorForSupportThreshold() const {
return sigmaFactorForSupportThreshold_;
}
double GaussianPeakShape::sigmaToFwhmConversionFactor() const {
return 2 * sqrt(2 * std::log(2.));
}
| [
"bernhard.kausler@iwr.uni-heidelberg.de"
] | bernhard.kausler@iwr.uni-heidelberg.de |
2a97108f915d58472347350cc5216acd0a7a7861 | cc6586824584d1a9816dafd31bff2377d92f19ad | /ch3/Stacks_and_Queues/Ch3_3.5/main.cpp | 85426c64d0af57059184ef8e059336696ee62c71 | [] | no_license | huyunf/CC150 | 73bd0a9bff3fd05f469bac9e56deaf199eb4a78d | fe735476c0d81b44400919306fd56cad8be3eef8 | refs/heads/master | 2020-04-06T05:47:15.841302 | 2016-07-29T17:53:08 | 2016-07-29T17:53:08 | 58,819,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,251 | cpp | /*
Implement a MyQueue class which implements a queue using two stacks.
*/
#include <iostream>
using namespace std;
class cstack
{
public:
cstack() :stack_ptr(-1) {};
bool push(int d);
bool pop(int *d);
void dump_stack();
private:
static const int stack_size = 65536;
int stack_array[stack_size];
int stack_ptr;
};
bool cstack::push(int d)
{
if (stack_ptr >= stack_size)
{
cout << "Stack Full" << endl;
return false;
}
else
{
stack_ptr++;
stack_array[stack_ptr] = d;
}
return true;
}
bool cstack::pop(int* d)
{
if (stack_ptr < 0)
{
cout << "Stack Empty" << endl;
return false;
}
else
{
*d = stack_array[stack_ptr--];
}
return true;
}
void cstack::dump_stack()
{
if (stack_ptr >= 0)
{
for (int i = 0; i <= stack_ptr; i++)
{
cout << stack_array[i] << " ";
}
cout << endl;
}
else
{
cout << "EMPTY" << endl;
}
}
class MyQueue
{
public:
MyQueue();
~MyQueue();
bool push(int d);
bool pop(int *d);
void dump();
private:
cstack* stk_main;
cstack* stk_assistant;
};
MyQueue::MyQueue()
{
stk_main = new cstack;
stk_assistant = new cstack;
}
MyQueue::~MyQueue()
{
if (stk_main) delete stk_main;
if (stk_assistant) delete stk_assistant;
}
bool MyQueue::push(int d)
{
return stk_main->push(d);
}
bool MyQueue::pop(int *d)
{
bool r;
int data;
if (stk_assistant->pop(&data))
{
*d = data;
}
else
{
while (stk_main->pop(&data))
{
r = stk_assistant->push(data);
}
if (stk_assistant->pop(&data))
{
*d = data;
}
else
{
return false;
}
}
cout << "Pop data: " << *d << endl;
return true;
}
void MyQueue::dump()
{
cout << "stack main:" << endl;
stk_main->dump_stack();
cout << "stack assistant: " << endl;
stk_assistant->dump_stack();
}
int main()
{
int d;
int a[] = { 0,1,2,3,4,5,6,7 };
MyQueue* q = new MyQueue;
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
q->push(i);
}
q->dump();
q->pop(&d);
q->push(1);
q->push(3);
q->push(4);
q->push(5);
q->pop(&d);
q->dump();
q->pop(&d);
q->pop(&d);
q->pop(&d);
q->pop(&d);
q->pop(&d);
q->pop(&d);
q->pop(&d);
q->dump();
if (q) delete q;
return 0;
} | [
"Yunfeng Hu"
] | Yunfeng Hu |
63b69c4be3c7cf4d53b18ff78a1699619e827596 | 187cec85c2a2984be61e7534ea77199015e03810 | /NetServer/noncopyable.h | f413d4d3aafb559b6e7837f1225c4c698d3f1d36 | [] | no_license | yueqianlongma/RpcLearning | 268f95195f59ffd184b902274e9ecc10bfe9e4ee | b44f0f7a04ea02ebb495d89dbc9bde379bffeb75 | refs/heads/master | 2023-03-12T02:54:15.538785 | 2021-03-03T09:40:48 | 2021-03-03T09:40:48 | 344,073,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | #ifndef __NETSERVER_NONCOPYABLE_H__
#define __NETSERVER_NONCOPYABLE_H__
namespace net
{
class noncopyable
{
public:
noncopyable(noncopyable&) = delete;
noncopyable& operator=(noncopyable&) = delete;
protected:
noncopyable() = default; //这里必须要写, 因为上面我们使用了 noncopyable(noncopyable&), 虽然是delete的,但是任然使得默认的构造函数被删除
};
class copyable
{
};
}
#endif | [
"yydw.mjl@foxmail.com"
] | yydw.mjl@foxmail.com |
be3dce246d85b3a7b038bd6423dcf710a01c3dda | b0a31edabc9d4bd939cb853a254892089374ad66 | /C++Study/C++Study/STL/Chapter10_Algorithm/5. copy.cpp | 8b8655b84dad3362960cf4f53c35897139c03163 | [] | no_license | 2302053453/MyStudy | e31201d40cc701c9cc4692b60f132fec3e4bf91a | 229c431c0ef4ab40b52d37729b049c69de959166 | refs/heads/master | 2021-06-04T05:33:52.733762 | 2016-05-06T01:54:28 | 2016-05-06T01:54:28 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,150 | cpp | //#include<iostream>
//#include<algorithm>
//#include<vector>
//#include<list>
//
//using namespace std;
//
///*
// 2016-03-18
// copy 예제
// 컨테이너에 저정한 것과 같은 자료형을 저장하는
// 다른 컨테이너에 저장하고 싶을 떄 사용
// 복사할때 A를 B로 copy할 때 B는 최소한 A만큼의 크기를
// 확보하고 있어야 한다.
// -> copy를 할 떄 미리 공간을 지정해 두어야 한다.
//*/
//
//int main()
//{
// vector<int> vec1(10);
// // copy를 할 수 있도롤 미리 공간을 할당
// vector<int> vec2(10);
// generate(vec1.begin(), vec1.end(), rand);
//
// cout << "vec1의 모든 데이터를 vec2에 copy" << endl;
// copy(vec1.begin(), vec1.end(), vec2.begin());
// int count = vec2.size();
//
// for (int i = 0; i < count; i++)
// cout << vec2[i] << endl;
//
// cout << "vec1의 모든 데이터를 list1에 copy" << endl;
// // copy를 할 수 있도롤 미리 공간을 할당
// list<int> list1(10);
// copy(vec1.begin(), vec1.end(), list1.begin());
// for (list<int>::iterator iter = list1.begin(); iter != list1.end(); ++iter)
// cout << *iter << endl;
// return 0;
//} | [
"jhghdi@gmail.con"
] | jhghdi@gmail.con |
86f22454990ee3ffa7e57e769f900bfa6d62d0d1 | f1a2536fa7e9a8aabc0bc07122adefe213bf3111 | /slam_system/rf_map/bt_dtr/bt_dtr_node.h | 5a29b2b99b813b7f85d932afe688ecd15c274587 | [] | no_license | lood339/Pan-tilt-zoom-SLAM | 87076cf223c113101d8a6f9dd807d85b22deafa7 | 529212e09b8d2d233d3d6d5ecb6e9a0992b13507 | refs/heads/master | 2020-03-31T15:24:33.269349 | 2019-07-10T13:39:45 | 2019-07-10T13:39:45 | 152,335,661 | 5 | 0 | null | 2018-10-09T23:41:27 | 2018-10-09T23:41:27 | null | UTF-8 | C++ | false | false | 2,141 | h | // Created by jimmy on 2016-12-29.
// Copyright (c) 2016 Nowhere Planet. All rights reserved.
//
#ifndef __BT_DTR_Node__
#define __BT_DTR_Node__
// back tracking decision tree Node for regression
// idea: during the testing, back tracking trees once the testing example reaches the leaf node.
// It "should" increase performance
// disadvantage: increasing storage of the model, decrease speed in testing
#include <stdio.h>
#include <vector>
#include <Eigen/Dense>
#include "bt_dtr_util.h"
using std::vector;
using Eigen::VectorXf;
// tree node structure in a tree
class BTDTRNode
{
typedef BTDTRNode Node;
typedef BTDTRNode* NodePtr;
typedef BTDTRSplitParameter SplitParameter;
public:
BTDTRNode *left_child_; // left child in a tree
BTDTRNode *right_child_; // right child in a tree
int depth_; // depth in a tree, from 0
bool is_leaf_; // indicator if this is a leaf node
// non-leaf node parameter
SplitParameter split_param_; // intermedia node data structure
// leaf node parameter
VectorXf label_mean_; // label, e.g., 3D location
VectorXf label_stddev_; // standard deviation of labels
VectorXf feat_mean_; // mean value of local descriptors, e.g., WHT features
int index_; // node index, for save/store tree
// auxiliary data
int sample_num_; // num of training examples
double sample_percentage_; // ratio of training examples from parent node
public:
BTDTRNode(int depth)
{
left_child_ = NULL;
right_child_ = NULL;
depth_ = depth;
is_leaf_ = false;
sample_num_ = 0;
sample_percentage_ = 0.0;
index_ = -1;
}
~BTDTRNode();
static bool writeTree(const char *fileName, const NodePtr root, const int leafNodeNum);
static bool readTree(const char *fileName, NodePtr & root, int &leafNodeNum);
private:
static void writeNode(FILE *pf, const NodePtr node);
static void readNode(FILE *pf, NodePtr & node);
};
#endif /* defined(__BT_DTR_Node__) */
| [
"jimmy@Jianhuis-Mac-mini.local"
] | jimmy@Jianhuis-Mac-mini.local |
a1f77b6ad35af304efd0b9e646bca863df7c48c8 | 202d02a2a749be7e3e5440e962670d9836a79f25 | /src/pixie/System/Spline.cpp | 8d7af1c6b36d652a19d5b247afbb6bf995ab886a | [
"MIT"
] | permissive | martonantoni/pixie | 792b3b373c002a2a5089598fdfc9ade3f6aec55f | 4760e1363eb20919ef5c9d4b5adb5b7d955e3ccf | refs/heads/master | 2023-08-17T02:53:27.056968 | 2023-08-12T16:01:25 | 2023-08-12T16:01:25 | 249,523,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,626 | cpp | #include "StdAfx.h"
#include "pixie/pixie/i_pixie.h"
cPoint CubicSpline(const std::vector<cPoint> &SplineParameters, double t)
{
if(ASSERTFALSE(SplineParameters.size()!=4))
return {};
auto a=Lerp(SplineParameters[0], SplineParameters[1], t);
auto b=Lerp(SplineParameters[1], SplineParameters[2], t);
auto c=Lerp(SplineParameters[2], SplineParameters[3], t);
auto d=Lerp(a, b, t);
auto e=Lerp(b, c, t);
return Lerp(d, e, t);
}
std::vector<cPoint> GenerateSplinePoints(const std::vector<cPoint> &SplineParameters, double DesiredSpacing)
{
RELEASE_ASSERT(SplineParameters.size() == 4);
constexpr int TableSize=100;
constexpr double TableResolution=1.0/TableSize;
std::vector<std::pair<cPoint, double>> SplinePoints;
SplinePoints.reserve(TableSize);
SplinePoints.emplace_back(SplineParameters.front(), 0.0);
for(int i=1; i<TableSize; ++i)
{
auto Point=CubicSpline(SplineParameters, TableResolution*i);
SplinePoints.emplace_back(Point, Point.DistanceFrom(SplinePoints.back().first)+SplinePoints.back().second);
}
double DesiredDistance=DesiredSpacing;
std::vector<cPoint> Points;
Points.emplace_back(SplinePoints.front().first);
for(int i=1;i<TableSize;++i)
{
while(SplinePoints[i].second>DesiredDistance)
{
// will be between index i and i-1
double DistanceFromPrev=SplinePoints[i].second-SplinePoints[i-1].second;
if(DistanceFromPrev<0.00000001)
continue;
double t=i*TableResolution-TableResolution*((SplinePoints[i].second-DesiredDistance)/DistanceFromPrev);
Points.emplace_back(CubicSpline(SplineParameters, t));
DesiredDistance+=DesiredSpacing;
}
}
return Points;
} | [
"marton.antoni@gmail.com"
] | marton.antoni@gmail.com |
6c67e2e5f28e60e09dbb7aa64ba159ea35492a43 | 1dbf007249acad6038d2aaa1751cbde7e7842c53 | /eip/src/v3/model/PublicipInstanceResp.cpp | e998ee8306165018adfc02116bbf52c9fe01f63c | [] | permissive | huaweicloud/huaweicloud-sdk-cpp-v3 | 24fc8d93c922598376bdb7d009e12378dff5dd20 | 71674f4afbb0cd5950f880ec516cfabcde71afe4 | refs/heads/master | 2023-08-04T19:37:47.187698 | 2023-08-03T08:25:43 | 2023-08-03T08:25:43 | 324,328,641 | 11 | 10 | Apache-2.0 | 2021-06-24T07:25:26 | 2020-12-25T09:11:43 | C++ | UTF-8 | C++ | false | false | 20,359 | cpp |
#include "huaweicloud/eip/v3/model/PublicipInstanceResp.h"
namespace HuaweiCloud {
namespace Sdk {
namespace Eip {
namespace V3 {
namespace Model {
PublicipInstanceResp::PublicipInstanceResp()
{
id_ = "";
idIsSet_ = false;
projectId_ = "";
projectIdIsSet_ = false;
ipVersion_ = 0;
ipVersionIsSet_ = false;
publicIpAddress_ = "";
publicIpAddressIsSet_ = false;
publicIpv6Address_ = "";
publicIpv6AddressIsSet_ = false;
status_ = "";
statusIsSet_ = false;
description_ = "";
descriptionIsSet_ = false;
publicBorderGroup_ = "";
publicBorderGroupIsSet_ = false;
createdAt_ = utility::datetime();
createdAtIsSet_ = false;
updatedAt_ = utility::datetime();
updatedAtIsSet_ = false;
type_ = "";
typeIsSet_ = false;
vnicIsSet_ = false;
bandwidthIsSet_ = false;
enterpriseProjectId_ = "";
enterpriseProjectIdIsSet_ = false;
billingInfo_ = "";
billingInfoIsSet_ = false;
lockStatus_ = "";
lockStatusIsSet_ = false;
associateInstanceType_ = "";
associateInstanceTypeIsSet_ = false;
associateInstanceId_ = "";
associateInstanceIdIsSet_ = false;
publicipPoolId_ = "";
publicipPoolIdIsSet_ = false;
publicipPoolName_ = "";
publicipPoolNameIsSet_ = false;
alias_ = "";
aliasIsSet_ = false;
}
PublicipInstanceResp::~PublicipInstanceResp() = default;
void PublicipInstanceResp::validate()
{
}
web::json::value PublicipInstanceResp::toJson() const
{
web::json::value val = web::json::value::object();
if(idIsSet_) {
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_);
}
if(projectIdIsSet_) {
val[utility::conversions::to_string_t("project_id")] = ModelBase::toJson(projectId_);
}
if(ipVersionIsSet_) {
val[utility::conversions::to_string_t("ip_version")] = ModelBase::toJson(ipVersion_);
}
if(publicIpAddressIsSet_) {
val[utility::conversions::to_string_t("public_ip_address")] = ModelBase::toJson(publicIpAddress_);
}
if(publicIpv6AddressIsSet_) {
val[utility::conversions::to_string_t("public_ipv6_address")] = ModelBase::toJson(publicIpv6Address_);
}
if(statusIsSet_) {
val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_);
}
if(descriptionIsSet_) {
val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_);
}
if(publicBorderGroupIsSet_) {
val[utility::conversions::to_string_t("public_border_group")] = ModelBase::toJson(publicBorderGroup_);
}
if(createdAtIsSet_) {
val[utility::conversions::to_string_t("created_at")] = ModelBase::toJson(createdAt_);
}
if(updatedAtIsSet_) {
val[utility::conversions::to_string_t("updated_at")] = ModelBase::toJson(updatedAt_);
}
if(typeIsSet_) {
val[utility::conversions::to_string_t("type")] = ModelBase::toJson(type_);
}
if(vnicIsSet_) {
val[utility::conversions::to_string_t("vnic")] = ModelBase::toJson(vnic_);
}
if(bandwidthIsSet_) {
val[utility::conversions::to_string_t("bandwidth")] = ModelBase::toJson(bandwidth_);
}
if(enterpriseProjectIdIsSet_) {
val[utility::conversions::to_string_t("enterprise_project_id")] = ModelBase::toJson(enterpriseProjectId_);
}
if(billingInfoIsSet_) {
val[utility::conversions::to_string_t("billing_info")] = ModelBase::toJson(billingInfo_);
}
if(lockStatusIsSet_) {
val[utility::conversions::to_string_t("lock_status")] = ModelBase::toJson(lockStatus_);
}
if(associateInstanceTypeIsSet_) {
val[utility::conversions::to_string_t("associate_instance_type")] = ModelBase::toJson(associateInstanceType_);
}
if(associateInstanceIdIsSet_) {
val[utility::conversions::to_string_t("associate_instance_id")] = ModelBase::toJson(associateInstanceId_);
}
if(publicipPoolIdIsSet_) {
val[utility::conversions::to_string_t("publicip_pool_id")] = ModelBase::toJson(publicipPoolId_);
}
if(publicipPoolNameIsSet_) {
val[utility::conversions::to_string_t("publicip_pool_name")] = ModelBase::toJson(publicipPoolName_);
}
if(aliasIsSet_) {
val[utility::conversions::to_string_t("alias")] = ModelBase::toJson(alias_);
}
return val;
}
bool PublicipInstanceResp::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("project_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("project_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setProjectId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("ip_version"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("ip_version"));
if(!fieldValue.is_null())
{
int32_t refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setIpVersion(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("public_ip_address"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("public_ip_address"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPublicIpAddress(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("public_ipv6_address"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("public_ipv6_address"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPublicIpv6Address(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("status"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setStatus(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("description"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setDescription(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("public_border_group"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("public_border_group"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPublicBorderGroup(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("created_at"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("created_at"));
if(!fieldValue.is_null())
{
utility::datetime refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setCreatedAt(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("updated_at"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("updated_at"));
if(!fieldValue.is_null())
{
utility::datetime refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setUpdatedAt(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("type"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("type"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setType(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("vnic"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("vnic"));
if(!fieldValue.is_null())
{
VnicInfo refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setVnic(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("bandwidth"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("bandwidth"));
if(!fieldValue.is_null())
{
PublicipBandwidthInfo refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setBandwidth(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("enterprise_project_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("enterprise_project_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setEnterpriseProjectId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("billing_info"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("billing_info"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setBillingInfo(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("lock_status"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("lock_status"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setLockStatus(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("associate_instance_type"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("associate_instance_type"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setAssociateInstanceType(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("associate_instance_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("associate_instance_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setAssociateInstanceId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("publicip_pool_id"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("publicip_pool_id"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPublicipPoolId(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("publicip_pool_name"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("publicip_pool_name"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setPublicipPoolName(refVal);
}
}
if(val.has_field(utility::conversions::to_string_t("alias"))) {
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("alias"));
if(!fieldValue.is_null())
{
std::string refVal;
ok &= ModelBase::fromJson(fieldValue, refVal);
setAlias(refVal);
}
}
return ok;
}
std::string PublicipInstanceResp::getId() const
{
return id_;
}
void PublicipInstanceResp::setId(const std::string& value)
{
id_ = value;
idIsSet_ = true;
}
bool PublicipInstanceResp::idIsSet() const
{
return idIsSet_;
}
void PublicipInstanceResp::unsetid()
{
idIsSet_ = false;
}
std::string PublicipInstanceResp::getProjectId() const
{
return projectId_;
}
void PublicipInstanceResp::setProjectId(const std::string& value)
{
projectId_ = value;
projectIdIsSet_ = true;
}
bool PublicipInstanceResp::projectIdIsSet() const
{
return projectIdIsSet_;
}
void PublicipInstanceResp::unsetprojectId()
{
projectIdIsSet_ = false;
}
int32_t PublicipInstanceResp::getIpVersion() const
{
return ipVersion_;
}
void PublicipInstanceResp::setIpVersion(int32_t value)
{
ipVersion_ = value;
ipVersionIsSet_ = true;
}
bool PublicipInstanceResp::ipVersionIsSet() const
{
return ipVersionIsSet_;
}
void PublicipInstanceResp::unsetipVersion()
{
ipVersionIsSet_ = false;
}
std::string PublicipInstanceResp::getPublicIpAddress() const
{
return publicIpAddress_;
}
void PublicipInstanceResp::setPublicIpAddress(const std::string& value)
{
publicIpAddress_ = value;
publicIpAddressIsSet_ = true;
}
bool PublicipInstanceResp::publicIpAddressIsSet() const
{
return publicIpAddressIsSet_;
}
void PublicipInstanceResp::unsetpublicIpAddress()
{
publicIpAddressIsSet_ = false;
}
std::string PublicipInstanceResp::getPublicIpv6Address() const
{
return publicIpv6Address_;
}
void PublicipInstanceResp::setPublicIpv6Address(const std::string& value)
{
publicIpv6Address_ = value;
publicIpv6AddressIsSet_ = true;
}
bool PublicipInstanceResp::publicIpv6AddressIsSet() const
{
return publicIpv6AddressIsSet_;
}
void PublicipInstanceResp::unsetpublicIpv6Address()
{
publicIpv6AddressIsSet_ = false;
}
std::string PublicipInstanceResp::getStatus() const
{
return status_;
}
void PublicipInstanceResp::setStatus(const std::string& value)
{
status_ = value;
statusIsSet_ = true;
}
bool PublicipInstanceResp::statusIsSet() const
{
return statusIsSet_;
}
void PublicipInstanceResp::unsetstatus()
{
statusIsSet_ = false;
}
std::string PublicipInstanceResp::getDescription() const
{
return description_;
}
void PublicipInstanceResp::setDescription(const std::string& value)
{
description_ = value;
descriptionIsSet_ = true;
}
bool PublicipInstanceResp::descriptionIsSet() const
{
return descriptionIsSet_;
}
void PublicipInstanceResp::unsetdescription()
{
descriptionIsSet_ = false;
}
std::string PublicipInstanceResp::getPublicBorderGroup() const
{
return publicBorderGroup_;
}
void PublicipInstanceResp::setPublicBorderGroup(const std::string& value)
{
publicBorderGroup_ = value;
publicBorderGroupIsSet_ = true;
}
bool PublicipInstanceResp::publicBorderGroupIsSet() const
{
return publicBorderGroupIsSet_;
}
void PublicipInstanceResp::unsetpublicBorderGroup()
{
publicBorderGroupIsSet_ = false;
}
utility::datetime PublicipInstanceResp::getCreatedAt() const
{
return createdAt_;
}
void PublicipInstanceResp::setCreatedAt(const utility::datetime& value)
{
createdAt_ = value;
createdAtIsSet_ = true;
}
bool PublicipInstanceResp::createdAtIsSet() const
{
return createdAtIsSet_;
}
void PublicipInstanceResp::unsetcreatedAt()
{
createdAtIsSet_ = false;
}
utility::datetime PublicipInstanceResp::getUpdatedAt() const
{
return updatedAt_;
}
void PublicipInstanceResp::setUpdatedAt(const utility::datetime& value)
{
updatedAt_ = value;
updatedAtIsSet_ = true;
}
bool PublicipInstanceResp::updatedAtIsSet() const
{
return updatedAtIsSet_;
}
void PublicipInstanceResp::unsetupdatedAt()
{
updatedAtIsSet_ = false;
}
std::string PublicipInstanceResp::getType() const
{
return type_;
}
void PublicipInstanceResp::setType(const std::string& value)
{
type_ = value;
typeIsSet_ = true;
}
bool PublicipInstanceResp::typeIsSet() const
{
return typeIsSet_;
}
void PublicipInstanceResp::unsettype()
{
typeIsSet_ = false;
}
VnicInfo PublicipInstanceResp::getVnic() const
{
return vnic_;
}
void PublicipInstanceResp::setVnic(const VnicInfo& value)
{
vnic_ = value;
vnicIsSet_ = true;
}
bool PublicipInstanceResp::vnicIsSet() const
{
return vnicIsSet_;
}
void PublicipInstanceResp::unsetvnic()
{
vnicIsSet_ = false;
}
PublicipBandwidthInfo PublicipInstanceResp::getBandwidth() const
{
return bandwidth_;
}
void PublicipInstanceResp::setBandwidth(const PublicipBandwidthInfo& value)
{
bandwidth_ = value;
bandwidthIsSet_ = true;
}
bool PublicipInstanceResp::bandwidthIsSet() const
{
return bandwidthIsSet_;
}
void PublicipInstanceResp::unsetbandwidth()
{
bandwidthIsSet_ = false;
}
std::string PublicipInstanceResp::getEnterpriseProjectId() const
{
return enterpriseProjectId_;
}
void PublicipInstanceResp::setEnterpriseProjectId(const std::string& value)
{
enterpriseProjectId_ = value;
enterpriseProjectIdIsSet_ = true;
}
bool PublicipInstanceResp::enterpriseProjectIdIsSet() const
{
return enterpriseProjectIdIsSet_;
}
void PublicipInstanceResp::unsetenterpriseProjectId()
{
enterpriseProjectIdIsSet_ = false;
}
std::string PublicipInstanceResp::getBillingInfo() const
{
return billingInfo_;
}
void PublicipInstanceResp::setBillingInfo(const std::string& value)
{
billingInfo_ = value;
billingInfoIsSet_ = true;
}
bool PublicipInstanceResp::billingInfoIsSet() const
{
return billingInfoIsSet_;
}
void PublicipInstanceResp::unsetbillingInfo()
{
billingInfoIsSet_ = false;
}
std::string PublicipInstanceResp::getLockStatus() const
{
return lockStatus_;
}
void PublicipInstanceResp::setLockStatus(const std::string& value)
{
lockStatus_ = value;
lockStatusIsSet_ = true;
}
bool PublicipInstanceResp::lockStatusIsSet() const
{
return lockStatusIsSet_;
}
void PublicipInstanceResp::unsetlockStatus()
{
lockStatusIsSet_ = false;
}
std::string PublicipInstanceResp::getAssociateInstanceType() const
{
return associateInstanceType_;
}
void PublicipInstanceResp::setAssociateInstanceType(const std::string& value)
{
associateInstanceType_ = value;
associateInstanceTypeIsSet_ = true;
}
bool PublicipInstanceResp::associateInstanceTypeIsSet() const
{
return associateInstanceTypeIsSet_;
}
void PublicipInstanceResp::unsetassociateInstanceType()
{
associateInstanceTypeIsSet_ = false;
}
std::string PublicipInstanceResp::getAssociateInstanceId() const
{
return associateInstanceId_;
}
void PublicipInstanceResp::setAssociateInstanceId(const std::string& value)
{
associateInstanceId_ = value;
associateInstanceIdIsSet_ = true;
}
bool PublicipInstanceResp::associateInstanceIdIsSet() const
{
return associateInstanceIdIsSet_;
}
void PublicipInstanceResp::unsetassociateInstanceId()
{
associateInstanceIdIsSet_ = false;
}
std::string PublicipInstanceResp::getPublicipPoolId() const
{
return publicipPoolId_;
}
void PublicipInstanceResp::setPublicipPoolId(const std::string& value)
{
publicipPoolId_ = value;
publicipPoolIdIsSet_ = true;
}
bool PublicipInstanceResp::publicipPoolIdIsSet() const
{
return publicipPoolIdIsSet_;
}
void PublicipInstanceResp::unsetpublicipPoolId()
{
publicipPoolIdIsSet_ = false;
}
std::string PublicipInstanceResp::getPublicipPoolName() const
{
return publicipPoolName_;
}
void PublicipInstanceResp::setPublicipPoolName(const std::string& value)
{
publicipPoolName_ = value;
publicipPoolNameIsSet_ = true;
}
bool PublicipInstanceResp::publicipPoolNameIsSet() const
{
return publicipPoolNameIsSet_;
}
void PublicipInstanceResp::unsetpublicipPoolName()
{
publicipPoolNameIsSet_ = false;
}
std::string PublicipInstanceResp::getAlias() const
{
return alias_;
}
void PublicipInstanceResp::setAlias(const std::string& value)
{
alias_ = value;
aliasIsSet_ = true;
}
bool PublicipInstanceResp::aliasIsSet() const
{
return aliasIsSet_;
}
void PublicipInstanceResp::unsetalias()
{
aliasIsSet_ = false;
}
}
}
}
}
}
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
a7df56e967839502411a30649fa106fb611813bb | 91337a37770debaabbdbe6accd332edca0931100 | /algorithms/strings/Weighted Uniform Strings.cpp | e80af3489defd615c27a724d7f71704976193b0a | [] | no_license | googleknight/HackerRank_Solutions | d350ed98c0c6e7562dcd68a7260574a726d8ed91 | f584db0ff7699faf56d8c3f99c995a68a2deb0e0 | refs/heads/master | 2021-01-20T02:07:28.690211 | 2017-04-30T11:11:34 | 2017-04-30T11:11:34 | 89,375,687 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | //https://www.hackerrank.com/challenges/weighted-uniform-string
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
int n,x;
cin>>str>>n;
set<int> weight;
for(int i=0,j;i<str.length();i++)
{
weight.insert(str.at(i)-96);
for(j=i+1;j<str.length();j++)
{
if(str.at(j)==str.at(i))
weight.insert((str.at(j)-96)*(j-i+1));
else
break;
}
i=--j;
}
for(int i=0;i<n;i++)
{
cin>>x;
if(weight.find(x)!=weight.end())
cout<<"Yes\n";
else
cout<<"No\n";
}
return 0;
}
| [
"mathur1995@gmail.com"
] | mathur1995@gmail.com |
ca93809a8c8ba9f6af58df61137064a05269e2ba | b56bac95f5af902a8fdcb6e612ee2f43f895ae3a | /Wireless OverSim-INETMANET/inetmanet-2.0/src/underTest/wimax/linklayer/Ieee80216/MACSublayer/QoS/CommonPartSublayerQoSAP.cc | 132c7da428d7678dfa500e716ddf00a4e3533372 | [] | no_license | shabirali-mnnit/WirelessOversim-INETMANET | 380ea45fecaf56906ce2226b7638e97d6d1f00b0 | 1c6522495caa26d705bfe810f495c07f8b581a85 | refs/heads/master | 2021-07-30T10:55:25.490486 | 2021-07-20T08:14:35 | 2021-07-20T08:14:35 | 74,204,332 | 2 | 0 | null | 2016-11-22T05:47:22 | 2016-11-19T11:27:26 | C++ | UTF-8 | C++ | false | false | 396 | cc | #include "CommonPartSublayerQoSAP.h"
#include "PhyControlInfo_m.h"
#include "InterfaceTableAccess.h"
#include "InterfaceEntry.h"
Define_Module(CommonPartSublayerQoSAP);
CommonPartSublayerQoSAP::CommonPartSublayerQoSAP()
{
}
CommonPartSublayerQoSAP::~CommonPartSublayerQoSAP()
{
}
void CommonPartSublayerQoSAP::initialize()
{
}
void CommonPartSublayerQoSAP::handleMessage(cMessage *msg)
{
}
| [
"rcs1501@mnnit.ac.in"
] | rcs1501@mnnit.ac.in |
42afbebe9d1626bcb379f9c6c19601cbadd25cd7 | 350167ad671cea6e40222db4b15d632db06a51b2 | /StandardTemplateLibrary/stdafx.cpp | c996bcd6323c88cd6c94cf33abe355993bf2cb41 | [] | no_license | michaelfordbrown/AcceleratedIntroductionToCPP | 35d15c8631ab28ded6143ac10a73fe7c2f99a482 | 2617e86c36c6dc9ed59fdefb9dc1523d08f6edf3 | refs/heads/master | 2021-08-30T00:38:48.079928 | 2017-12-15T11:43:18 | 2017-12-15T11:43:18 | 112,620,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | // stdafx.cpp : source file that includes just the standard includes
// StandardTemplateLibrary.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"michaelfordbrown@hotmail.com"
] | michaelfordbrown@hotmail.com |
45c2a3e30b09e45ab2180e95ec43340f54a834d8 | 5e17dba0aa651b40cc060e3a1fa643330a39f8c2 | /rf24/software/ping_server/ping_server.ino | 6f15108ed7c9dec6226a15fbfe6f16ba180ace4f | [] | no_license | skalpt/rf | 8b460bc2d8e2f6cb1bde6e60336eddd83590b03f | ed057b3e77abdb7fd2ee20d78e05f64228cf1b3b | refs/heads/master | 2020-04-05T23:05:39.313082 | 2014-01-07T01:13:24 | 2014-01-07T01:13:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,649 | ino | /**
* An Mirf example which copies back the data it recives.
*
* Pins:
* Hardware SPI:
* MISO -> 12
* MOSI -> 11
* SCK -> 13
*
* Configurable:
* CE -> 8
* CSN -> 7
*
*/
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
void setup(){
Serial.begin(9600);
/*
* Set the SPI Driver.
*/
Mirf.spi = &MirfHardwareSpi;
/*
* Setup pins / SPI.
*/
Mirf.init();
/*
* Configure reciving address.
*/
Mirf.setRADDR((byte *)"serv1");
/*
* Set the payload length to sizeof(unsigned long) the
* return type of millis().
*
* NB: payload on client and server must be the same.
*/
Mirf.payload = sizeof(unsigned long);
/*
* Write channel and payload config then power up reciver.
*/
Mirf.config();
Serial.println("Listening...");
}
void loop(){
/*
* A buffer to store the data.
*/
byte data[Mirf.payload];
/*
* If a packet has been recived.
*
* isSending also restores listening mode when it
* transitions from true to false.
*/
if(!Mirf.isSending() && Mirf.dataReady()){
// Serial.println("Got packet");
/*
* Get load the packet into the buffer.
*/
Mirf.getData(data);
/*
* Set the send address.
*/
Mirf.setTADDR((byte *)"clie1");
/*
* Send the data back to the client.
*/
Mirf.send(data);
/*
* Wait untill sending has finished
*
* NB: isSending returns the chip to receving after returning true.
*/
Serial.println("Reply sent.");
}
} | [
"julian@thenewdabbs.com"
] | julian@thenewdabbs.com |
efb59fba9b4859d99d0cc13abd72df718bfab1f8 | f8b6238c44679460dee0fbd49f3f21c309791e1d | /Lab 4/ControlSystem.h | 5a413662cd23f726a92f4cfb4bf5a81da1d0223e | [] | no_license | JohnCodd/GamesEngineeringII | 92a636af91621108895c33c799899ba95b27c570 | a3b095e221027f1b0cdc52995c38e1efb4c467e6 | refs/heads/master | 2020-03-29T16:03:41.284544 | 2019-03-28T15:05:23 | 2019-03-28T15:05:23 | 150,095,001 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 225 | h | #pragma once
#include "Entity.h"
class ControlSystem
{
std::vector<Entity> entities;
public:
void addEntity(Entity e) { entities.push_back(e); }
void update()
{
std::cout << "ControlSystem Update" << std::endl;
}
}; | [
"john.codd@hotmail.com"
] | john.codd@hotmail.com |
26fe3b35ad2db268e76074bb7d5c5cf58d941b3f | 49aef59a754ded1be83520c78a2d55b58bf57336 | /tests/TestArr/TestArr.cpp | c4a5511015b54355ac343e0099b2607e0afc688f | [] | no_license | andreyV512/Coating | 048fe1764e6d0beb91e3d4832fb660f058f97b6b | 2d98bed2ff91faeb8561d99e6253bcd39123e829 | refs/heads/master | 2023-04-14T20:25:14.481248 | 2021-04-27T10:34:04 | 2021-04-27T10:34:04 | 347,822,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | // TestArr.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include "templates\typelist.hpp"
template<class O, class P>struct tst
{
bool operator()()
{
printf("%s\n", typeid(O).name());
return true;
}
};
template<class >struct TstOn {};
template<class >struct TstOff {};
template<class List>struct __filtr_tst_bits__;
template<class Head, class ...Tail>struct __filtr_tst_bits__<Vlst<Head, Tail...>>
{
typedef typename __filtr_tst_bits__<Vlst<Tail...>>::Result Result;
};
template<class Head, class ...Tail>struct __filtr_tst_bits__<Vlst<TstOn<Head>, Tail...>>
{
typedef typename VL::Append< TstOn<Head>, typename __filtr_tst_bits__<Vlst<Tail...>>::Result>::Result Result;
};
template<class Head, class ...Tail>struct __filtr_tst_bits__<Vlst<TstOff<Head>, Tail...>>
{
typedef typename VL::Append< TstOff<Head>, typename __filtr_tst_bits__<Vlst<Tail...>>::Result>::Result Result;
};
template<>struct __filtr_tst_bits__<Vlst<>>
{
typedef Vlst<> Result;
};
struct A {};
struct B {};
struct C {};
struct D {};
struct F {};
struct Z {};
typedef Vlst<TstOn<Z>, A, TstOn<B>, C, TstOff<D>, F> list;
VL::Factory<list> f;
int main()
{
typedef __filtr_tst_bits__<list>::Result xxx;
VL::find<xxx, tst>()();
}
| [
"nobody@mail.net"
] | nobody@mail.net |
d4110a9aac4e3501c8ea11b09ecacdcfb4c46e15 | 1923a18e2b45c3d7011ea4172975cef806e571ce | /framework/features/visuals.cpp | 18c5e9ab7ea3f29625cd0fafcfc6870244abb063 | [] | no_license | sestain/hawk_sdk | 9a06f286cd59812a8973ed770198cd1d32e19ce3 | f24cd0bd1ebd7a225b849476b9f51fda8f642cae | refs/heads/main | 2023-02-26T00:06:21.037287 | 2021-01-28T09:24:12 | 2021-01-28T09:24:12 | 316,706,269 | 0 | 0 | null | 2020-11-28T10:14:56 | 2020-11-28T10:14:55 | null | UTF-8 | C++ | false | false | 7,035 | cpp | #include "features.hpp"
#include "../menu/variables.hpp"
#include "../globals.hpp"
#include <chrono>
#include <ctime>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <locale>
#include <codecvt>
#include <string>
#include <sstream>
bool features::visuals::bound(player_t* player)
{
vec3_t origin, min, max, flb, brt, blb, frt, frb, brb, blt, flt;
int left, top, right, bottom;
origin = player->abs_origin();
min = player->mins() + origin;
max = player->maxs() + origin;
vec3_t points[] = {
vec3_t(min.x, min.y, min.z),
vec3_t(min.x, max.y, min.z),
vec3_t(max.x, max.y, min.z),
vec3_t(max.x, min.y, min.z),
vec3_t(max.x, max.y, max.z),
vec3_t(min.x, max.y, max.z),
vec3_t(min.x, min.y, max.z),
vec3_t(max.x, min.y, max.z)
};
if (!csgo::render::world_to_screen(flb, points[3]) || !csgo::render::world_to_screen(brt, points[5])
|| !csgo::render::world_to_screen(blb, points[0]) || !csgo::render::world_to_screen(frt, points[4])
|| !csgo::render::world_to_screen(frb, points[2]) || !csgo::render::world_to_screen(brb, points[1])
|| !csgo::render::world_to_screen(blt, points[6]) || !csgo::render::world_to_screen(flt, points[7]))
return false;
vec3_t arr[] = {flb, brt, blb, frt, frb, brb, blt, flt};
left = flb.x;
top = flb.y;
right = flb.x;
bottom = flb.y;
for (int i = 1; i < 8; i++) {
if (left > arr[i].x)
left = arr[i].x;
if (bottom < arr[i].y)
bottom = arr[i].y;
if (right < arr[i].x)
right = arr[i].x;
if (top > arr[i].y)
top = arr[i].y;
}
box.x = (int) left;
box.y = (int) top;
box.w = int(right - left);
box.h = int(bottom - top);
return true;
}
void features::visuals::watermark() {
}
void features::visuals::flags(player_t* player, int i)
{
auto flag = [] (player_t* player, std::string n, Color clr)
{
draw::string(box.x + box.w + 4, box.y - 4 + offset[player->idx()], draw::fonts::main, clr, n);
offset[player->idx()] += 10;
};
// literally just figured this out by MarkHC | https://www.unknowncheats.me/forum/1393142-post5.html
player_info_t player_info;
csgo::i::engine->get_player_info(i, &player_info);
bool bot = player_info.m_fake_player;
if (bot)
flag(player, "bot", Color(255, 255, 255, alpha[player->idx()]));
if (player->armor() > 0)
{
if (player->has_helmet())
flag(player, "hk", Color(255, 255, 255, alpha[player->idx()]));
else
flag(player, "k", Color(255, 255, 255, alpha[player->idx()]));
}
flag(player, "$" + std::to_string(player->account()), Color(133, 187, 101, alpha[player->idx()]));
if (player->scoped())
flag(player, "zoom", Color(255, 255, 255, alpha[player->idx()]));
}
void features::visuals::name(player_t* player, int i)
{
Color clr = Color(vars.visuals.name_clr.r, vars.visuals.name_clr.g, vars.visuals.name_clr.b, alpha[player->idx()]);
player_info_t player_info;
csgo::i::engine->get_player_info(i, &player_info);
std::string str = player_info.m_name;
draw::string(box.x + box.w / 2, box.y - 6, draw::fonts::main, clr, str, true);
}
void features::visuals::hitmarker_event(event_t* event)
{
if (!vars.visuals.hitsound)
return;
int attacker = csgo::i::engine->get_player_for_userid(event->get_int("attacker"));
if (attacker != csgo::i::engine->get_local_player()) /* checking if the attacker is local so we dont do events for enemy *NIGGERS* - retardation tyler */
return;
csgo::i::engine->client_cmd_unrestricted("play buttons\\arena_switch_press_02.wav");
}
void features::visuals::ammo(player_t* player)
{
Color clr = Color(vars.visuals.ammo_clr.r, vars.visuals.ammo_clr.g, vars.visuals.ammo_clr.b, alpha[player->idx()]);
auto wpn = player->weapon();
if (!wpn)
return;
auto data = wpn->data();
if (!data)
return;
auto clip = wpn->ammo();
auto max_clip = data->m_max_clip;
int delta = box.w * clip / max_clip;
draw::rectangle(box.x, box.y + box.h + 4, box.w, 3, Color(0, 0, 0, alpha[player->idx()] / 2));
draw::rectangle(box.x, box.y + box.h + 4, delta, 3, clr);
draw::outlinedrect(box.x, box.y + box.h + 4, box.w, 3, Color(0, 0, 0, alpha[player->idx()]));
}
void features::visuals::weapon(player_t* player)
{
Color clr = Color(vars.visuals.wep_clr.r, vars.visuals.wep_clr.g, vars.visuals.wep_clr.b, alpha[player->idx()]);
auto normal_wpn_str = [] (player_t* player) -> std::string
{
auto wpn = player->weapon();
if (!wpn)
return " ";
auto data = wpn->data();
if (!data)
return " ";
std::string m_wpn_name = data->m_weapon_name;
m_wpn_name.erase(0, 7); /* takes away weapon_ */
std::transform(m_wpn_name.begin(), m_wpn_name.end(), m_wpn_name.begin(), ::tolower); /* lower looks better tbh i want this cheat to look very original */
if (m_wpn_name == "knife_t")
return "knife";
else if (m_wpn_name == "usp_silencer")
return "usp s";
else if (m_wpn_name == "m4a1_silencer")
return "m4a1 s";
else
return m_wpn_name;
};
if (vars.visuals.ammo)
draw::string(box.x + box.w / 2, box.y + box.h + 12, draw::fonts::main, clr, normal_wpn_str(player), true);
else
draw::string(box.x + box.w / 2, box.y + box.h + 6, draw::fonts::main, clr, normal_wpn_str(player), true);
}
void features::visuals::health_bar(player_t* player)
{
int delta = player->health() * box.h / 100;
draw::rectangle(box.x - 6, box.y, 3, box.h, Color(0, 0, 0, alpha[player->idx()] / 2));
draw::rectangle(box.x - 6, box.y + (box.h - delta), 3, delta, Color(0, 255, 0, alpha[player->idx()]));
draw::outlinedrect(box.x - 6, box.y, 3, box.h, Color(0, 0, 0, alpha[player->idx()]));
if (!(player->health() == 100))
draw::string(box.x - 6, box.y + (box.h - delta), draw::fonts::smallest, Color(255, 255, 255, alpha[player->idx()]), std::to_string(player->health()), true);
}
void features::visuals::bounding_box(player_t* player)
{
Color clr = Color(vars.visuals.box_clr.r, vars.visuals.box_clr.g, vars.visuals.box_clr.b, alpha[player->idx()]);
draw::outlinedrect(box.x + 1, box.y + 1, box.w - 2, box.h - 2, Color(0, 0, 0, alpha[player->idx()]));
draw::outlinedrect(box.x - 1, box.y - 1, box.w + 2, box.h + 2, Color(0, 0, 0, alpha[player->idx()]));
draw::outlinedrect(box.x, box.y, box.w, box.h, clr);
}
void features::visuals::run() {
for (int i = 1; i <= csgo::i::globals->m_max_clients; i++)
{
player_t* player = csgo::i::ent_list->get<player_t*>(i);
player_t* local = csgo::i::ent_list->get<player_t*>(csgo::i::engine->get_local_player());
if (!player
|| !player->alive()
|| player == local
|| player->team() == local->team())
continue;
offset[player->idx()] = 0;
alpha[player->idx()] = player->dormant() ? max(alpha[player->idx()] - 5, 100) : min(alpha[player->idx()] + 5, 255);
if (visuals::bound(player))
{
if (vars.visuals.name)
visuals::name(player, i);
if (vars.visuals.health)
visuals::health_bar(player);
if (vars.visuals.box)
visuals::bounding_box(player);
if (vars.visuals.weapon)
visuals::weapon(player);
if (vars.visuals.flags)
visuals::flags(player, i);
if (vars.visuals.ammo)
visuals::ammo(player);
}
}
}
| [
"49698228+Pleberie@users.noreply.github.com"
] | 49698228+Pleberie@users.noreply.github.com |
7d0e647831098e6670189abc6de55bca07699fee | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /chrome/installer/util/install_util.cc | fe23ea3f7d5eaa40dc98a06a779b367c59d7e81c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 24,129 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// See the corresponding header file for description of the functions in this
// file.
#include "chrome/installer/util/install_util.h"
#include <shellapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "base/version.h"
#include "base/win/registry.h"
#include "base/win/shortcut.h"
#include "base/win/windows_version.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/install_static/install_details.h"
#include "chrome/install_static/install_modes.h"
#include "chrome/install_static/install_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/installation_state.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/installer/util/util_constants.h"
#include "chrome/installer/util/work_item_list.h"
using base::win::RegKey;
using installer::ProductState;
namespace {
const wchar_t kRegDowngradeVersion[] = L"DowngradeVersion";
// Creates a zero-sized non-decorated foreground window that doesn't appear
// in the taskbar. This is used as a parent window for calls to ShellExecuteEx
// in order for the UAC dialog to appear in the foreground and for focus
// to be returned to this process once the UAC task is dismissed. Returns
// NULL on failure, a handle to the UAC window on success.
HWND CreateUACForegroundWindow() {
HWND foreground_window = ::CreateWindowEx(WS_EX_TOOLWINDOW,
L"STATIC",
NULL,
WS_POPUP | WS_VISIBLE,
0, 0, 0, 0,
NULL, NULL,
::GetModuleHandle(NULL),
NULL);
if (foreground_window) {
HMONITOR monitor = ::MonitorFromWindow(foreground_window,
MONITOR_DEFAULTTONEAREST);
if (monitor) {
MONITORINFO mi = {0};
mi.cbSize = sizeof(mi);
::GetMonitorInfo(monitor, &mi);
RECT screen_rect = mi.rcWork;
int x_offset = (screen_rect.right - screen_rect.left) / 2;
int y_offset = (screen_rect.bottom - screen_rect.top) / 2;
::MoveWindow(foreground_window,
screen_rect.left + x_offset,
screen_rect.top + y_offset,
0, 0, FALSE);
} else {
NOTREACHED() << "Unable to get default monitor";
}
::SetForegroundWindow(foreground_window);
}
return foreground_window;
}
} // namespace
void InstallUtil::TriggerActiveSetupCommand() {
base::string16 active_setup_reg(install_static::GetActiveSetupPath());
base::win::RegKey active_setup_key(
HKEY_LOCAL_MACHINE, active_setup_reg.c_str(), KEY_QUERY_VALUE);
base::string16 cmd_str;
LONG read_status = active_setup_key.ReadValue(L"StubPath", &cmd_str);
if (read_status != ERROR_SUCCESS) {
LOG(ERROR) << active_setup_reg << ", " << read_status;
// This should never fail if Chrome is registered at system-level, but if it
// does there is not much else to be done.
return;
}
base::CommandLine cmd(base::CommandLine::FromString(cmd_str));
// Force creation of shortcuts as the First Run beacon might land between now
// and the time setup.exe checks for it.
cmd.AppendSwitch(installer::switches::kForceConfigureUserSettings);
base::Process process =
base::LaunchProcess(cmd.GetCommandLineString(), base::LaunchOptions());
if (!process.IsValid())
PLOG(ERROR) << cmd.GetCommandLineString();
}
bool InstallUtil::ExecuteExeAsAdmin(const base::CommandLine& cmd,
DWORD* exit_code) {
base::FilePath::StringType program(cmd.GetProgram().value());
DCHECK(!program.empty());
DCHECK_NE(program[0], L'\"');
base::CommandLine::StringType params(cmd.GetCommandLineString());
if (params[0] == '"') {
DCHECK_EQ('"', params[program.length() + 1]);
DCHECK_EQ(program, params.substr(1, program.length()));
params = params.substr(program.length() + 2);
} else {
DCHECK_EQ(program, params.substr(0, program.length()));
params = params.substr(program.length());
}
base::TrimWhitespace(params, base::TRIM_ALL, ¶ms);
HWND uac_foreground_window = CreateUACForegroundWindow();
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.hwnd = uac_foreground_window;
info.lpVerb = L"runas";
info.lpFile = program.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
bool success = false;
if (::ShellExecuteEx(&info) == TRUE) {
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (::GetExitCodeProcess(info.hProcess, &ret_val)) {
success = true;
if (exit_code)
*exit_code = ret_val;
}
}
if (uac_foreground_window) {
DestroyWindow(uac_foreground_window);
}
return success;
}
base::CommandLine InstallUtil::GetChromeUninstallCmd(bool system_install) {
ProductState state;
if (state.Initialize(system_install))
return state.uninstall_command();
return base::CommandLine(base::CommandLine::NO_PROGRAM);
}
void InstallUtil::GetChromeVersion(BrowserDistribution* dist,
bool system_install,
base::Version* version) {
DCHECK(dist);
RegKey key;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
LONG result = key.Open(reg_root,
dist->GetVersionKey().c_str(),
KEY_QUERY_VALUE | KEY_WOW64_32KEY);
base::string16 version_str;
if (result == ERROR_SUCCESS)
result = key.ReadValue(google_update::kRegVersionField, &version_str);
*version = base::Version();
if (result == ERROR_SUCCESS && !version_str.empty()) {
VLOG(1) << "Existing " << dist->GetDisplayName() << " version found "
<< version_str;
*version = base::Version(base::UTF16ToASCII(version_str));
} else {
DCHECK_EQ(ERROR_FILE_NOT_FOUND, result);
VLOG(1) << "No existing " << dist->GetDisplayName()
<< " install found.";
}
}
void InstallUtil::GetCriticalUpdateVersion(BrowserDistribution* dist,
bool system_install,
base::Version* version) {
DCHECK(dist);
RegKey key;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
LONG result = key.Open(reg_root,
dist->GetVersionKey().c_str(),
KEY_QUERY_VALUE | KEY_WOW64_32KEY);
base::string16 version_str;
if (result == ERROR_SUCCESS)
result = key.ReadValue(google_update::kRegCriticalVersionField,
&version_str);
*version = base::Version();
if (result == ERROR_SUCCESS && !version_str.empty()) {
VLOG(1) << "Critical Update version for " << dist->GetDisplayName()
<< " found " << version_str;
*version = base::Version(base::UTF16ToASCII(version_str));
} else {
DCHECK_EQ(ERROR_FILE_NOT_FOUND, result);
VLOG(1) << "No existing " << dist->GetDisplayName()
<< " install found.";
}
}
bool InstallUtil::IsOSSupported() {
// We do not support anything prior to Windows 7.
VLOG(1) << base::SysInfo::OperatingSystemName() << ' '
<< base::SysInfo::OperatingSystemVersion();
return base::win::GetVersion() >= base::win::VERSION_WIN7;
}
void InstallUtil::AddInstallerResultItems(
bool system_install,
const base::string16& state_key,
installer::InstallStatus status,
int string_resource_id,
const base::string16* const launch_cmd,
WorkItemList* install_list) {
DCHECK(install_list);
DCHECK(install_list->best_effort());
DCHECK(!install_list->rollback_enabled());
const HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
DWORD installer_result = (GetInstallReturnCode(status) == 0) ? 0 : 1;
install_list->AddCreateRegKeyWorkItem(root, state_key, KEY_WOW64_32KEY);
install_list->AddSetRegValueWorkItem(root,
state_key,
KEY_WOW64_32KEY,
installer::kInstallerResult,
installer_result,
true);
install_list->AddSetRegValueWorkItem(root,
state_key,
KEY_WOW64_32KEY,
installer::kInstallerError,
static_cast<DWORD>(status),
true);
if (string_resource_id != 0) {
base::string16 msg = installer::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root,
state_key,
KEY_WOW64_32KEY,
installer::kInstallerResultUIString,
msg,
true);
}
if (launch_cmd != NULL && !launch_cmd->empty()) {
install_list->AddSetRegValueWorkItem(
root,
state_key,
KEY_WOW64_32KEY,
installer::kInstallerSuccessLaunchCmdLine,
*launch_cmd,
true);
}
}
bool InstallUtil::IsPerUserInstall() {
return !install_static::InstallDetails::Get().system_level();
}
// static
bool InstallUtil::IsFirstRunSentinelPresent() {
// TODO(msw): Consolidate with first_run::internal::IsFirstRunSentinelPresent.
base::FilePath user_data_dir;
return !base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) ||
base::PathExists(user_data_dir.Append(chrome::kFirstRunSentinel));
}
// static
bool InstallUtil::IsStartMenuShortcutWithActivatorGuidInstalled() {
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
base::FilePath shortcut_path;
if (!ShellUtil::GetShortcutPath(
ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT, dist,
install_static::IsSystemInstall() ? ShellUtil::SYSTEM_LEVEL
: ShellUtil::CURRENT_USER,
&shortcut_path)) {
return false;
}
shortcut_path =
shortcut_path.Append(dist->GetShortcutName() + installer::kLnkExt);
if (!base::PathExists(shortcut_path))
return false;
base::win::ShortcutProperties properties;
base::win::ResolveShortcutProperties(
shortcut_path,
base::win::ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID,
&properties);
return ::IsEqualCLSID(properties.toast_activator_clsid,
install_static::GetToastActivatorClsid());
}
// static
base::string16 InstallUtil::GetToastActivatorRegistryPath() {
// CLSID has a string format of "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}",
// which contains 38 characters. The length is 39 to make space for the
// string terminator.
constexpr int kGuidLength = 39;
base::string16 guid_string;
if (::StringFromGUID2(install_static::GetToastActivatorClsid(),
base::WriteInto(&guid_string, kGuidLength),
kGuidLength) != kGuidLength) {
return base::string16();
}
return L"Software\\Classes\\CLSID\\" + guid_string;
}
// static
bool InstallUtil::GetEULASentinelFilePath(base::FilePath* path) {
base::FilePath user_data_dir;
if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
return false;
*path = user_data_dir.Append(installer::kEULASentinelFile);
return true;
}
// This method tries to delete a registry key and logs an error message
// in case of failure. It returns true if deletion is successful (or the key did
// not exist), otherwise false.
bool InstallUtil::DeleteRegistryKey(HKEY root_key,
const base::string16& key_path,
REGSAM wow64_access) {
VLOG(1) << "Deleting registry key " << key_path;
RegKey target_key;
LONG result =
target_key.Open(root_key, key_path.c_str(), DELETE | wow64_access);
if (result == ERROR_FILE_NOT_FOUND)
return true;
if (result == ERROR_SUCCESS)
result = target_key.DeleteKey(L"");
if (result != ERROR_SUCCESS) {
LOG(ERROR) << "Failed to delete registry key: " << key_path
<< " error: " << result;
return false;
}
return true;
}
// This method tries to delete a registry value and logs an error message
// in case of failure. It returns true if deletion is successful (or the key did
// not exist), otherwise false.
bool InstallUtil::DeleteRegistryValue(HKEY reg_root,
const base::string16& key_path,
REGSAM wow64_access,
const base::string16& value_name) {
RegKey key;
LONG result = key.Open(reg_root, key_path.c_str(),
KEY_SET_VALUE | wow64_access);
if (result == ERROR_SUCCESS)
result = key.DeleteValue(value_name.c_str());
if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) {
LOG(ERROR) << "Failed to delete registry value: " << value_name
<< " error: " << result;
return false;
}
return true;
}
// static
InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryKeyIf(
HKEY root_key,
const base::string16& key_to_delete_path,
const base::string16& key_to_test_path,
const REGSAM wow64_access,
const wchar_t* value_name,
const RegistryValuePredicate& predicate) {
DCHECK(root_key);
ConditionalDeleteResult delete_result = NOT_FOUND;
RegKey key;
base::string16 actual_value;
if (key.Open(root_key, key_to_test_path.c_str(),
KEY_QUERY_VALUE | wow64_access) == ERROR_SUCCESS &&
key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS &&
predicate.Evaluate(actual_value)) {
key.Close();
delete_result = DeleteRegistryKey(root_key,
key_to_delete_path,
wow64_access)
? DELETED : DELETE_FAILED;
}
return delete_result;
}
// static
InstallUtil::ConditionalDeleteResult InstallUtil::DeleteRegistryValueIf(
HKEY root_key,
const wchar_t* key_path,
REGSAM wow64_access,
const wchar_t* value_name,
const RegistryValuePredicate& predicate) {
DCHECK(root_key);
DCHECK(key_path);
ConditionalDeleteResult delete_result = NOT_FOUND;
RegKey key;
base::string16 actual_value;
if (key.Open(root_key, key_path,
KEY_QUERY_VALUE | KEY_SET_VALUE | wow64_access)
== ERROR_SUCCESS &&
key.ReadValue(value_name, &actual_value) == ERROR_SUCCESS &&
predicate.Evaluate(actual_value)) {
LONG result = key.DeleteValue(value_name);
if (result != ERROR_SUCCESS) {
LOG(ERROR) << "Failed to delete registry value: "
<< (value_name ? value_name : L"(Default)")
<< " error: " << result;
delete_result = DELETE_FAILED;
} else {
delete_result = DELETED;
}
}
return delete_result;
}
bool InstallUtil::ValueEquals::Evaluate(const base::string16& value) const {
return value == value_to_match_;
}
// static
int InstallUtil::GetInstallReturnCode(installer::InstallStatus status) {
switch (status) {
case installer::FIRST_INSTALL_SUCCESS:
case installer::INSTALL_REPAIRED:
case installer::NEW_VERSION_UPDATED:
case installer::IN_USE_UPDATED:
case installer::OLD_VERSION_DOWNGRADE:
case installer::IN_USE_DOWNGRADE:
return 0;
default:
return status;
}
}
// static
void InstallUtil::ComposeCommandLine(const base::string16& program,
const base::string16& arguments,
base::CommandLine* command_line) {
*command_line =
base::CommandLine::FromString(L"\"" + program + L"\" " + arguments);
}
void InstallUtil::AppendModeSwitch(base::CommandLine* command_line) {
const install_static::InstallDetails& install_details =
install_static::InstallDetails::Get();
if (*install_details.install_switch())
command_line->AppendSwitch(install_details.install_switch());
}
// static
base::string16 InstallUtil::GetCurrentDate() {
static const wchar_t kDateFormat[] = L"yyyyMMdd";
wchar_t date_str[arraysize(kDateFormat)] = {0};
int len = GetDateFormatW(LOCALE_INVARIANT, 0, NULL, kDateFormat,
date_str, arraysize(date_str));
if (len) {
--len; // Subtract terminating \0.
} else {
PLOG(DFATAL) << "GetDateFormat";
}
return base::string16(date_str, len);
}
// Open |path| with minimal access to obtain information about it, returning
// true and populating |file| on success.
// static
bool InstallUtil::ProgramCompare::OpenForInfo(const base::FilePath& path,
base::File* file) {
DCHECK(file);
file->Initialize(path, base::File::FLAG_OPEN);
return file->IsValid();
}
// Populate |info| for |file|, returning true on success.
// static
bool InstallUtil::ProgramCompare::GetInfo(const base::File& file,
BY_HANDLE_FILE_INFORMATION* info) {
DCHECK(file.IsValid());
return GetFileInformationByHandle(file.GetPlatformFile(), info) != 0;
}
// static
base::Version InstallUtil::GetDowngradeVersion(
bool system_install,
const BrowserDistribution* dist) {
DCHECK(dist);
RegKey key;
base::string16 downgrade_version;
if (key.Open(system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER,
dist->GetStateKey().c_str(),
KEY_QUERY_VALUE | KEY_WOW64_32KEY) != ERROR_SUCCESS ||
key.ReadValue(kRegDowngradeVersion, &downgrade_version) !=
ERROR_SUCCESS) {
return base::Version();
}
return base::Version(base::UTF16ToASCII(downgrade_version));
}
// static
void InstallUtil::AddUpdateDowngradeVersionItem(
bool system_install,
const base::Version* current_version,
const base::Version& new_version,
const BrowserDistribution* dist,
WorkItemList* list) {
DCHECK(list);
DCHECK(dist);
base::Version downgrade_version = GetDowngradeVersion(system_install, dist);
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
if (!current_version ||
(*current_version <= new_version &&
((!downgrade_version.IsValid() || downgrade_version <= new_version)))) {
list->AddDeleteRegValueWorkItem(root, dist->GetStateKey(), KEY_WOW64_32KEY,
kRegDowngradeVersion);
} else if (*current_version > new_version && !downgrade_version.IsValid()) {
list->AddSetRegValueWorkItem(
root, dist->GetStateKey(), KEY_WOW64_32KEY, kRegDowngradeVersion,
base::ASCIIToUTF16(current_version->GetString()), true);
}
}
// static
void InstallUtil::GetMachineLevelUserCloudPolicyEnrollmentTokenRegistryPath(
std::wstring* key_path,
std::wstring* value_name) {
// This token applies to all installs on the machine, even though only a
// system install can set it. This is to prevent users from doing a user
// install of chrome to get around policies.
*key_path = L"SOFTWARE\\Policies\\";
install_static::AppendChromeInstallSubDirectory(
install_static::InstallDetails::Get().mode(), false /* !include_suffix */,
key_path);
*value_name = L"MachineLevelUserCloudPolicyEnrollmentToken";
}
// static
void InstallUtil::GetMachineLevelUserCloudPolicyDMTokenRegistryPath(
std::wstring* key_path,
std::wstring* value_name) {
// This token applies to all installs on the machine, even though only a
// system install can set it. This is to prevent users from doing a user
// install of chrome to get around policies.
*key_path = L"SOFTWARE\\";
install_static::AppendChromeInstallSubDirectory(
install_static::InstallDetails::Get().mode(), false /* !include_suffix */,
key_path);
key_path->append(L"\\Enrollment");
*value_name = L"dmtoken";
}
// static
std::wstring InstallUtil::GetMachineLevelUserCloudPolicyEnrollmentToken() {
// Because chrome needs to know if machine level user cloud policies must be
// initialized even before the entire policy service is brought up, this
// helper function exists to directly read the token from the system policies.
//
// Putting the enrollment token in the system policy area is a convenient
// way for administrators to enroll chrome throughout their fleet by pushing
// this token via SCCM.
// TODO(rogerta): This may not be the best place for the helpers dealing with
// the enrollment and/or DM tokens. See crbug.com/823852 for details.
std::wstring key_path;
std::wstring value_name;
GetMachineLevelUserCloudPolicyEnrollmentTokenRegistryPath(&key_path,
&value_name);
RegKey key;
LONG result = key.Open(HKEY_LOCAL_MACHINE, key_path.c_str(), KEY_QUERY_VALUE);
if (result != ERROR_SUCCESS) {
if (result != ERROR_FILE_NOT_FOUND) {
::SetLastError(result);
PLOG(ERROR) << "Failed to open HKLM\\" << key_path;
}
return std::wstring();
}
std::wstring value;
result = key.ReadValue(value_name.c_str(), &value);
if (result != ERROR_SUCCESS) {
::SetLastError(result);
PLOG(ERROR) << "Failed to read HKLM\\" << key_path << "\\" << value_name;
}
return value;
}
InstallUtil::ProgramCompare::ProgramCompare(const base::FilePath& path_to_match)
: path_to_match_(path_to_match),
file_info_() {
DCHECK(!path_to_match_.empty());
if (!OpenForInfo(path_to_match_, &file_)) {
PLOG(WARNING) << "Failed opening " << path_to_match_.value()
<< "; falling back to path string comparisons.";
} else if (!GetInfo(file_, &file_info_)) {
PLOG(WARNING) << "Failed getting information for "
<< path_to_match_.value()
<< "; falling back to path string comparisons.";
file_.Close();
}
}
InstallUtil::ProgramCompare::~ProgramCompare() {
}
bool InstallUtil::ProgramCompare::Evaluate(const base::string16& value) const {
// Suss out the exe portion of the value, which is expected to be a command
// line kinda (or exactly) like:
// "c:\foo\bar\chrome.exe" -- "%1"
base::FilePath program(base::CommandLine::FromString(value).GetProgram());
if (program.empty()) {
LOG(WARNING) << "Failed to parse an executable name from command line: \""
<< value << "\"";
return false;
}
return EvaluatePath(program);
}
bool InstallUtil::ProgramCompare::EvaluatePath(
const base::FilePath& path) const {
// Try the simple thing first: do the paths happen to match?
if (base::FilePath::CompareEqualIgnoreCase(path_to_match_.value(),
path.value()))
return true;
// If the paths don't match and we couldn't open the expected file, we've done
// our best.
if (!file_.IsValid())
return false;
// Open the program and see if it references the expected file.
base::File file;
BY_HANDLE_FILE_INFORMATION info = {};
return (OpenForInfo(path, &file) &&
GetInfo(file, &info) &&
info.dwVolumeSerialNumber == file_info_.dwVolumeSerialNumber &&
info.nFileIndexHigh == file_info_.nFileIndexHigh &&
info.nFileIndexLow == file_info_.nFileIndexLow);
}
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
a56d2c94798e7afd5356e26a357fbb0521bda2c6 | d0276045ff88c6ad4969aa4deb929d1e2ed9efb7 | /Striver SDE SHEET/Day 2 (Arrays)/Pascal Triangle.cpp | d47a4da0b751faddb8b3bf80b2517b731952281c | [] | no_license | rishabhtyagi2306/Competitive-Programming | 2f4d6e34701d3012832e908341606fa0501173a4 | 269d42a89940eefa73c922b6f275596fe68add6a | refs/heads/master | 2023-07-12T18:05:17.366652 | 2021-08-29T18:30:09 | 2021-08-29T18:30:09 | 256,992,147 | 3 | 3 | null | 2020-10-02T05:43:31 | 2020-04-19T12:20:46 | C++ | UTF-8 | C++ | false | false | 1,218 | cpp | class Solution {
public:
vector<vector<int>> generate(int numRows)
{
vector<vector<int>> ans;
for(int i = 1; i <= numRows; i++)
{
vector<int> tmp;
if(i == 1)
{
tmp.push_back(1);
}
else if(i == 2)
{
tmp.push_back(1);
tmp.push_back(1);
}
else
{
tmp.push_back(1);
for(int j = 1; j < ans[i-2].size(); j++)
{
tmp.push_back(ans[i-2][j] + ans[i-2][j-1]);
}
tmp.push_back(1);
}
ans.push_back(tmp);
}
return ans;
}
// Space optimized code O(1) space.
// void printPascal(int n)
// {
// for (int line = 1; line <= n; line++)
// {
// int C = 1; // used to represent C(line, i)
// for (int i = 1; i <= line; i++)
// {
// // The first value in a line is always 1
// cout<< C<<" ";
// C = C * (line - i) / i;
// }
// cout<<"\n";
// }
// }
}; | [
"rishabhtyagi.2306@gmail.com"
] | rishabhtyagi.2306@gmail.com |
053da5eb7b233e250a4adfb35c7aaf19988fefab | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /tcss/src/v20201101/model/DescribeWebVulListRequest.cpp | d890c2721220cd0517f7741e1015dbac2100c1cd | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,490 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcss/v20201101/model/DescribeWebVulListRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tcss::V20201101::Model;
using namespace std;
DescribeWebVulListRequest::DescribeWebVulListRequest() :
m_limitHasBeenSet(false),
m_offsetHasBeenSet(false),
m_filtersHasBeenSet(false),
m_orderHasBeenSet(false),
m_byHasBeenSet(false)
{
}
string DescribeWebVulListRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_limitHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Limit";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_limit, allocator);
}
if (m_offsetHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Offset";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_offset, allocator);
}
if (m_filtersHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Filters";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_filters.begin(); itr != m_filters.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_orderHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Order";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_order.c_str(), allocator).Move(), allocator);
}
if (m_byHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "By";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_by.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
uint64_t DescribeWebVulListRequest::GetLimit() const
{
return m_limit;
}
void DescribeWebVulListRequest::SetLimit(const uint64_t& _limit)
{
m_limit = _limit;
m_limitHasBeenSet = true;
}
bool DescribeWebVulListRequest::LimitHasBeenSet() const
{
return m_limitHasBeenSet;
}
uint64_t DescribeWebVulListRequest::GetOffset() const
{
return m_offset;
}
void DescribeWebVulListRequest::SetOffset(const uint64_t& _offset)
{
m_offset = _offset;
m_offsetHasBeenSet = true;
}
bool DescribeWebVulListRequest::OffsetHasBeenSet() const
{
return m_offsetHasBeenSet;
}
vector<RunTimeFilters> DescribeWebVulListRequest::GetFilters() const
{
return m_filters;
}
void DescribeWebVulListRequest::SetFilters(const vector<RunTimeFilters>& _filters)
{
m_filters = _filters;
m_filtersHasBeenSet = true;
}
bool DescribeWebVulListRequest::FiltersHasBeenSet() const
{
return m_filtersHasBeenSet;
}
string DescribeWebVulListRequest::GetOrder() const
{
return m_order;
}
void DescribeWebVulListRequest::SetOrder(const string& _order)
{
m_order = _order;
m_orderHasBeenSet = true;
}
bool DescribeWebVulListRequest::OrderHasBeenSet() const
{
return m_orderHasBeenSet;
}
string DescribeWebVulListRequest::GetBy() const
{
return m_by;
}
void DescribeWebVulListRequest::SetBy(const string& _by)
{
m_by = _by;
m_byHasBeenSet = true;
}
bool DescribeWebVulListRequest::ByHasBeenSet() const
{
return m_byHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
5dc369e27445c26f18f448e763359cb30d928f23 | fa02d527a0c3440274aadfa007ef30e0eed61d07 | /SVR/Arduino src/SVR Serial Sender.ino | 19b8756db19bb58bb159d1567b80d77257873326 | [] | no_license | tdeweyn/SVR | 6b36608ac560180590f75e10bdb9ef280d6b6b19 | f2b997b687866a4f4310bf86b8ba3d9743c16a3b | refs/heads/master | 2021-09-06T06:51:30.923556 | 2018-02-03T13:21:19 | 2018-02-03T13:21:19 | 115,836,981 | 0 | 0 | null | 2017-12-31T02:16:13 | 2017-12-31T02:11:08 | null | UTF-8 | C++ | false | false | 316 | ino | /*
* Sub vocal recognition sensor Serial printing to python
* Based off the Arduino ReadAnalogVoltage example.
*/
const int inputPin = A5; // Change to whatever pin yours is.
void setup() {
Serial.begin(115200); // Gotta go fast
}
void loop() {
Serial.println(analogRead(inputPin));
Serial.flush();
}
| [
"james.l.fu@gmail.com"
] | james.l.fu@gmail.com |
3ca4e3dc758b0618cd716101a1539beceb4a89df | 0c6da8b04ba38ba930364155fd3596b94c41dfbb | /Problemset/design-front-middle-back-queue/design-front-middle-back-queue.cpp | ba7e12b6fbf30bdca0307d51eb738c41d244f227 | [] | no_license | rubychen0611/LeetCode | 200725a80cf4e27b8180a14276d4f5c8958b5c39 | 185a0f9de2624345ca1f219be633ed1e891e6d8d | refs/heads/main | 2023-08-26T11:33:02.711733 | 2021-10-21T03:22:12 | 2021-10-21T03:22:12 | 306,789,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,666 | cpp |
// @Title: 设计前中后队列 (Design Front Middle Back Queue)
// @Author: rubychen0611
// @Date: 2020-12-24 19:19:05
// @Runtime: 72 ms
// @Memory: 20.3 MB
class FrontMiddleBackQueue {
private:
list<int> Q;
list<int>::iterator mid;
public:
FrontMiddleBackQueue() {
}
void pushFront(int val) {
if(Q.empty())
{
Q.push_front(val);
mid = Q.begin();
}
else
{
if (Q.size() % 2 == 1) // 奇数
{
Q.push_front(val);
mid --;
}
else // 偶数
{
Q.push_front(val);
}
}
}
void pushMiddle(int val)
{
if (Q.empty()) {
pushFront(val);
return;
}
if(Q.size() % 2 == 1)
{
mid = Q.insert(mid, val);
}
else
{
mid ++;
mid = Q.insert(mid, val);
}
}
void pushBack(int val) {
if(Q.empty())
{
Q.push_back(val);
mid = Q.begin();
}
else
{
if (Q.size() % 2 == 1) // 奇数
{
Q.push_back(val);
}
else // 偶数
{
Q.push_back(val);
mid ++;
}
}
}
int popFront() {
if (Q.empty())
return -1;
if (Q.size() % 2 == 1)
{
int x = Q.front();
Q.pop_front();
return x;
}
else
{
int x = Q.front();
mid++;
Q.pop_front();
return x;
}
}
int popMiddle() {
if (Q.empty())
return -1;
list<int>::iterator it = mid;
if (Q.size() % 2 == 1)
mid --;
else
mid ++;
int x = *it;
Q.erase(it);
return x;
}
int popBack() {
if (Q.empty())
return -1;
if (Q.size() % 2 == 1)
{
int x = Q.back();
mid--;
Q.pop_back();
return x;
}
else
{
int x = Q.back();
Q.pop_back();
return x;
}
}
};
/**
* Your FrontMiddleBackQueue object will be instantiated and called as such:
* FrontMiddleBackQueue* obj = new FrontMiddleBackQueue();
* obj->pushFront(val);
* obj->pushMiddle(val);
* obj->pushBack(val);
* int param_4 = obj->popFront();
* int param_5 = obj->popMiddle();
* int param_6 = obj->popBack();
*/
| [
"rubychen0611@yeah.net"
] | rubychen0611@yeah.net |
b95dffd1c23c09f025c1d5be9c61a519a3cd2e63 | d150cf91105b580bda2bfdd333513024fad3856c | /projet-minestorm/mainwindow.h | 7b7b66bcf8ce0a51ad698b891f1f32ec0422e7d5 | [] | no_license | rolljee/epsi-project | 4cd3e48b7058b9e935401facda1ef4a4da8cc446 | aad3f52b19782f171a33f96c8ad249929041c9d4 | refs/heads/master | 2021-05-01T01:03:23.659665 | 2017-03-22T21:41:31 | 2017-03-22T21:41:31 | 74,974,744 | 3 | 1 | null | 2016-12-03T17:58:17 | 2016-11-28T13:18:10 | C++ | UTF-8 | C++ | false | false | 372 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class Game;
/**
* @brief La classe MainWindow crée un widget contenant un controller et un gameboard pour le game
* donné
*/
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(Game *game,QWidget *parent = 0);
~MainWindow();
private:
};
#endif // MAINWINDOW_H
| [
"Nicolas RIQUELME"
] | Nicolas RIQUELME |
8841204e9d3d9c193ba403592d74ecc8771cb42a | 145f9616480e621b5ec5f16c21d4dcf4b7be27da | /entities/Attack.hpp | 2689a36fd931917df83a0546c6405f74a46d987e | [] | no_license | DavidSaxon/Advanced-Evolutionary-Tatics-LD24 | 4821eaf8b6fc7068fe3ca3059435b9312d852da5 | c5a7ed6390780e972cc062f5b60877f7efa0218d | refs/heads/master | 2016-09-05T20:27:56.842691 | 2012-08-26T23:29:44 | 2012-08-26T23:29:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | hpp | /*************************************************************\
| This is an attack, has a destination, team, and player type |
\*************************************************************/
#ifndef _ATTACK_H_
#define _ATTACK_H_
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include "../Entity.hpp"
using namespace std;
class Attack : public Entity {
private:
//VARIABLES
double destX; //the x destination
double destY; //the y destination
double xMove; //the move speed in the x direction
double yMove; //the move speed in the y direction
int type; //the type of attack
GLuint* tex; //the texture
int aliveTime; //the time the bullet is alive for
public:
//CONSTRUCTOR
Attack(int x, int y, double dx, double dy, int tp, bool p, GLuint* t);
//DESTRUCTOR
~Attack();
//FUNCTIONS
/*updates the attack*/
void update();
/*draws the attack*/
void draw(int offsetX, int offserY);
};
#endif
| [
"david.saxon@windowslive.com"
] | david.saxon@windowslive.com |
76d8249b32cbde41110bd3fbab6ae6db87bcb5f5 | e11d1a4b4059a18536ea44509754841735a94d2c | /algo/stack/cplusplus/push.cpp | 663078ecb232abae73bcf5779d966164b5123137 | [] | no_license | hexu1985/lib_code | e18577cda5b127db43381798b6a4879586a885f0 | 5833f2eaf1a6addbfcd2d81e76a151a424518d3e | refs/heads/master | 2020-06-25T22:31:32.220915 | 2020-05-21T06:40:06 | 2020-05-21T06:40:06 | 96,992,991 | 0 | 0 | null | 2017-07-12T10:00:51 | 2017-07-12T10:00:51 | null | UTF-8 | C++ | false | false | 348 | cpp | // stack::push/pop
#include <iostream> // std::cout
#include "stack.h" // stack
int main ()
{
stack<int> mystack;
for (int i=0; i<5; ++i) mystack.push(i);
std::cout << "Popping out elements...";
while (!mystack.empty())
{
std::cout << ' ' << mystack.top();
mystack.pop();
}
std::cout << '\n';
return 0;
}
| [
"hexu_bupt@sina.com"
] | hexu_bupt@sina.com |
86fefd3135aba74dc073da1b402c82211e7903cb | c0b1f0e7c2a690a1993ee6a7829e58d32f082424 | /thor/code/Thor/Graphics/GraphicsRuntimeDx11Component/ThHardwareBuffer.cpp | 4acce3bd6e9021fdd77da71e6310cbc85b255ea8 | [
"MIT"
] | permissive | Soth1985/Thor | 2c05189c5af0b8d3ce4fe6640f0b48cd57d2ff15 | 4e1c939183ce3e7f8ae4150cfe190f8f00d0f0b2 | refs/heads/master | 2020-12-25T19:03:55.824820 | 2015-01-01T14:12:43 | 2015-01-01T14:12:43 | 28,458,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,701 | cpp | #include <Thor/Graphics/GraphicsRuntimeDx11Component/ThHardwareBuffer.h>
#include <Thor/Graphics/GraphicsRuntimeDx11Component/ThDirectX11Renderer.h>
namespace Thor{
THOR_REG_TYPE(ThHardwareBuffer, THOR_TYPELIST_1(ThHardwareResource));
//----------------------------------------------------------------------------------------
//
// ThHardwareBuffer
//
//----------------------------------------------------------------------------------------
ThiType* ThHardwareBuffer::GetType()const
{
return ThType<ThHardwareBuffer>::Instance();
}
//----------------------------------------------------------------------------------------
ID3D11Resource* ThHardwareBuffer::GetResource()const
{
return m_Buffer;
}
//----------------------------------------------------------------------------------------
const ThString& ThHardwareBuffer::GetName()const
{
return *m_Name;
}
//----------------------------------------------------------------------------------------
ID3D11Buffer* ThHardwareBuffer::GetBuffer()const
{
return m_Buffer;
}
//----------------------------------------------------------------------------------------
ThHardwareBuffer::ThHardwareBuffer(const ThString* name, ThDirectX11Renderer* renderer, ID3D11Buffer* buffer)
:
m_Name(name),
m_Renderer(renderer),
m_Buffer(buffer)
{
//
}
//----------------------------------------------------------------------------------------
ThHardwareBuffer::ThHardwareBuffer()
{
//
}
//----------------------------------------------------------------------------------------
ThHardwareBuffer::~ThHardwareBuffer()
{
ThGraphicsUtils::SafeRelease(m_Buffer);
m_Renderer->RemoveHardwareBuffer(m_Name);
}
} | [
"soth1985@yahoo.com"
] | soth1985@yahoo.com |
86eb1c40e09aad945cff491d97ec83574ebcddfc | f5460007665164b39d62e20d6a353f006a023c1c | /SDSSystem/SDSSystem/Ctrl/MyLineEdit.h | 44accf6b4281dc263a802dd026f03909bcb94fa1 | [] | no_license | Windy-X/SDS_SEG | 861cb239b47da3d608ee5c5bda3811d67c64fdad | a09c7c60b6b97b929ef809b21c73a46e6669d438 | refs/heads/main | 2023-02-18T20:15:21.751381 | 2021-01-20T03:50:13 | 2021-01-20T03:50:13 | 331,186,007 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 676 | h | /********************************************************************
* Copyright (C) 深圳市德力凯电子有限公司
* All rights reserved
*
* 文件名称:MyLineEdit.h
* 摘 要:重载QLineEdit控件,控件获取焦点时向父窗口发送信号
*
* 历史记录:
* <2020/10/23> xiongz,
* ********************************************************************/
#pragma once
#include <QObject>
#include <QLineEdit>
#include <QFocusEvent>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
signals:
void SigEditGetFocus();
protected slots:
virtual void focusInEvent(QFocusEvent *ev) override;
public:
MyLineEdit(QWidget *parent = NULL);
~MyLineEdit();
};
| [
"Winnie199406@163.com"
] | Winnie199406@163.com |
1febf7aa39c2dd6474f2e83c994982454825ea41 | 229f25ccda6d721f31c6d4de27a7bb85dcc0f929 | /solutions/uva/11507 - Bender B. Rodríguez Problem/solution.cpp | 7b922e060a5156fda8117316d0727eef525ce08e | [] | no_license | camil0palacios/Competitive-programming | e743378a8791a66c90ffaae29b4fd4cfb58fff59 | 4211fa61e516cb986b3404d87409ad1a49f78132 | refs/heads/master | 2022-11-01T20:35:21.541132 | 2022-10-27T03:13:42 | 2022-10-27T03:13:42 | 155,419,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
while(cin >> n, n){
int dir = 0;
for(int i = 1; i < n; i++){
string s; cin >> s;
if(s == "+z"){
if(dir == 0)dir = 4;
else if(dir == 1)dir = 5;
else if(dir == 4)dir = 1;
else if(dir == 5)dir = 0;
}
if(s == "-z"){
if(dir == 0)dir = 5;
else if(dir == 1)dir = 4;
else if(dir == 4)dir = 0;
else if(dir == 5)dir = 1;
}
if(s == "+y"){
if(dir == 0)dir = 2;
else if(dir == 1)dir = 3;
else if(dir == 2)dir = 1;
else if(dir == 3)dir = 0;
}
if(s == "-y"){
if(dir == 0)dir = 3;
else if(dir == 1)dir = 2;
else if(dir == 2)dir = 0;
else if(dir == 3)dir = 1;
}
}
if(dir == 0)cout << "+x";
else if(dir == 1)cout << "-x";
else if(dir == 2)cout << "+y";
else if(dir == 3)cout << "-y";
else if(dir == 4)cout << "+z";
else if(dir == 5)cout << "-z";
cout << endl;
}
return 0;
} | [
"camilopalacios772@gmail.com"
] | camilopalacios772@gmail.com |
01d24fc54a0ff0422f7c9f261cf3c583e65d8e5e | eb205ea05c1ee102ff8306e9704a8e29477626c2 | /tqueue/Memory.h | 1d1a6a8c985083367807a3b5368dd85181f9fe73 | [] | no_license | lllhhhqqq/Utility | 54d2854e8ee6024b871b8cf6e1641137232fb184 | ab03538a16e8bd0a34e72a3e58acb3721ab8071a | refs/heads/master | 2021-01-23T06:29:23.940542 | 2014-06-08T14:57:04 | 2014-06-08T14:57:04 | 20,618,945 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,295 | h | #ifndef MEMORY_H_V1_0
#define MEMORY_H_V1_0
#include <list>
#include <string>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "Type_Cast.hpp"
class MemoryRead
{
public:
MemoryRead():read_offset(0),write_offset(0) {
buffer = new char[1024];
memset(buffer,0,sizeof(buffer));
}
~MemoryRead() {
delete []buffer;
}
inline void WritePos(size_t size)
{
memcpy(buffer + write_offset, (void*)&size, sizeof(size_t));
write_offset += sizeof(size_t);
}
template <typename T>
inline void write(typename RefType<T>::const_reftype val_write, size_t size)
{
WritePos(size);
memcpy(buffer + write_offset, (void*)(&val_write), size);
write_offset += size;
}
inline size_t ReadPos()
{
size_t length;
memcpy((void*)&length, buffer+read_offset, sizeof(size_t));
read_offset += sizeof(size_t);
return length;
}
template <typename T>
inline void read(typename RefType<T>::reftype val_read)
{
size_t length = ReadPos();
memcpy((void*)&val_read, buffer+read_offset, length);
read_offset += length;
}
public:
class Iterator
{
public:
Iterator();
~Iterator();
private:
};
private:
char* buffer;
size_t read_offset;
size_t write_offset;
};
template <>
inline void MemoryRead::write<std::string&>(const std::string& val_write, size_t size)
{
WritePos(val_write.length());
memcpy(buffer + write_offset, (void*)val_write.c_str(), val_write.length()+1);
write_offset += val_write.length()+1;
}
template <>
inline void MemoryRead::write<char*>(const char* val_write, size_t size)
{
WritePos(size);
memcpy(buffer + write_offset, (void*)val_write, size);
write_offset += size;
}
template <>
inline void MemoryRead::read<std::string&>(std::string& val_read)
{
size_t length = ReadPos();
//val_read = std::string(buffer+read_offset,length);
val_read.append(buffer+read_offset,length);
read_offset += length + 1;
}
template <>
inline void MemoryRead::read<char*>(char* val_read)
{
size_t length = ReadPos();
memcpy((void*)val_read, buffer+read_offset, length);
read_offset += length;
}
//////////////////////////////////////////////////////////////////////////
//insert help,? to support map set hashmap?
template <typename T,typename Container>
struct InsertHelp
{
typedef Container container_type;
static inline void Insert(Container& c,T& value)
{
//static_assert(false,"not support this type");
}
};
template <typename T>
struct InsertHelp<T, std::list<T>>
{
typedef std::list<T> container_type;
static inline void Insert(std::list<T>& c,T& value)
{
//c.insert(value);
c.push_back(value);
}
};
template <typename T>
struct InsertHelp<T, std::vector<T>>
{
typedef std::vector<T> container_type;
static inline void Insert(std::vector<T>& c,T& value)
{
c.push_back(value);
}
};
//////////////////////////////////////////////////////////////////////////
template <typename T, typename _TyImpl>
struct DataProxy;
template <typename T, typename _TyImpl>
struct DataProxy
{
static inline void write_head(_TyImpl& impl, size_t size)
{
impl.WritePos(size);
}
static inline size_t read_head(_TyImpl& impl)
{
size_t size = impl.ReadPos();
return size;
}
static inline void write(_TyImpl& impl, const T& valwrite, size_t size)
{
//默认采用结构体自己的方法来构造,读写序列
WriteParam(impl, valwrite, false);
}
static inline void read(_TyImpl& impl, T& valread)
{
//默认采用结构体自己的方法来构造,读写序列
ReadParam(impl, valread, false);
}
};
template <typename T, typename _TyImpl>
struct DataProxy< std::vector<T>&, _TyImpl >
{
typedef InsertHelp<T, std::vector<T> > InsertType;
typedef typename InsertType::container_type ContainerType;
typedef typename RefType<T>::reftype reftype;
static inline void write_head(_TyImpl& impl, size_t size)
{
impl.WritePos(size);
}
static inline size_t read_head(_TyImpl& impl)
{
size_t size = impl.ReadPos();
return size;
}
static inline void write(_TyImpl& impl, const ContainerType& valwrite, size_t size)
{
size = valwrite.size();
impl.WritePos(size);
for (auto begin = valwrite.begin(); begin != valwrite.end(); ++begin)
{
//TODO: not call DataProxy, to call Param,makeparam need innerdata;
DataProxy<reftype, _TyImpl>::write(impl,*begin,sizeof(T));
}
}
static inline void read(_TyImpl& impl, ContainerType& valread)
{
size_t size = impl.ReadPos();
for (size_t i = 0; i < size; ++i)
{
T value;
DataProxy<reftype, _TyImpl>::read(impl,value);
InsertType::Insert(valread,value);
}
}
};
template <typename T, typename _TyImpl>
struct DataProxy< std::list<T>&, _TyImpl >
{
typedef InsertHelp<T, std::list<T> > InsertType;
typedef typename InsertType::container_type ContainerType;
typedef typename RefType<T>::reftype reftype;
static inline void write_head(_TyImpl& impl, size_t size)
{
impl.WritePos(size);
}
static inline size_t read_head(_TyImpl& impl)
{
size_t size = impl.ReadPos();
return size;
}
static inline void write(_TyImpl& impl, const ContainerType& valwrite, size_t size)
{
size = valwrite.size();
impl.WritePos(size);
for (auto begin = valwrite.begin(); begin != valwrite.end(); ++begin)
{
//DataProxy<T>::write(*begin);
DataProxy<reftype,_TyImpl>::write(impl,*begin,sizeof(T));
}
}
static inline void read(_TyImpl& impl, ContainerType& valread)
{
size_t size = impl.ReadPos();
for (size_t i = 0; i < size; ++i)
{
T value;
DataProxy<reftype, _TyImpl>::read(impl,value);
InsertType::Insert(valread,value);
}
}
};
#define HEAD_FUNC_DECLARE(Impl) \
static inline void write_head(Impl& impl, size_t size) \
{ impl.WritePos(size); } \
static inline size_t read_head(Impl& impl) \
{ \
size_t size = impl.ReadPos(); \
return size; \
}
#define Proxy_COMMON_DECLARE(type, Impl) \
template <typename Impl>\
struct DataProxy<type, Impl>\
{\
HEAD_FUNC_DECLARE(Impl) \
static inline void write(Impl& impl, const type& valwrite, size_t size)\
{\
impl.write<type>(valwrite, size);\
}\
static inline void read(Impl& impl, type& valread)\
{\
impl.read<type>(valread);\
}\
};
#define Proxy_COMMON_PTR_DEDLARE(type) \
template <typename Impl>\
struct DataProxy<type, Impl>\
{\
HEAD_FUNC_DECLARE(Impl) \
static inline void write(Impl& impl, const type valwrite, size_t size)\
{\
impl.write<type>(valwrite, size);\
}\
static inline void read(Impl& impl, type valread)\
{\
impl.read<type>(valread);\
}\
};
#define Proxy_COMMON_REF_DECLARE(type, Impl) \
template <typename Impl>\
struct DataProxy<type, Impl>\
{\
HEAD_FUNC_DECLARE(Impl) \
static inline void write(Impl& impl, const type valwrite, size_t size)\
{\
impl.write<type>(valwrite, size);\
}\
static inline void read(Impl& impl, type valread)\
{\
impl.read<type>(valread);\
}\
};
Proxy_COMMON_DECLARE(int, MemoryRead)
Proxy_COMMON_DECLARE(unsigned int, MemoryRead)
Proxy_COMMON_DECLARE(char, MemoryRead)
Proxy_COMMON_DECLARE(long, MemoryRead)
Proxy_COMMON_DECLARE(bool, MemoryRead)
Proxy_COMMON_DECLARE(long long, MemoryRead)
Proxy_COMMON_DECLARE(std::string, MemoryRead)
Proxy_COMMON_REF_DECLARE(int&, MemoryRead)
Proxy_COMMON_REF_DECLARE(unsigned int&, MemoryRead)
Proxy_COMMON_REF_DECLARE(char&, MemoryRead)
Proxy_COMMON_REF_DECLARE(long&, MemoryRead)
Proxy_COMMON_REF_DECLARE(bool&, MemoryRead)
Proxy_COMMON_REF_DECLARE(long long&, MemoryRead)
Proxy_COMMON_REF_DECLARE(std::string&, MemoryRead)
/*
template <>
struct DataProxy<std::string&>
{
static inline void write(MemoryRead& m, const std::string& valwrite, size_t size)
{
m.write<std::string&>(valwrite, size);
}
static inline void read(MemoryRead& m, std::string& valread)
{
m.read<std::string&>(valread);
}
};*/
//Proxy_COMMON_REF_DECLARE(std::string&)
Proxy_COMMON_PTR_DEDLARE(char*)
#endif // !MEMORY_H_V1_0
| [
"lllhhhqqqlhq2007@hotmail.com"
] | lllhhhqqqlhq2007@hotmail.com |
b152ff7ce537422f241f96ba1812b3ce253c279b | 89607b067f4194fd3861a00a5f7691cda1430c0d | /src/kademlia/boost_to_std_error.hpp | 84af38739c816752ac92d7ce9bf9dcd822a023aa | [] | no_license | lsst-dm/kademlia | f093609a706d4428e8c0cf2e2d4adc3a4cfa8996 | 546f679888b9dd2c6beff82814122d6a83011dae | refs/heads/master | 2021-01-15T18:59:32.012811 | 2015-09-13T16:56:44 | 2015-09-13T16:56:44 | 41,469,325 | 0 | 0 | null | 2015-08-27T06:20:38 | 2015-08-27T06:20:38 | null | UTF-8 | C++ | false | false | 2,363 | hpp | // Copyright (c) 2013-2014, David Keller
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the University of California, Berkeley nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY DAVID KELLER 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 REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef KADEMLIA_BOOST_TO_STD_ERROR_HPP
#define KADEMLIA_BOOST_TO_STD_ERROR_HPP
#ifdef _MSC_VER
# pragma once
#endif
#include <system_error>
#include <boost/system/error_code.hpp>
#include "kademlia/error_impl.hpp"
namespace kademlia {
namespace detail {
/**
*
*/
inline std::error_code
boost_to_std_error
( boost::system::error_code const& failure )
{
if ( failure.category() == boost::system::generic_category() )
return std::error_code{ failure.value(), std::generic_category() };
else if ( failure.category() == boost::system::system_category() )
return std::error_code{ failure.value(), std::system_category() };
else
return make_error_code( UNKNOWN );
}
} // namespace detail
} // namespace kademlia
#endif
| [
"david.keller@litchis.fr"
] | david.keller@litchis.fr |
7e288521ab02e29b68ce3946c73254ffc1b72bae | 4f530f52e204fa4cbf47cd1d6eaaf79d27dc9c4d | /include/dynamic_introspection/DynamicIntrospection.h | d79bdfe05ba55e098228a2f0cefffb5ec7a781cd | [] | no_license | pal-robotics/dynamic_introspection | 389413d928e092e509c026c1edaae2d0a81e24ae | e575d9a46071cc80e018c0f11d19425a43d9921b | refs/heads/master | 2021-05-13T17:26:19.339372 | 2015-02-19T16:44:03 | 2015-02-19T16:44:03 | 116,823,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | #ifndef _DYNAMIC_INTROSPECTION_
#define _DYNAMIC_INTROSPECTION_
#include <Eigen/Dense>
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <dynamic_introspection/IntrospectionMsg.h>
class DynamicIntrospection{
public:
DynamicIntrospection(ros::NodeHandle &nh, const std::string &topic);
~DynamicIntrospection();
void registerVariable(int *variable, std::string id);
void registerVariable(double *variable, std::string id);
void registerVariable(bool *variable, std::string id);
void registerVariable(Eigen::VectorXd *variable, std::string id);
void registerVariable(Eigen::MatrixXd *variable, std::string id);
void generateMessage();
void publishDataTopic();
void publishDataBag();
void closeBag();
void openBag(std::string fileName);
private:
bool openedBag_;
bool configured_;
ros::NodeHandle node_handle_;
ros::Publisher introspectionPub_;
rosbag::Bag bag_;
//Registered variables
std::vector< std::pair<std::string, int*> > registeredInt_;
std::vector< std::pair<std::string, double*> > registeredDouble_;
std::vector<std::pair<std::string, bool*> > registeredBool_;
std::vector<std::pair<std::string, Eigen::VectorXd*> > registeredVector_;
std::vector<std::pair<std::string, Eigen::MatrixXd*> > registeredMatrix_;
dynamic_introspection::IntrospectionMsg introspectionMessage_;
};
typedef boost::shared_ptr<DynamicIntrospection> DynamicIntrospectionPtr;
#endif
| [
"hilario.tome@pal-robotics.com"
] | hilario.tome@pal-robotics.com |
263d55547a2b1441b0f19c5f292a8046dd93a59c | decefb13f8a603c1f5cc7eb00634b4649915204f | /packages/node-mobile/deps/icu-small/source/tools/genrb/reslist.cpp | 3186c781e934f3767b3007e85c5092379294dc9f | [
"Zlib",
"CC0-1.0",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"ICU",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"Artistic-2.0",
"BSD-3-Clause",
"NTP",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-sc... | permissive | open-pwa/open-pwa | f092b377dc6cb04123a16ef96811ad09a9956c26 | 4c88c8520b4f6e7af8701393fd2cedbe1b209e8f | refs/heads/master | 2022-05-28T22:05:19.514921 | 2022-05-20T07:27:10 | 2022-05-20T07:27:10 | 247,925,596 | 24 | 1 | Apache-2.0 | 2021-08-10T07:38:42 | 2020-03-17T09:13:00 | C++ | UTF-8 | C++ | false | false | 61,318 | cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2000-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
*
* File reslist.cpp
*
* Modification History:
*
* Date Name Description
* 02/21/00 weiv Creation.
*******************************************************************************
*/
// Safer use of UnicodeString.
#ifndef UNISTR_FROM_CHAR_EXPLICIT
# define UNISTR_FROM_CHAR_EXPLICIT explicit
#endif
// Less important, but still a good idea.
#ifndef UNISTR_FROM_STRING_EXPLICIT
# define UNISTR_FROM_STRING_EXPLICIT explicit
#endif
#include <assert.h>
#include <iostream>
#include <set>
#include <stdio.h>
#include "unicode/localpointer.h"
#include "reslist.h"
#include "unewdata.h"
#include "unicode/ures.h"
#include "unicode/putil.h"
#include "errmsg.h"
#include "filterrb.h"
#include "uarrsort.h"
#include "uelement.h"
#include "uhash.h"
#include "uinvchar.h"
#include "ustr_imp.h"
#include "unicode/utf16.h"
#include "uassert.h"
/*
* Align binary data at a 16-byte offset from the start of the resource bundle,
* to be safe for any data type it may contain.
*/
#define BIN_ALIGNMENT 16
// This numeric constant must be at least 1.
// If StringResource.fNumUnitsSaved == 0 then the string occurs only once,
// and it makes no sense to move it to the pool bundle.
// The larger the threshold for fNumUnitsSaved
// the smaller the savings, and the smaller the pool bundle.
// We trade some total size reduction to reduce the pool bundle a bit,
// so that one can reasonably save data size by
// removing bundle files without rebuilding the pool bundle.
// This can also help to keep the pool and total (pool+local) string indexes
// within 16 bits, that is, within range of Table16 and Array16 containers.
#ifndef GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING
# define GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING 10
#endif
U_NAMESPACE_USE
static UBool gIncludeCopyright = FALSE;
static UBool gUsePoolBundle = FALSE;
static UBool gIsDefaultFormatVersion = TRUE;
static int32_t gFormatVersion = 3;
/* How do we store string values? */
enum {
STRINGS_UTF16_V1, /* formatVersion 1: int length + UChars + NUL + padding to 4 bytes */
STRINGS_UTF16_V2 /* formatVersion 2 & up: optional length in 1..3 UChars + UChars + NUL */
};
static const int32_t MAX_IMPLICIT_STRING_LENGTH = 40; /* do not store the length explicitly for such strings */
static const ResFile kNoPoolBundle;
/*
* res_none() returns the address of kNoResource,
* for use in non-error cases when no resource is to be added to the bundle.
* (NULL is used in error cases.)
*/
static SResource kNoResource; // TODO: const
static UDataInfo dataInfo= {
sizeof(UDataInfo),
0,
U_IS_BIG_ENDIAN,
U_CHARSET_FAMILY,
sizeof(UChar),
0,
{0x52, 0x65, 0x73, 0x42}, /* dataFormat="ResB" */
{1, 3, 0, 0}, /* formatVersion */
{1, 4, 0, 0} /* dataVersion take a look at version inside parsed resb*/
};
static const UVersionInfo gFormatVersions[4] = { /* indexed by a major-formatVersion integer */
{ 0, 0, 0, 0 },
{ 1, 3, 0, 0 },
{ 2, 0, 0, 0 },
{ 3, 0, 0, 0 }
};
// Remember to update genrb.h GENRB_VERSION when changing the data format.
// (Or maybe we should remove GENRB_VERSION and report the ICU version number?)
static uint8_t calcPadding(uint32_t size) {
/* returns space we need to pad */
return (uint8_t) ((size % sizeof(uint32_t)) ? (sizeof(uint32_t) - (size % sizeof(uint32_t))) : 0);
}
void setIncludeCopyright(UBool val){
gIncludeCopyright=val;
}
UBool getIncludeCopyright(void){
return gIncludeCopyright;
}
void setFormatVersion(int32_t formatVersion) {
gIsDefaultFormatVersion = FALSE;
gFormatVersion = formatVersion;
}
int32_t getFormatVersion() {
return gFormatVersion;
}
void setUsePoolBundle(UBool use) {
gUsePoolBundle = use;
}
// TODO: return const pointer, or find another way to express "none"
struct SResource* res_none() {
return &kNoResource;
}
SResource::SResource()
: fType(URES_NONE), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1), fKey(-1), fKey16(-1),
line(0), fNext(NULL) {
ustr_init(&fComment);
}
SResource::SResource(SRBRoot *bundle, const char *tag, int8_t type, const UString* comment,
UErrorCode &errorCode)
: fType(type), fWritten(FALSE), fRes(RES_BOGUS), fRes16(-1),
fKey(bundle != NULL ? bundle->addTag(tag, errorCode) : -1), fKey16(-1),
line(0), fNext(NULL) {
ustr_init(&fComment);
if(comment != NULL) {
ustr_cpy(&fComment, comment, &errorCode);
}
}
SResource::~SResource() {
ustr_deinit(&fComment);
}
ContainerResource::~ContainerResource() {
SResource *current = fFirst;
while (current != NULL) {
SResource *next = current->fNext;
delete current;
current = next;
}
}
TableResource::~TableResource() {}
// TODO: clarify that containers adopt new items, even in error cases; use LocalPointer
void TableResource::add(SResource *res, int linenumber, UErrorCode &errorCode) {
if (U_FAILURE(errorCode) || res == NULL || res == &kNoResource) {
return;
}
/* remember this linenumber to report to the user if there is a duplicate key */
res->line = linenumber;
/* here we need to traverse the list */
++fCount;
/* is the list still empty? */
if (fFirst == NULL) {
fFirst = res;
res->fNext = NULL;
return;
}
const char *resKeyString = fRoot->fKeys + res->fKey;
SResource *current = fFirst;
SResource *prev = NULL;
while (current != NULL) {
const char *currentKeyString = fRoot->fKeys + current->fKey;
int diff;
/*
* formatVersion 1: compare key strings in native-charset order
* formatVersion 2 and up: compare key strings in ASCII order
*/
if (gFormatVersion == 1 || U_CHARSET_FAMILY == U_ASCII_FAMILY) {
diff = uprv_strcmp(currentKeyString, resKeyString);
} else {
diff = uprv_compareInvCharsAsAscii(currentKeyString, resKeyString);
}
if (diff < 0) {
prev = current;
current = current->fNext;
} else if (diff > 0) {
/* we're either in front of the list, or in the middle */
if (prev == NULL) {
/* front of the list */
fFirst = res;
} else {
/* middle of the list */
prev->fNext = res;
}
res->fNext = current;
return;
} else {
/* Key already exists! ERROR! */
error(linenumber, "duplicate key '%s' in table, first appeared at line %d", currentKeyString, current->line);
errorCode = U_UNSUPPORTED_ERROR;
return;
}
}
/* end of list */
prev->fNext = res;
res->fNext = NULL;
}
ArrayResource::~ArrayResource() {}
void ArrayResource::add(SResource *res) {
if (res != NULL && res != &kNoResource) {
if (fFirst == NULL) {
fFirst = res;
} else {
fLast->fNext = res;
}
fLast = res;
++fCount;
}
}
PseudoListResource::~PseudoListResource() {}
void PseudoListResource::add(SResource *res) {
if (res != NULL && res != &kNoResource) {
res->fNext = fFirst;
fFirst = res;
++fCount;
}
}
StringBaseResource::StringBaseResource(SRBRoot *bundle, const char *tag, int8_t type,
const UChar *value, int32_t len,
const UString* comment, UErrorCode &errorCode)
: SResource(bundle, tag, type, comment, errorCode) {
if (len == 0 && gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(type);
fWritten = TRUE;
return;
}
fString.setTo(ConstChar16Ptr(value), len);
fString.getTerminatedBuffer(); // Some code relies on NUL-termination.
if (U_SUCCESS(errorCode) && fString.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
}
StringBaseResource::StringBaseResource(SRBRoot *bundle, int8_t type,
const icu::UnicodeString &value, UErrorCode &errorCode)
: SResource(bundle, NULL, type, NULL, errorCode), fString(value) {
if (value.isEmpty() && gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(type);
fWritten = TRUE;
return;
}
fString.getTerminatedBuffer(); // Some code relies on NUL-termination.
if (U_SUCCESS(errorCode) && fString.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
}
// Pool bundle string, alias the buffer. Guaranteed NUL-terminated and not empty.
StringBaseResource::StringBaseResource(int8_t type, const UChar *value, int32_t len,
UErrorCode &errorCode)
: SResource(NULL, NULL, type, NULL, errorCode), fString(TRUE, value, len) {
assert(len > 0);
assert(!fString.isBogus());
}
StringBaseResource::~StringBaseResource() {}
static int32_t U_CALLCONV
string_hash(const UElement key) {
const StringResource *res = static_cast<const StringResource *>(key.pointer);
return res->fString.hashCode();
}
static UBool U_CALLCONV
string_comp(const UElement key1, const UElement key2) {
const StringResource *res1 = static_cast<const StringResource *>(key1.pointer);
const StringResource *res2 = static_cast<const StringResource *>(key2.pointer);
return res1->fString == res2->fString;
}
StringResource::~StringResource() {}
AliasResource::~AliasResource() {}
IntResource::IntResource(SRBRoot *bundle, const char *tag, int32_t value,
const UString* comment, UErrorCode &errorCode)
: SResource(bundle, tag, URES_INT, comment, errorCode) {
fValue = value;
fRes = URES_MAKE_RESOURCE(URES_INT, value & RES_MAX_OFFSET);
fWritten = TRUE;
}
IntResource::~IntResource() {}
IntVectorResource::IntVectorResource(SRBRoot *bundle, const char *tag,
const UString* comment, UErrorCode &errorCode)
: SResource(bundle, tag, URES_INT_VECTOR, comment, errorCode),
fCount(0), fArray(new uint32_t[RESLIST_MAX_INT_VECTOR]) {
if (fArray == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
IntVectorResource::~IntVectorResource() {
delete[] fArray;
}
void IntVectorResource::add(int32_t value, UErrorCode &errorCode) {
if (U_SUCCESS(errorCode)) {
fArray[fCount++] = value;
}
}
BinaryResource::BinaryResource(SRBRoot *bundle, const char *tag,
uint32_t length, uint8_t *data, const char* fileName,
const UString* comment, UErrorCode &errorCode)
: SResource(bundle, tag, URES_BINARY, comment, errorCode),
fLength(length), fData(NULL), fFileName(NULL) {
if (U_FAILURE(errorCode)) {
return;
}
if (fileName != NULL && *fileName != 0){
fFileName = new char[uprv_strlen(fileName)+1];
if (fFileName == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_strcpy(fFileName, fileName);
}
if (length > 0) {
fData = new uint8_t[length];
if (fData == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
uprv_memcpy(fData, data, length);
} else {
if (gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(URES_BINARY);
fWritten = TRUE;
}
}
}
BinaryResource::~BinaryResource() {
delete[] fData;
delete[] fFileName;
}
/* Writing Functions */
void
StringResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet,
UErrorCode &errorCode) {
assert(fSame == NULL);
fSame = static_cast<StringResource *>(uhash_get(stringSet, this));
if (fSame != NULL) {
// This is a duplicate of a pool bundle string or of an earlier-visited string.
if (++fSame->fNumCopies == 1) {
assert(fSame->fWritten);
int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(fSame->fRes);
if (poolStringIndex >= bundle->fPoolStringIndexLimit) {
bundle->fPoolStringIndexLimit = poolStringIndex + 1;
}
}
return;
}
/* Put this string into the set for finding duplicates. */
fNumCopies = 1;
uhash_put(stringSet, this, this, &errorCode);
if (bundle->fStringsForm != STRINGS_UTF16_V1) {
int32_t len = length();
if (len <= MAX_IMPLICIT_STRING_LENGTH &&
!U16_IS_TRAIL(fString[0]) && fString.indexOf((UChar)0) < 0) {
/*
* This string will be stored without an explicit length.
* Runtime will detect !U16_IS_TRAIL(s[0]) and call u_strlen().
*/
fNumCharsForLength = 0;
} else if (len <= 0x3ee) {
fNumCharsForLength = 1;
} else if (len <= 0xfffff) {
fNumCharsForLength = 2;
} else {
fNumCharsForLength = 3;
}
bundle->f16BitStringsLength += fNumCharsForLength + len + 1; /* +1 for the NUL */
}
}
void
ContainerResource::handlePreflightStrings(SRBRoot *bundle, UHashtable *stringSet,
UErrorCode &errorCode) {
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
current->preflightStrings(bundle, stringSet, errorCode);
}
}
void
SResource::preflightStrings(SRBRoot *bundle, UHashtable *stringSet, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return;
}
if (fRes != RES_BOGUS) {
/*
* The resource item word was already precomputed, which means
* no further data needs to be written.
* This might be an integer, or an empty string/binary/etc.
*/
return;
}
handlePreflightStrings(bundle, stringSet, errorCode);
}
void
SResource::handlePreflightStrings(SRBRoot * /*bundle*/, UHashtable * /*stringSet*/,
UErrorCode & /*errorCode*/) {
/* Neither a string nor a container. */
}
int32_t
SRBRoot::makeRes16(uint32_t resWord) const {
if (resWord == 0) {
return 0; /* empty string */
}
uint32_t type = RES_GET_TYPE(resWord);
int32_t offset = (int32_t)RES_GET_OFFSET(resWord);
if (type == URES_STRING_V2) {
assert(offset > 0);
if (offset < fPoolStringIndexLimit) {
if (offset < fPoolStringIndex16Limit) {
return offset;
}
} else {
offset = offset - fPoolStringIndexLimit + fPoolStringIndex16Limit;
if (offset <= 0xffff) {
return offset;
}
}
}
return -1;
}
int32_t
SRBRoot::mapKey(int32_t oldpos) const {
const KeyMapEntry *map = fKeyMap;
if (map == NULL) {
return oldpos;
}
int32_t i, start, limit;
/* do a binary search for the old, pre-compactKeys() key offset */
start = fUsePoolBundle->fKeysCount;
limit = start + fKeysCount;
while (start < limit - 1) {
i = (start + limit) / 2;
if (oldpos < map[i].oldpos) {
limit = i;
} else {
start = i;
}
}
assert(oldpos == map[start].oldpos);
return map[start].newpos;
}
/*
* Only called for UTF-16 v1 strings and duplicate UTF-16 v2 strings.
* For unique UTF-16 v2 strings, write16() sees fRes != RES_BOGUS
* and exits early.
*/
void
StringResource::handleWrite16(SRBRoot * /*bundle*/) {
SResource *same;
if ((same = fSame) != NULL) {
/* This is a duplicate. */
assert(same->fRes != RES_BOGUS && same->fWritten);
fRes = same->fRes;
fWritten = same->fWritten;
}
}
void
ContainerResource::writeAllRes16(SRBRoot *bundle) {
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
bundle->f16BitUnits.append((UChar)current->fRes16);
}
fWritten = TRUE;
}
void
ArrayResource::handleWrite16(SRBRoot *bundle) {
if (fCount == 0 && gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(URES_ARRAY);
fWritten = TRUE;
return;
}
int32_t res16 = 0;
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
current->write16(bundle);
res16 |= current->fRes16;
}
if (fCount <= 0xffff && res16 >= 0 && gFormatVersion > 1) {
fRes = URES_MAKE_RESOURCE(URES_ARRAY16, bundle->f16BitUnits.length());
bundle->f16BitUnits.append((UChar)fCount);
writeAllRes16(bundle);
}
}
void
TableResource::handleWrite16(SRBRoot *bundle) {
if (fCount == 0 && gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE);
fWritten = TRUE;
return;
}
/* Find the smallest table type that fits the data. */
int32_t key16 = 0;
int32_t res16 = 0;
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
current->write16(bundle);
key16 |= current->fKey16;
res16 |= current->fRes16;
}
if(fCount > (uint32_t)bundle->fMaxTableLength) {
bundle->fMaxTableLength = fCount;
}
if (fCount <= 0xffff && key16 >= 0) {
if (res16 >= 0 && gFormatVersion > 1) {
/* 16-bit count, key offsets and values */
fRes = URES_MAKE_RESOURCE(URES_TABLE16, bundle->f16BitUnits.length());
bundle->f16BitUnits.append((UChar)fCount);
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
bundle->f16BitUnits.append((UChar)current->fKey16);
}
writeAllRes16(bundle);
} else {
/* 16-bit count, 16-bit key offsets, 32-bit values */
fTableType = URES_TABLE;
}
} else {
/* 32-bit count, key offsets and values */
fTableType = URES_TABLE32;
}
}
void
PseudoListResource::handleWrite16(SRBRoot * /*bundle*/) {
fRes = URES_MAKE_EMPTY_RESOURCE(URES_TABLE);
fWritten = TRUE;
}
void
SResource::write16(SRBRoot *bundle) {
if (fKey >= 0) {
// A tagged resource has a non-negative key index into the parsed key strings.
// compactKeys() built a map from parsed key index to the final key index.
// After the mapping, negative key indexes are used for shared pool bundle keys.
fKey = bundle->mapKey(fKey);
// If the key index fits into a Key16 for a Table or Table16,
// then set the fKey16 field accordingly.
// Otherwise keep it at -1.
if (fKey >= 0) {
if (fKey < bundle->fLocalKeyLimit) {
fKey16 = fKey;
}
} else {
int32_t poolKeyIndex = fKey & 0x7fffffff;
if (poolKeyIndex <= 0xffff) {
poolKeyIndex += bundle->fLocalKeyLimit;
if (poolKeyIndex <= 0xffff) {
fKey16 = poolKeyIndex;
}
}
}
}
/*
* fRes != RES_BOGUS:
* The resource item word was already precomputed, which means
* no further data needs to be written.
* This might be an integer, or an empty or UTF-16 v2 string,
* an empty binary, etc.
*/
if (fRes == RES_BOGUS) {
handleWrite16(bundle);
}
// Compute fRes16 for precomputed as well as just-computed fRes.
fRes16 = bundle->makeRes16(fRes);
}
void
SResource::handleWrite16(SRBRoot * /*bundle*/) {
/* Only a few resource types write 16-bit units. */
}
/*
* Only called for UTF-16 v1 strings, and for aliases.
* For UTF-16 v2 strings, preWrite() sees fRes != RES_BOGUS
* and exits early.
*/
void
StringBaseResource::handlePreWrite(uint32_t *byteOffset) {
/* Write the UTF-16 v1 string. */
fRes = URES_MAKE_RESOURCE(fType, *byteOffset >> 2);
*byteOffset += 4 + (length() + 1) * U_SIZEOF_UCHAR;
}
void
IntVectorResource::handlePreWrite(uint32_t *byteOffset) {
if (fCount == 0 && gFormatVersion > 1) {
fRes = URES_MAKE_EMPTY_RESOURCE(URES_INT_VECTOR);
fWritten = TRUE;
} else {
fRes = URES_MAKE_RESOURCE(URES_INT_VECTOR, *byteOffset >> 2);
*byteOffset += (1 + fCount) * 4;
}
}
void
BinaryResource::handlePreWrite(uint32_t *byteOffset) {
uint32_t pad = 0;
uint32_t dataStart = *byteOffset + sizeof(fLength);
if (dataStart % BIN_ALIGNMENT) {
pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT);
*byteOffset += pad; /* pad == 4 or 8 or 12 */
}
fRes = URES_MAKE_RESOURCE(URES_BINARY, *byteOffset >> 2);
*byteOffset += 4 + fLength;
}
void
ContainerResource::preWriteAllRes(uint32_t *byteOffset) {
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
current->preWrite(byteOffset);
}
}
void
ArrayResource::handlePreWrite(uint32_t *byteOffset) {
preWriteAllRes(byteOffset);
fRes = URES_MAKE_RESOURCE(URES_ARRAY, *byteOffset >> 2);
*byteOffset += (1 + fCount) * 4;
}
void
TableResource::handlePreWrite(uint32_t *byteOffset) {
preWriteAllRes(byteOffset);
if (fTableType == URES_TABLE) {
/* 16-bit count, 16-bit key offsets, 32-bit values */
fRes = URES_MAKE_RESOURCE(URES_TABLE, *byteOffset >> 2);
*byteOffset += 2 + fCount * 6;
} else {
/* 32-bit count, key offsets and values */
fRes = URES_MAKE_RESOURCE(URES_TABLE32, *byteOffset >> 2);
*byteOffset += 4 + fCount * 8;
}
}
void
SResource::preWrite(uint32_t *byteOffset) {
if (fRes != RES_BOGUS) {
/*
* The resource item word was already precomputed, which means
* no further data needs to be written.
* This might be an integer, or an empty or UTF-16 v2 string,
* an empty binary, etc.
*/
return;
}
handlePreWrite(byteOffset);
*byteOffset += calcPadding(*byteOffset);
}
void
SResource::handlePreWrite(uint32_t * /*byteOffset*/) {
assert(FALSE);
}
/*
* Only called for UTF-16 v1 strings, and for aliases. For UTF-16 v2 strings,
* write() sees fWritten and exits early.
*/
void
StringBaseResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) {
/* Write the UTF-16 v1 string. */
int32_t len = length();
udata_write32(mem, len);
udata_writeUString(mem, getBuffer(), len + 1);
*byteOffset += 4 + (len + 1) * U_SIZEOF_UCHAR;
fWritten = TRUE;
}
void
ContainerResource::writeAllRes(UNewDataMemory *mem, uint32_t *byteOffset) {
uint32_t i = 0;
for (SResource *current = fFirst; current != NULL; ++i, current = current->fNext) {
current->write(mem, byteOffset);
}
assert(i == fCount);
}
void
ContainerResource::writeAllRes32(UNewDataMemory *mem, uint32_t *byteOffset) {
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
udata_write32(mem, current->fRes);
}
*byteOffset += fCount * 4;
}
void
ArrayResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) {
writeAllRes(mem, byteOffset);
udata_write32(mem, fCount);
*byteOffset += 4;
writeAllRes32(mem, byteOffset);
}
void
IntVectorResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) {
udata_write32(mem, fCount);
for(uint32_t i = 0; i < fCount; ++i) {
udata_write32(mem, fArray[i]);
}
*byteOffset += (1 + fCount) * 4;
}
void
BinaryResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) {
uint32_t pad = 0;
uint32_t dataStart = *byteOffset + sizeof(fLength);
if (dataStart % BIN_ALIGNMENT) {
pad = (BIN_ALIGNMENT - dataStart % BIN_ALIGNMENT);
udata_writePadding(mem, pad); /* pad == 4 or 8 or 12 */
*byteOffset += pad;
}
udata_write32(mem, fLength);
if (fLength > 0) {
udata_writeBlock(mem, fData, fLength);
}
*byteOffset += 4 + fLength;
}
void
TableResource::handleWrite(UNewDataMemory *mem, uint32_t *byteOffset) {
writeAllRes(mem, byteOffset);
if(fTableType == URES_TABLE) {
udata_write16(mem, (uint16_t)fCount);
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
udata_write16(mem, current->fKey16);
}
*byteOffset += (1 + fCount)* 2;
if ((fCount & 1) == 0) {
/* 16-bit count and even number of 16-bit key offsets need padding before 32-bit resource items */
udata_writePadding(mem, 2);
*byteOffset += 2;
}
} else /* URES_TABLE32 */ {
udata_write32(mem, fCount);
for (SResource *current = fFirst; current != NULL; current = current->fNext) {
udata_write32(mem, (uint32_t)current->fKey);
}
*byteOffset += (1 + fCount)* 4;
}
writeAllRes32(mem, byteOffset);
}
void
SResource::write(UNewDataMemory *mem, uint32_t *byteOffset) {
if (fWritten) {
assert(fRes != RES_BOGUS);
return;
}
handleWrite(mem, byteOffset);
uint8_t paddingSize = calcPadding(*byteOffset);
if (paddingSize > 0) {
udata_writePadding(mem, paddingSize);
*byteOffset += paddingSize;
}
fWritten = TRUE;
}
void
SResource::handleWrite(UNewDataMemory * /*mem*/, uint32_t * /*byteOffset*/) {
assert(FALSE);
}
void SRBRoot::write(const char *outputDir, const char *outputPkg,
char *writtenFilename, int writtenFilenameLen,
UErrorCode &errorCode) {
UNewDataMemory *mem = NULL;
uint32_t byteOffset = 0;
uint32_t top, size;
char dataName[1024];
int32_t indexes[URES_INDEX_TOP];
compactKeys(errorCode);
/*
* Add padding bytes to fKeys so that fKeysTop is 4-aligned.
* Safe because the capacity is a multiple of 4.
*/
while (fKeysTop & 3) {
fKeys[fKeysTop++] = (char)0xaa;
}
/*
* In URES_TABLE, use all local key offsets that fit into 16 bits,
* and use the remaining 16-bit offsets for pool key offsets
* if there are any.
* If there are no local keys, then use the whole 16-bit space
* for pool key offsets.
* Note: This cannot be changed without changing the major formatVersion.
*/
if (fKeysBottom < fKeysTop) {
if (fKeysTop <= 0x10000) {
fLocalKeyLimit = fKeysTop;
} else {
fLocalKeyLimit = 0x10000;
}
} else {
fLocalKeyLimit = 0;
}
UHashtable *stringSet;
if (gFormatVersion > 1) {
stringSet = uhash_open(string_hash, string_comp, string_comp, &errorCode);
if (U_SUCCESS(errorCode) &&
fUsePoolBundle != NULL && fUsePoolBundle->fStrings != NULL) {
for (SResource *current = fUsePoolBundle->fStrings->fFirst;
current != NULL;
current = current->fNext) {
StringResource *sr = static_cast<StringResource *>(current);
sr->fNumCopies = 0;
sr->fNumUnitsSaved = 0;
uhash_put(stringSet, sr, sr, &errorCode);
}
}
fRoot->preflightStrings(this, stringSet, errorCode);
} else {
stringSet = NULL;
}
if (fStringsForm == STRINGS_UTF16_V2 && f16BitStringsLength > 0) {
compactStringsV2(stringSet, errorCode);
}
uhash_close(stringSet);
if (U_FAILURE(errorCode)) {
return;
}
int32_t formatVersion = gFormatVersion;
if (fPoolStringIndexLimit != 0) {
int32_t sum = fPoolStringIndexLimit + fLocalStringIndexLimit;
if ((sum - 1) > RES_MAX_OFFSET) {
errorCode = U_BUFFER_OVERFLOW_ERROR;
return;
}
if (fPoolStringIndexLimit < 0x10000 && sum <= 0x10000) {
// 16-bit indexes work for all pool + local strings.
fPoolStringIndex16Limit = fPoolStringIndexLimit;
} else {
// Set the pool index threshold so that 16-bit indexes work
// for some pool strings and some local strings.
fPoolStringIndex16Limit = (int32_t)(
((int64_t)fPoolStringIndexLimit * 0xffff) / sum);
}
} else if (gIsDefaultFormatVersion && formatVersion == 3 && !fIsPoolBundle) {
// If we just default to formatVersion 3
// but there are no pool bundle strings to share
// and we do not write a pool bundle,
// then write formatVersion 2 which is just as good.
formatVersion = 2;
}
fRoot->write16(this);
if (f16BitUnits.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
if (f16BitUnits.length() & 1) {
f16BitUnits.append((UChar)0xaaaa); /* pad to multiple of 4 bytes */
}
byteOffset = fKeysTop + f16BitUnits.length() * 2;
fRoot->preWrite(&byteOffset);
/* total size including the root item */
top = byteOffset;
if (writtenFilename && writtenFilenameLen) {
*writtenFilename = 0;
}
if (writtenFilename) {
int32_t off = 0, len = 0;
if (outputDir) {
len = (int32_t)uprv_strlen(outputDir);
if (len > writtenFilenameLen) {
len = writtenFilenameLen;
}
uprv_strncpy(writtenFilename, outputDir, len);
}
if (writtenFilenameLen -= len) {
off += len;
writtenFilename[off] = U_FILE_SEP_CHAR;
if (--writtenFilenameLen) {
++off;
if(outputPkg != NULL)
{
uprv_strcpy(writtenFilename+off, outputPkg);
off += (int32_t)uprv_strlen(outputPkg);
writtenFilename[off] = '_';
++off;
}
len = (int32_t)uprv_strlen(fLocale);
if (len > writtenFilenameLen) {
len = writtenFilenameLen;
}
uprv_strncpy(writtenFilename + off, fLocale, len);
if (writtenFilenameLen -= len) {
off += len;
len = 5;
if (len > writtenFilenameLen) {
len = writtenFilenameLen;
}
uprv_strncpy(writtenFilename + off, ".res", len);
}
}
}
}
if(outputPkg)
{
uprv_strcpy(dataName, outputPkg);
uprv_strcat(dataName, "_");
uprv_strcat(dataName, fLocale);
}
else
{
uprv_strcpy(dataName, fLocale);
}
uprv_memcpy(dataInfo.formatVersion, gFormatVersions + formatVersion, sizeof(UVersionInfo));
mem = udata_create(outputDir, "res", dataName,
&dataInfo, (gIncludeCopyright==TRUE)? U_COPYRIGHT_STRING:NULL, &errorCode);
if(U_FAILURE(errorCode)){
return;
}
/* write the root item */
udata_write32(mem, fRoot->fRes);
/*
* formatVersion 1.1 (ICU 2.8):
* write int32_t indexes[] after root and before the key strings
* to make it easier to parse resource bundles in icuswap or from Java etc.
*/
uprv_memset(indexes, 0, sizeof(indexes));
indexes[URES_INDEX_LENGTH]= fIndexLength;
indexes[URES_INDEX_KEYS_TOP]= fKeysTop>>2;
indexes[URES_INDEX_RESOURCES_TOP]= (int32_t)(top>>2);
indexes[URES_INDEX_BUNDLE_TOP]= indexes[URES_INDEX_RESOURCES_TOP];
indexes[URES_INDEX_MAX_TABLE_LENGTH]= fMaxTableLength;
/*
* formatVersion 1.2 (ICU 3.6):
* write indexes[URES_INDEX_ATTRIBUTES] with URES_ATT_NO_FALLBACK set or not set
* the memset() above initialized all indexes[] to 0
*/
if (fNoFallback) {
indexes[URES_INDEX_ATTRIBUTES]=URES_ATT_NO_FALLBACK;
}
/*
* formatVersion 2.0 (ICU 4.4):
* more compact string value storage, optional pool bundle
*/
if (URES_INDEX_16BIT_TOP < fIndexLength) {
indexes[URES_INDEX_16BIT_TOP] = (fKeysTop>>2) + (f16BitUnits.length()>>1);
}
if (URES_INDEX_POOL_CHECKSUM < fIndexLength) {
if (fIsPoolBundle) {
indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_IS_POOL_BUNDLE | URES_ATT_NO_FALLBACK;
uint32_t checksum = computeCRC((const char *)(fKeys + fKeysBottom),
(uint32_t)(fKeysTop - fKeysBottom), 0);
if (f16BitUnits.length() <= 1) {
// no pool strings to checksum
} else if (U_IS_BIG_ENDIAN) {
checksum = computeCRC(reinterpret_cast<const char *>(f16BitUnits.getBuffer()),
(uint32_t)f16BitUnits.length() * 2, checksum);
} else {
// Swap to big-endian so we get the same checksum on all platforms
// (except for charset family, due to the key strings).
UnicodeString s(f16BitUnits);
assert(!s.isBogus());
// .getBuffer(capacity) returns a mutable buffer
char16_t* p = s.getBuffer(f16BitUnits.length());
for (int32_t count = f16BitUnits.length(); count > 0; --count) {
uint16_t x = *p;
*p++ = (uint16_t)((x << 8) | (x >> 8));
}
s.releaseBuffer(f16BitUnits.length());
checksum = computeCRC((const char *)s.getBuffer(),
(uint32_t)f16BitUnits.length() * 2, checksum);
}
indexes[URES_INDEX_POOL_CHECKSUM] = (int32_t)checksum;
} else if (gUsePoolBundle) {
indexes[URES_INDEX_ATTRIBUTES] |= URES_ATT_USES_POOL_BUNDLE;
indexes[URES_INDEX_POOL_CHECKSUM] = fUsePoolBundle->fChecksum;
}
}
// formatVersion 3 (ICU 56):
// share string values via pool bundle strings
indexes[URES_INDEX_LENGTH] |= fPoolStringIndexLimit << 8; // bits 23..0 -> 31..8
indexes[URES_INDEX_ATTRIBUTES] |= (fPoolStringIndexLimit >> 12) & 0xf000; // bits 27..24 -> 15..12
indexes[URES_INDEX_ATTRIBUTES] |= fPoolStringIndex16Limit << 16;
/* write the indexes[] */
udata_writeBlock(mem, indexes, fIndexLength*4);
/* write the table key strings */
udata_writeBlock(mem, fKeys+fKeysBottom,
fKeysTop-fKeysBottom);
/* write the v2 UTF-16 strings, URES_TABLE16 and URES_ARRAY16 */
udata_writeBlock(mem, f16BitUnits.getBuffer(), f16BitUnits.length()*2);
/* write all of the bundle contents: the root item and its children */
byteOffset = fKeysTop + f16BitUnits.length() * 2;
fRoot->write(mem, &byteOffset);
assert(byteOffset == top);
size = udata_finish(mem, &errorCode);
if(top != size) {
fprintf(stderr, "genrb error: wrote %u bytes but counted %u\n",
(int)size, (int)top);
errorCode = U_INTERNAL_PROGRAM_ERROR;
}
}
/* Opening Functions */
TableResource* table_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) {
LocalPointer<TableResource> res(new TableResource(bundle, tag, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
ArrayResource* array_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) {
LocalPointer<ArrayResource> res(new ArrayResource(bundle, tag, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
struct SResource *string_open(struct SRBRoot *bundle, const char *tag, const UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) {
LocalPointer<SResource> res(
new StringResource(bundle, tag, value, len, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
struct SResource *alias_open(struct SRBRoot *bundle, const char *tag, UChar *value, int32_t len, const struct UString* comment, UErrorCode *status) {
LocalPointer<SResource> res(
new AliasResource(bundle, tag, value, len, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
IntVectorResource *intvector_open(struct SRBRoot *bundle, const char *tag, const struct UString* comment, UErrorCode *status) {
LocalPointer<IntVectorResource> res(
new IntVectorResource(bundle, tag, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
struct SResource *int_open(struct SRBRoot *bundle, const char *tag, int32_t value, const struct UString* comment, UErrorCode *status) {
LocalPointer<SResource> res(new IntResource(bundle, tag, value, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
struct SResource *bin_open(struct SRBRoot *bundle, const char *tag, uint32_t length, uint8_t *data, const char* fileName, const struct UString* comment, UErrorCode *status) {
LocalPointer<SResource> res(
new BinaryResource(bundle, tag, length, data, fileName, comment, *status), *status);
return U_SUCCESS(*status) ? res.orphan() : NULL;
}
SRBRoot::SRBRoot(const UString *comment, UBool isPoolBundle, UErrorCode &errorCode)
: fRoot(NULL), fLocale(NULL), fIndexLength(0), fMaxTableLength(0), fNoFallback(FALSE),
fStringsForm(STRINGS_UTF16_V1), fIsPoolBundle(isPoolBundle),
fKeys(NULL), fKeyMap(NULL),
fKeysBottom(0), fKeysTop(0), fKeysCapacity(0),
fKeysCount(0), fLocalKeyLimit(0),
f16BitUnits(), f16BitStringsLength(0),
fUsePoolBundle(&kNoPoolBundle),
fPoolStringIndexLimit(0), fPoolStringIndex16Limit(0), fLocalStringIndexLimit(0),
fWritePoolBundle(NULL) {
if (U_FAILURE(errorCode)) {
return;
}
if (gFormatVersion > 1) {
// f16BitUnits must start with a zero for empty resources.
// We might be able to omit it if there are no empty 16-bit resources.
f16BitUnits.append((UChar)0);
}
fKeys = (char *) uprv_malloc(sizeof(char) * KEY_SPACE_SIZE);
if (isPoolBundle) {
fRoot = new PseudoListResource(this, errorCode);
} else {
fRoot = new TableResource(this, NULL, comment, errorCode);
}
if (fKeys == NULL || fRoot == NULL || U_FAILURE(errorCode)) {
if (U_SUCCESS(errorCode)) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
return;
}
fKeysCapacity = KEY_SPACE_SIZE;
/* formatVersion 1.1 and up: start fKeysTop after the root item and indexes[] */
if (gUsePoolBundle || isPoolBundle) {
fIndexLength = URES_INDEX_POOL_CHECKSUM + 1;
} else if (gFormatVersion >= 2) {
fIndexLength = URES_INDEX_16BIT_TOP + 1;
} else /* formatVersion 1 */ {
fIndexLength = URES_INDEX_ATTRIBUTES + 1;
}
fKeysBottom = (1 /* root */ + fIndexLength) * 4;
uprv_memset(fKeys, 0, fKeysBottom);
fKeysTop = fKeysBottom;
if (gFormatVersion == 1) {
fStringsForm = STRINGS_UTF16_V1;
} else {
fStringsForm = STRINGS_UTF16_V2;
}
}
/* Closing Functions */
void res_close(struct SResource *res) {
delete res;
}
SRBRoot::~SRBRoot() {
delete fRoot;
uprv_free(fLocale);
uprv_free(fKeys);
uprv_free(fKeyMap);
}
/* Misc Functions */
void SRBRoot::setLocale(UChar *locale, UErrorCode &errorCode) {
if(U_FAILURE(errorCode)) {
return;
}
uprv_free(fLocale);
fLocale = (char*) uprv_malloc(sizeof(char) * (u_strlen(locale)+1));
if(fLocale == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
u_UCharsToChars(locale, fLocale, u_strlen(locale)+1);
}
const char *
SRBRoot::getKeyString(int32_t key) const {
if (key < 0) {
return fUsePoolBundle->fKeys + (key & 0x7fffffff);
} else {
return fKeys + key;
}
}
const char *
SResource::getKeyString(const SRBRoot *bundle) const {
if (fKey == -1) {
return NULL;
}
return bundle->getKeyString(fKey);
}
const char *
SRBRoot::getKeyBytes(int32_t *pLength) const {
*pLength = fKeysTop - fKeysBottom;
return fKeys + fKeysBottom;
}
int32_t
SRBRoot::addKeyBytes(const char *keyBytes, int32_t length, UErrorCode &errorCode) {
int32_t keypos;
// It is not legal to add new key bytes after compactKeys is run!
U_ASSERT(fKeyMap == nullptr);
if (U_FAILURE(errorCode)) {
return -1;
}
if (length < 0 || (keyBytes == NULL && length != 0)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return -1;
}
if (length == 0) {
return fKeysTop;
}
keypos = fKeysTop;
fKeysTop += length;
if (fKeysTop >= fKeysCapacity) {
/* overflow - resize the keys buffer */
fKeysCapacity += KEY_SPACE_SIZE;
fKeys = static_cast<char *>(uprv_realloc(fKeys, fKeysCapacity));
if(fKeys == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return -1;
}
}
uprv_memcpy(fKeys + keypos, keyBytes, length);
return keypos;
}
int32_t
SRBRoot::addTag(const char *tag, UErrorCode &errorCode) {
int32_t keypos;
if (U_FAILURE(errorCode)) {
return -1;
}
if (tag == NULL) {
/* no error: the root table and array items have no keys */
return -1;
}
keypos = addKeyBytes(tag, (int32_t)(uprv_strlen(tag) + 1), errorCode);
if (U_SUCCESS(errorCode)) {
++fKeysCount;
}
return keypos;
}
static int32_t
compareInt32(int32_t lPos, int32_t rPos) {
/*
* Compare possibly-negative key offsets. Don't just return lPos - rPos
* because that is prone to negative-integer underflows.
*/
if (lPos < rPos) {
return -1;
} else if (lPos > rPos) {
return 1;
} else {
return 0;
}
}
static int32_t U_CALLCONV
compareKeySuffixes(const void *context, const void *l, const void *r) {
const struct SRBRoot *bundle=(const struct SRBRoot *)context;
int32_t lPos = ((const KeyMapEntry *)l)->oldpos;
int32_t rPos = ((const KeyMapEntry *)r)->oldpos;
const char *lStart = bundle->getKeyString(lPos);
const char *lLimit = lStart;
const char *rStart = bundle->getKeyString(rPos);
const char *rLimit = rStart;
int32_t diff;
while (*lLimit != 0) { ++lLimit; }
while (*rLimit != 0) { ++rLimit; }
/* compare keys in reverse character order */
while (lStart < lLimit && rStart < rLimit) {
diff = (int32_t)(uint8_t)*--lLimit - (int32_t)(uint8_t)*--rLimit;
if (diff != 0) {
return diff;
}
}
/* sort equal suffixes by descending key length */
diff = (int32_t)(rLimit - rStart) - (int32_t)(lLimit - lStart);
if (diff != 0) {
return diff;
}
/* Sort pool bundle keys first (negative oldpos), and otherwise keys in parsing order. */
return compareInt32(lPos, rPos);
}
static int32_t U_CALLCONV
compareKeyNewpos(const void * /*context*/, const void *l, const void *r) {
return compareInt32(((const KeyMapEntry *)l)->newpos, ((const KeyMapEntry *)r)->newpos);
}
static int32_t U_CALLCONV
compareKeyOldpos(const void * /*context*/, const void *l, const void *r) {
return compareInt32(((const KeyMapEntry *)l)->oldpos, ((const KeyMapEntry *)r)->oldpos);
}
void SResource::collectKeys(std::function<void(int32_t)> collector) const {
collector(fKey);
}
void ContainerResource::collectKeys(std::function<void(int32_t)> collector) const {
collector(fKey);
for (SResource* curr = fFirst; curr != NULL; curr = curr->fNext) {
curr->collectKeys(collector);
}
}
void
SRBRoot::compactKeys(UErrorCode &errorCode) {
KeyMapEntry *map;
char *keys;
int32_t i;
// Except for pool bundles, keys might not be used.
// Do not add unused keys to the final bundle.
std::set<int32_t> keysInUse;
if (!fIsPoolBundle) {
fRoot->collectKeys([&keysInUse](int32_t key) {
if (key >= 0) {
keysInUse.insert(key);
}
});
fKeysCount = static_cast<int32_t>(keysInUse.size());
}
int32_t keysCount = fUsePoolBundle->fKeysCount + fKeysCount;
if (U_FAILURE(errorCode) || fKeyMap != NULL) {
return;
}
map = (KeyMapEntry *)uprv_malloc(keysCount * sizeof(KeyMapEntry));
if (map == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
keys = (char *)fUsePoolBundle->fKeys;
for (i = 0; i < fUsePoolBundle->fKeysCount; ++i) {
map[i].oldpos =
(int32_t)(keys - fUsePoolBundle->fKeys) | 0x80000000; /* negative oldpos */
map[i].newpos = 0;
while (*keys != 0) { ++keys; } /* skip the key */
++keys; /* skip the NUL */
}
keys = fKeys + fKeysBottom;
while (i < keysCount) {
int32_t keyOffset = static_cast<int32_t>(keys - fKeys);
if (!fIsPoolBundle && keysInUse.count(keyOffset) == 0) {
// Mark the unused key as deleted
while (*keys != 0) { *keys++ = 1; }
*keys++ = 1;
} else {
map[i].oldpos = keyOffset;
map[i].newpos = 0;
while (*keys != 0) { ++keys; } /* skip the key */
++keys; /* skip the NUL */
i++;
}
}
if (keys != fKeys + fKeysTop) {
// Throw away any unused keys from the end
fKeysTop = static_cast<int32_t>(keys - fKeys);
}
/* Sort the keys so that each one is immediately followed by all of its suffixes. */
uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry),
compareKeySuffixes, this, FALSE, &errorCode);
/*
* Make suffixes point into earlier, longer strings that contain them
* and mark the old, now unused suffix bytes as deleted.
*/
if (U_SUCCESS(errorCode)) {
keys = fKeys;
for (i = 0; i < keysCount;) {
/*
* This key is not a suffix of the previous one;
* keep this one and delete the following ones that are
* suffixes of this one.
*/
const char *key;
const char *keyLimit;
int32_t j = i + 1;
map[i].newpos = map[i].oldpos;
if (j < keysCount && map[j].oldpos < 0) {
/* Key string from the pool bundle, do not delete. */
i = j;
continue;
}
key = getKeyString(map[i].oldpos);
for (keyLimit = key; *keyLimit != 0; ++keyLimit) {}
for (; j < keysCount && map[j].oldpos >= 0; ++j) {
const char *k;
char *suffix;
const char *suffixLimit;
int32_t offset;
suffix = keys + map[j].oldpos;
for (suffixLimit = suffix; *suffixLimit != 0; ++suffixLimit) {}
offset = static_cast<int32_t>((keyLimit - key) - (suffixLimit - suffix));
if (offset < 0) {
break; /* suffix cannot be longer than the original */
}
/* Is it a suffix of the earlier, longer key? */
for (k = keyLimit; suffix < suffixLimit && *--k == *--suffixLimit;) {}
if (suffix == suffixLimit && *k == *suffixLimit) {
map[j].newpos = map[i].oldpos + offset; /* yes, point to the earlier key */
// Mark the suffix as deleted
while (*suffix != 0) { *suffix++ = 1; }
*suffix = 1;
} else {
break; /* not a suffix, restart from here */
}
}
i = j;
}
/*
* Re-sort by newpos, then modify the key characters array in-place
* to squeeze out unused bytes, and readjust the newpos offsets.
*/
uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry),
compareKeyNewpos, NULL, FALSE, &errorCode);
if (U_SUCCESS(errorCode)) {
int32_t oldpos, newpos, limit;
oldpos = newpos = fKeysBottom;
limit = fKeysTop;
/* skip key offsets that point into the pool bundle rather than this new bundle */
for (i = 0; i < keysCount && map[i].newpos < 0; ++i) {}
if (i < keysCount) {
while (oldpos < limit) {
if (keys[oldpos] == 1) {
++oldpos; /* skip unused bytes */
} else {
/* adjust the new offsets for keys starting here */
while (i < keysCount && map[i].newpos == oldpos) {
map[i++].newpos = newpos;
}
/* move the key characters to their new position */
keys[newpos++] = keys[oldpos++];
}
}
U_ASSERT(i == keysCount);
}
fKeysTop = newpos;
/* Re-sort once more, by old offsets for binary searching. */
uprv_sortArray(map, keysCount, (int32_t)sizeof(KeyMapEntry),
compareKeyOldpos, NULL, FALSE, &errorCode);
if (U_SUCCESS(errorCode)) {
/* key size reduction by limit - newpos */
fKeyMap = map;
map = NULL;
}
}
}
uprv_free(map);
}
static int32_t U_CALLCONV
compareStringSuffixes(const void * /*context*/, const void *l, const void *r) {
const StringResource *left = *((const StringResource **)l);
const StringResource *right = *((const StringResource **)r);
const UChar *lStart = left->getBuffer();
const UChar *lLimit = lStart + left->length();
const UChar *rStart = right->getBuffer();
const UChar *rLimit = rStart + right->length();
int32_t diff;
/* compare keys in reverse character order */
while (lStart < lLimit && rStart < rLimit) {
diff = (int32_t)*--lLimit - (int32_t)*--rLimit;
if (diff != 0) {
return diff;
}
}
/* sort equal suffixes by descending string length */
return right->length() - left->length();
}
static int32_t U_CALLCONV
compareStringLengths(const void * /*context*/, const void *l, const void *r) {
const StringResource *left = *((const StringResource **)l);
const StringResource *right = *((const StringResource **)r);
int32_t diff;
/* Make "is suffix of another string" compare greater than a non-suffix. */
diff = (int)(left->fSame != NULL) - (int)(right->fSame != NULL);
if (diff != 0) {
return diff;
}
/* sort by ascending string length */
diff = left->length() - right->length();
if (diff != 0) {
return diff;
}
// sort by descending size reduction
diff = right->fNumUnitsSaved - left->fNumUnitsSaved;
if (diff != 0) {
return diff;
}
// sort lexically
return left->fString.compare(right->fString);
}
void
StringResource::writeUTF16v2(int32_t base, UnicodeString &dest) {
int32_t len = length();
fRes = URES_MAKE_RESOURCE(URES_STRING_V2, base + dest.length());
fWritten = TRUE;
switch(fNumCharsForLength) {
case 0:
break;
case 1:
dest.append((UChar)(0xdc00 + len));
break;
case 2:
dest.append((UChar)(0xdfef + (len >> 16)));
dest.append((UChar)len);
break;
case 3:
dest.append((UChar)0xdfff);
dest.append((UChar)(len >> 16));
dest.append((UChar)len);
break;
default:
break; /* will not occur */
}
dest.append(fString);
dest.append((UChar)0);
}
void
SRBRoot::compactStringsV2(UHashtable *stringSet, UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return;
}
// Store the StringResource pointers in an array for
// easy sorting and processing.
// We enumerate a set of strings, so there are no duplicates.
int32_t count = uhash_count(stringSet);
LocalArray<StringResource *> array(new StringResource *[count], errorCode);
if (U_FAILURE(errorCode)) {
return;
}
for (int32_t pos = UHASH_FIRST, i = 0; i < count; ++i) {
array[i] = (StringResource *)uhash_nextElement(stringSet, &pos)->key.pointer;
}
/* Sort the strings so that each one is immediately followed by all of its suffixes. */
uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **),
compareStringSuffixes, NULL, FALSE, &errorCode);
if (U_FAILURE(errorCode)) {
return;
}
/*
* Make suffixes point into earlier, longer strings that contain them.
* Temporarily use fSame and fSuffixOffset for suffix strings to
* refer to the remaining ones.
*/
for (int32_t i = 0; i < count;) {
/*
* This string is not a suffix of the previous one;
* write this one and subsume the following ones that are
* suffixes of this one.
*/
StringResource *res = array[i];
res->fNumUnitsSaved = (res->fNumCopies - 1) * res->get16BitStringsLength();
// Whole duplicates of pool strings are already account for in fPoolStringIndexLimit,
// see StringResource::handlePreflightStrings().
int32_t j;
for (j = i + 1; j < count; ++j) {
StringResource *suffixRes = array[j];
/* Is it a suffix of the earlier, longer string? */
if (res->fString.endsWith(suffixRes->fString)) {
assert(res->length() != suffixRes->length()); // Set strings are unique.
if (suffixRes->fWritten) {
// Pool string, skip.
} else if (suffixRes->fNumCharsForLength == 0) {
/* yes, point to the earlier string */
suffixRes->fSame = res;
suffixRes->fSuffixOffset = res->length() - suffixRes->length();
if (res->fWritten) {
// Suffix-share res which is a pool string.
// Compute the resource word and collect the maximum.
suffixRes->fRes =
res->fRes + res->fNumCharsForLength + suffixRes->fSuffixOffset;
int32_t poolStringIndex = (int32_t)RES_GET_OFFSET(suffixRes->fRes);
if (poolStringIndex >= fPoolStringIndexLimit) {
fPoolStringIndexLimit = poolStringIndex + 1;
}
suffixRes->fWritten = TRUE;
}
res->fNumUnitsSaved += suffixRes->fNumCopies * suffixRes->get16BitStringsLength();
} else {
/* write the suffix by itself if we need explicit length */
}
} else {
break; /* not a suffix, restart from here */
}
}
i = j;
}
/*
* Re-sort the strings by ascending length (except suffixes last)
* to optimize for URES_TABLE16 and URES_ARRAY16:
* Keep as many as possible within reach of 16-bit offsets.
*/
uprv_sortArray(array.getAlias(), count, (int32_t)sizeof(struct SResource **),
compareStringLengths, NULL, FALSE, &errorCode);
if (U_FAILURE(errorCode)) {
return;
}
if (fIsPoolBundle) {
// Write strings that are sufficiently shared.
// Avoid writing other strings.
int32_t numStringsWritten = 0;
int32_t numUnitsSaved = 0;
int32_t numUnitsNotSaved = 0;
for (int32_t i = 0; i < count; ++i) {
StringResource *res = array[i];
// Maximum pool string index when suffix-sharing the last character.
int32_t maxStringIndex =
f16BitUnits.length() + res->fNumCharsForLength + res->length() - 1;
if (res->fNumUnitsSaved >= GENRB_MIN_16BIT_UNITS_SAVED_FOR_POOL_STRING &&
maxStringIndex < RES_MAX_OFFSET) {
res->writeUTF16v2(0, f16BitUnits);
++numStringsWritten;
numUnitsSaved += res->fNumUnitsSaved;
} else {
numUnitsNotSaved += res->fNumUnitsSaved;
res->fRes = URES_MAKE_EMPTY_RESOURCE(URES_STRING);
res->fWritten = TRUE;
}
}
if (f16BitUnits.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
}
if (getShowWarning()) { // not quiet
printf("number of shared strings: %d\n", (int)numStringsWritten);
printf("16-bit units for strings: %6d = %6d bytes\n",
(int)f16BitUnits.length(), (int)f16BitUnits.length() * 2);
printf("16-bit units saved: %6d = %6d bytes\n",
(int)numUnitsSaved, (int)numUnitsSaved * 2);
printf("16-bit units not saved: %6d = %6d bytes\n",
(int)numUnitsNotSaved, (int)numUnitsNotSaved * 2);
}
} else {
assert(fPoolStringIndexLimit <= fUsePoolBundle->fStringIndexLimit);
/* Write the non-suffix strings. */
int32_t i;
for (i = 0; i < count && array[i]->fSame == NULL; ++i) {
StringResource *res = array[i];
if (!res->fWritten) {
int32_t localStringIndex = f16BitUnits.length();
if (localStringIndex >= fLocalStringIndexLimit) {
fLocalStringIndexLimit = localStringIndex + 1;
}
res->writeUTF16v2(fPoolStringIndexLimit, f16BitUnits);
}
}
if (f16BitUnits.isBogus()) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
return;
}
if (fWritePoolBundle != NULL && gFormatVersion >= 3) {
PseudoListResource *poolStrings =
static_cast<PseudoListResource *>(fWritePoolBundle->fRoot);
for (i = 0; i < count && array[i]->fSame == NULL; ++i) {
assert(!array[i]->fString.isEmpty());
StringResource *poolString =
new StringResource(fWritePoolBundle, array[i]->fString, errorCode);
if (poolString == NULL) {
errorCode = U_MEMORY_ALLOCATION_ERROR;
break;
}
poolStrings->add(poolString);
}
}
/* Write the suffix strings. Make each point to the real string. */
for (; i < count; ++i) {
StringResource *res = array[i];
if (res->fWritten) {
continue;
}
StringResource *same = res->fSame;
assert(res->length() != same->length()); // Set strings are unique.
res->fRes = same->fRes + same->fNumCharsForLength + res->fSuffixOffset;
int32_t localStringIndex = (int32_t)RES_GET_OFFSET(res->fRes) - fPoolStringIndexLimit;
// Suffixes of pool strings have been set already.
assert(localStringIndex >= 0);
if (localStringIndex >= fLocalStringIndexLimit) {
fLocalStringIndexLimit = localStringIndex + 1;
}
res->fWritten = TRUE;
}
}
// +1 to account for the initial zero in f16BitUnits
assert(f16BitUnits.length() <= (f16BitStringsLength + 1));
}
void SResource::applyFilter(
const PathFilter& /*filter*/,
ResKeyPath& /*path*/,
const SRBRoot* /*bundle*/) {
// Only a few resource types (tables) are capable of being filtered.
}
void TableResource::applyFilter(
const PathFilter& filter,
ResKeyPath& path,
const SRBRoot* bundle) {
SResource* prev = nullptr;
SResource* curr = fFirst;
for (; curr != nullptr;) {
path.push(curr->getKeyString(bundle));
auto inclusion = filter.match(path);
if (inclusion == PathFilter::EInclusion::INCLUDE) {
// Include whole subtree
// no-op
if (isVerbose()) {
std::cout << "genrb subtree: " << bundle->fLocale << ": INCLUDE: " << path << std::endl;
}
} else if (inclusion == PathFilter::EInclusion::EXCLUDE) {
// Reject the whole subtree
// Remove it from the linked list
if (isVerbose()) {
std::cout << "genrb subtree: " << bundle->fLocale << ": DELETE: " << path << std::endl;
}
if (prev == nullptr) {
fFirst = curr->fNext;
} else {
prev->fNext = curr->fNext;
}
fCount--;
delete curr;
curr = prev;
} else {
U_ASSERT(inclusion == PathFilter::EInclusion::PARTIAL);
// Recurse into the child
curr->applyFilter(filter, path, bundle);
}
path.pop();
prev = curr;
if (curr == nullptr) {
curr = fFirst;
} else {
curr = curr->fNext;
}
}
}
| [
"frank@lemanschik.com"
] | frank@lemanschik.com |
6856123cc74634670b2bb87fd3fe37e29004f840 | 48c2c911253fe6da02e3e2621484b41289cc4ba9 | /src/Field2.cpp | 5cb79881dcb72a1cef8cd78812e2c2fe69e158e4 | [] | no_license | nimadehmamy/Field_network | 0bc198785bea711f362dc932efbb49ea759de125 | 2be44a689a95c085ca98f8707214e805ee36ed48 | refs/heads/master | 2021-01-22T02:40:49.483887 | 2014-11-12T00:13:42 | 2014-11-12T00:13:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,133 | cpp | /*
* generate.cppx
*
* Created on: Dec 12, 2013
* Author: navid
*/
#include <iostream>
#include <cstdio>
#include "string.h"
#include <stdlib.h>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
double distance_squared(double x1, double y1, double x2, double y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
}
double distance2d(double x1, double y1, double x2, double y2) {
return sqrt(distance_squared(x1,y1,x2,y2));
}
double Green(double x1, double y1, double x2, double y2){
double r2 = distance_squared(x1,y1,x2,y2);
return exp(-r2*10);
}
/*instead of caluculating dx dy each time in weight2d,
we first calculate the matrix of all distances once and then access it to construct all the weights.
*/
void dists_to_hubs(double* X, double* Y,double* Xh, double* Yh, double* Dis2, int N, int N_hub) {
/*calculate all distances once, to reference later
*/
for (int i = 0; i < N ; i++) {
for (int j = 0; j < N_hub ; j++) {
Dis2[i*N_hub+j]=distance_squared(X[i],Y[i] , Xh[j], Yh[j]);
}
}
}
void Green1(double *Dist2, double *Grs , int N, int N_hub, double Dt){
/*
Calculates Green's function weights and returns them in Grs
*/
//double Dt;
//Dt=.01; //diffusion * time
for (int i=0; i< N*N_hub; i++){
Grs[i]=exp(-Dist2[i]/(4*Dt));
}
//return exp(-r2*10);
}
double weight_hub(double x, double y){
double r2 = distance_squared(x,y,0.0,0.0);
// return r^(-4)
return 1.0/r2/r2;
}
void weight_hub1(double *Xh, double *Yh, double *weights, int N_hub){
/* weights is an array of length N_hub which stores the weight of each hub.
*/
for (int i=0; i<N_hub; i++){
double r2 = distance_squared(Xh[i],Yh[i],0.0,0.0);
weights[i] =1.0/r2/r2;
}
}
double score2d(double xi, double yi, double xj,double yj, double *X_hub, double *Y_hub, int N_hub){
/*
input:
xi,yi,xj,yj: coordinates of two nodes
X_hub, Y_hub: pointer to the array of hub coordinates
N_hub: number of hubs
*/
double x,y;
double score = 0;
// Loop over all hubs
for (int counter_hub = 0; counter_hub < N_hub; counter_hub ++ ){
x = X_hub[counter_hub];
y = Y_hub[counter_hub];
score += Green(xi,yi,x,y) * Green(xj,yj,x,y) * weight_hub(x,y);
}
return score;
}
void get_point(double &x, double &y) {
double r = 1.0 * rand() / RAND_MAX;
double q = 1.0 * rand() / RAND_MAX;
x = r - 0.5;
y = q - 0.5;
}
void generate_hubs(double* X, double* Y, int N_hub){
for (int i = 0 ; i < N_hub; i++)
get_point(X[i],Y[i]);
}
void simulate2d(int id, int N, int N_hub) {
/*
Input:
id: the integer id of the current batch
N: number of nodes
alpha: blah blah
N_hub: number of hubs
*/
// X coordinates of the nodes
double X[N];
// y coordinates of the nodes
double Y[N];
double degree[N];
// X coordinates of the hubs
double X_hub[N_hub];
// y coordinates of the hubs
double Y_hub[N_hub];
// generate hubs
generate_hubs(X_hub, Y_hub, N_hub);
for (int i = 0; i < N; i++)
degree[i] = 0;
for (int i = 0; i < N; i++) {
get_point(X[i], Y[i]);
}
printf("Done getting points.\n");
double s;
//****************************
double *dist2;
dist2=(double *)malloc(N*N_hub*sizeof(double));// for distances to hubs
double *grs;
grs=(double *)malloc(N*N_hub*sizeof(double)); // for Green's functions to hubs
double *wgh;
wgh=(double *)malloc(N_hub*sizeof(double)); // for weights of hubs
double *wgh_Gr;
wgh_Gr=(double *)malloc(N_hub*sizeof(double)); // for weights multiplied by sum of Green's f's to get what needs to be multiplied into Gr to get degree
/* We want to calculate the weights for each time and form the network for each time
each gives us a degree contribution. The total degree comes from summing over time
The max time times diffusion constant "Dt" must be << size of space squared.
Here we discard points with r^2 > 0.1 Therefore max Dt <<.1
*/
printf("calculating distance^2 matrix...\n");
dists_to_hubs(X,Y, X_hub,Y_hub ,dist2, N, N_hub);
printf("distances to hubs computed.\n");
weight_hub1(X_hub,Y_hub, wgh, N_hub); // weights of hubs put in wgh
/* Now that we have Gr's and weights we can use them to calculate the degrees
*/
printf("Weights computed. Multiplying Greens...\n");
//double Dt=0.0001;
double inc=0.001;
double Dt_max=0.04;
ofstream f;
stringstream filename;
filename << "output/degrees-" << N << "-" << N_hub << ".txt";
// const char* filename = "degrees.txt";
cout << filename.str().c_str() << "\n";
if (id == 0)
f.open(filename.str().c_str());
else
f.open(filename.str().c_str(), std::fstream::app);
for (double Dt=0.0001; Dt< Dt_max; Dt+=inc){
Green1(dist2,grs,N, N_hub, Dt); // takes distances to hubs and puts Green's f's in grs
printf("Greens for Dt=%.4g computed.\n", Dt );
for (int j = 0; j < N_hub; j++) {
wgh_Gr[j]=0;
for (int i = 0; i < N; i++) {
wgh_Gr[j]+=wgh[j]*grs[i*N_hub+j]; // Greens * weights
}
}
/* The degrees are then the product of this and another Green's f summed over hubs
*/
printf("Greens multiplied. Calculating degrees...\n");
for (int i = 0; i < N ; i++) {
for (int j = 0; j < N_hub; j++) {
degree[i]+= grs[i*N_hub+j]*wgh_Gr[j];
}
}
}// Dt sum
for (int i = 0; i < N; i++) {
if (X[i] * X[i] + Y[i] * Y[i] < 0.1)
f << degree[i] << " " << X[i] << " " << Y[i] << '\n';
}
f.close();
}
//
void runBatch2D(int num_repeats, int N, int N_hub) {
for (int i = 0; i < num_repeats; i++){
cout<< "Simulating batch no "<< i << "\n";
simulate2d(i, N, N_hub);
}
}
int main(int argc, char *argv[]) {
srand (time(NULL)); // seed rand with time
/* default values */
int N = 1200;
int N_hub = 100;
/* process commandline arguments */
if (argc >= 3) {
N = atoi(argv[1]);
N_hub = atoi(argv[2]);
}
int batch=10;
if (argc==4){
batch= atoi(argv[3]);
}
runBatch2D(batch, N, N_hub);
}
| [
"nidami@gmail.com"
] | nidami@gmail.com |
90cf30ff292e8aaa41705979644a582774a7b490 | bff541a3925bb0cd5b43eaa238174135277b6b00 | /EventLog/EventLog.h | 157bc3e52713e93bc41cedac70c91d4f13d10125 | [] | no_license | bridadan/event-log-example | 9b456bd9e9e3cda124be33d4c7232ce1e657d3bc | 2383bc7e4a1f3c9fa996928f15664e408a9397ba | refs/heads/master | 2021-01-19T21:35:37.758054 | 2017-04-19T17:51:04 | 2017-04-19T17:51:04 | 88,670,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | h | #ifndef EVENT_LOG_H
#define EVENT_LOG_H
#include "EventLog/EventLogEvent.h"
#include <stdio.h>
#define EVENT_LOG_BUFFER_SIZE 64
class EventLog {
public:
enum LogState {
LOGGED_NO_TIME,
LOGGED_WITH_TIME,
SYNCED
};
// This assumes the filesystem is mounted and ready to go!
EventLog(const char* eventDir);
// Log the event to the filesystem
// Note: this is synchronous, so event must not go out of scope until the
// function returns
int log(EventLogEvent *event);
bool move(unsigned int eventId, LogState curState, LogState newState);
private:
const char* _eventDir;
unsigned int _lastEventId;
// TODO look at tuning these buffers or making them static
// All directories
char _logsNoTimeDir[EVENT_LOG_BUFFER_SIZE];
char _logsWithTimeDir[EVENT_LOG_BUFFER_SIZE];
char _syncedLogsDir[EVENT_LOG_BUFFER_SIZE];
// All files
char _lastEventIdFile[EVENT_LOG_BUFFER_SIZE];
// Starting from the last point in the log file, return an event
// The result will be placed in `event`
// Will return `true` if the log is unread
//bool _getEvent(Event *event);
bool _ensureDirectoryExists(const char* dir);
void _syncLastEventId();
const char* _getCorrectDirectory(LogState state);
};
#endif | [
"brianddaniels@gmail.com"
] | brianddaniels@gmail.com |
9a2032aa2c74ba69a362d7f2cc21929a54589bc8 | 23ae6999a16ce181e7c45e3e9d518923552ad4db | /image/image.cpp | d76d2b6ba61718d3361c6e5cb8d5e4a4b9d91b7b | [] | no_license | aalness/lfl | ce38d8019cdc7458de1e691d24df21df5842b4e4 | ce638b8cb10c556d34d66f0e128ee3d0666afb20 | refs/heads/master | 2021-01-21T23:33:53.955947 | 2015-05-05T00:17:36 | 2015-05-05T00:17:36 | 35,055,590 | 0 | 1 | null | 2015-05-04T19:45:23 | 2015-05-04T19:45:23 | null | UTF-8 | C++ | false | false | 12,000 | cpp | /*
* $Id: image.cpp 1336 2014-12-08 09:29:59Z justin $
* Copyright (C) 2009 Lucid Fusion Labs
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "lfapp/lfapp.h"
#include "lfapp/dom.h"
#include "lfapp/css.h"
#include "lfapp/flow.h"
#include "lfapp/gui.h"
namespace LFL {
DEFINE_string(output, "", "Output");
DEFINE_string(input, "", "Input");
DEFINE_bool(input_3D, false, "3d input");
DEFINE_float(input_scale, 0, "Input scale");
DEFINE_string(input_prims, "", "Comma separated list of .obj primitives to highlight");
DEFINE_string(input_filter, "", "Filter type [dark2alpha]");
DEFINE_bool(visualize, false, "Display");
DEFINE_string(shader, "", "Apply this shader");
DEFINE_string(make_png_atlas, "", "Build PNG atlas with files in directory");
DEFINE_int(make_png_atlas_size, 256, "Build PNG atlas with this size");
DEFINE_string(split_png_atlas, "", "Split PNG atlas back into individual files");
DEFINE_string(filter_png_atlas, "", "Filter PNG atlas");
AssetMap asset;
SoundAssetMap soundasset;
Scene scene;
Shader MyShader;
void DrawInput3D(Asset *a, Entity *e) {
if (!FLAGS_input_prims.empty() && a && a->geometry) {
vector<int> highlight_input_prims;
Split(FLAGS_input_prims, isint2<',', ' '>, &highlight_input_prims);
screen->gd->DisableLighting();
screen->gd->Color4f(1.0, 0.0, 0.0, 1.0);
int vpp = GraphicsDevice::VertsPerPrimitive(a->geometry->primtype);
for (auto i = highlight_input_prims.begin(); i != highlight_input_prims.end(); ++i) {
CHECK_LT(*i, a->geometry->count / vpp);
scene.Draw(a->geometry, e, *i * vpp, vpp);
}
screen->gd->Color4f(1.0, 1.0, 1.0, 1.0);
}
}
void Frame3D(LFL::Window *W, unsigned clicks, unsigned mic_samples, bool cam_sample, int flag) {
Asset *a = asset("input");
if (MyShader.ID) {
screen->gd->ActiveTexture(0);
screen->gd->BindTexture(GraphicsDevice::Texture2D, a->tex.ID);
screen->gd->UseShader(&MyShader);
// mandelbox params
float par[20][3] = { 0.25, -1.77 };
MyShader.SetUniform1f("xres", screen->width);
MyShader.SetUniform3fv("par", sizeofarray(par), &par[0][0]);
MyShader.SetUniform1f("fov_x", FLAGS_field_of_view);
MyShader.SetUniform1f("fov_y", FLAGS_field_of_view);
MyShader.SetUniform1f("min_dist", .000001);
MyShader.SetUniform1i("max_steps", 128);
MyShader.SetUniform1i("iters", 14);
MyShader.SetUniform1i("color_iters", 10);
MyShader.SetUniform1f("ao_eps", .0005);
MyShader.SetUniform1f("ao_strength", .1);
MyShader.SetUniform1f("glow_strength", .5);
MyShader.SetUniform1f("dist_to_color", .2);
MyShader.SetUniform1f("x_scale", 1);
MyShader.SetUniform1f("x_offset", 0);
MyShader.SetUniform1f("y_scale", 1);
MyShader.SetUniform1f("y_offset", 0);
v3 up = screen->cam->up, ort = screen->cam->ort, pos = screen->cam->pos;
v3 right = v3::Cross(ort, up);
float m[16] = { right.x, right.y, right.z, 0,
up.x, up.y, up.z, 0,
ort.x, ort.y, ort.z, 0,
pos.x, pos.y, pos.z, 0 };
screen->gd->LoadIdentity();
screen->gd->Mult(m);
glTimeResolutionShaderWindows(&MyShader, Color::black,
Box(-screen->width/2, -screen->height/2, screen->width, screen->height));
} else {
screen->cam->Look();
scene.Draw(&asset.vec);
}
}
void Frame2D(LFL::Window *W, unsigned clicks, unsigned mic_samples, bool cam_sample, int flag) {
Asset *a = asset("input");
if (MyShader.ID) {
screen->gd->ActiveTexture(0);
screen->gd->BindTexture(GraphicsDevice::Texture2D, a->tex.ID);
screen->gd->UseShader(&MyShader);
glTimeResolutionShaderWindows(&MyShader, Color::black, Box(screen->width, screen->height));
} else {
screen->gd->EnableLayering();
a->tex.Draw(screen->Box());
}
}
int Frame(LFL::Window *W, unsigned clicks, unsigned mic_samples, bool cam_sample, int flag) {
if (FLAGS_input_3D) Frame3D(W, clicks, mic_samples, cam_sample, flag);
screen->gd->DrawMode(DrawMode::_2D);
if (!FLAGS_input_3D) Frame2D(W, clicks, mic_samples, cam_sample, flag);
screen->DrawDialogs();
return 0;
}
}; // namespace LFL
using namespace LFL;
extern "C" int main(int argc, const char *argv[]) {
app->logfilename = StrCat(LFAppDownloadDir(), "image.txt");
screen->frame_cb = Frame;
screen->width = 420;
screen->height = 380;
screen->caption = "Image";
FLAGS_near_plane = 0.1;
FLAGS_lfapp_video = FLAGS_lfapp_input = true;
if (app->Create(argc, argv, __FILE__)) { app->Free(); return -1; }
if (app->Init()) { app->Free(); return -1; }
// asset.Add(Asset(name, texture, scale, translate, rotate, geometry, 0, 0, 0));
asset.Add(Asset("axis", "", 0, 0, 0, 0, 0, 0, 0, Asset::DrawCB(bind(&glAxis, _1, _2))));
asset.Add(Asset("grid", "", 0, 0, 0, Grid::Grid3D(), 0, 0, 0));
asset.Add(Asset("input", "", 0, 0, 0, 0, 0, 0, 0));
asset.Load();
app->shell.assets = &asset;
// soundasset.Add(SoundAsset(name, filename, ringbuf, channels, sample_rate, seconds));
soundasset.Add(SoundAsset("draw", "Draw.wav", 0, 0, 0, 0 ));
soundasset.Load();
app->shell.soundassets = &soundasset;
BindMap *binds = screen->binds = new BindMap();
// binds->Add(Bind(key, callback));
binds->Add(Bind(Key::Backquote, Bind::CB(bind([&](){ screen->console->Toggle(); }))));
binds->Add(Bind(Key::Quote, Bind::CB(bind([&](){ screen->console->Toggle(); }))));
binds->Add(Bind(Key::Escape, Bind::CB(bind(&Shell::quit, &app->shell, vector<string>()))));
binds->Add(Bind(Key::Return, Bind::CB(bind(&Shell::grabmode, &app->shell, vector<string>()))));
binds->Add(Bind(Key::LeftShift, Bind::TimeCB(bind(&Entity::RollLeft, screen->cam, _1))));
binds->Add(Bind(Key::Space, Bind::TimeCB(bind(&Entity::RollRight, screen->cam, _1))));
binds->Add(Bind('w', Bind::TimeCB(bind(&Entity::MoveFwd, screen->cam, _1))));
binds->Add(Bind('s', Bind::TimeCB(bind(&Entity::MoveRev, screen->cam, _1))));
binds->Add(Bind('a', Bind::TimeCB(bind(&Entity::MoveLeft, screen->cam, _1))));
binds->Add(Bind('d', Bind::TimeCB(bind(&Entity::MoveRight, screen->cam, _1))));
binds->Add(Bind('q', Bind::TimeCB(bind(&Entity::MoveDown, screen->cam, _1))));
binds->Add(Bind('e', Bind::TimeCB(bind(&Entity::MoveUp, screen->cam, _1))));
if (!FLAGS_make_png_atlas.empty()) {
FLAGS_atlas_dump=1;
vector<string> png;
DirectoryIter d(FLAGS_make_png_atlas, 0, 0, ".png");
for (const char *fn = d.Next(); fn; fn = d.Next()) png.push_back(FLAGS_make_png_atlas + fn);
AtlasFontEngine::MakeFromPNGFiles("png_atlas", png, FLAGS_make_png_atlas_size, NULL);
}
if (!FLAGS_split_png_atlas.empty()) {
Singleton<AtlasFontEngine>::Get()->Init(FontDesc(FLAGS_split_png_atlas, "", 0, Color::black));
Font *font = Fonts::Get(FLAGS_split_png_atlas, "", 0, Color::black);
CHECK(font);
map<v4, int> glyph_index;
for (int i = 255; i >= 0; i--) {
if (!font->glyph->table[i].tex.width && !font->glyph->table[i].tex.height) continue;
glyph_index[v4(font->glyph->table[i].tex.coord)] = i;
}
map<int, v4> glyphs;
for (map<v4, int>::const_iterator i = glyph_index.begin(); i != glyph_index.end(); ++i) glyphs[i->second] = i->first;
string outdir = StrCat(app->assetdir, FLAGS_split_png_atlas);
LocalFile::mkdir(outdir, 0755);
string atlas_png_fn = StrCat(app->assetdir, FLAGS_split_png_atlas, "0,0,0,0,0", "00.png");
AtlasFontEngine::SplitIntoPNGFiles(atlas_png_fn, glyphs, outdir + LocalFile::Slash);
}
if (!FLAGS_filter_png_atlas.empty()) {
if (Font *f = AtlasFontEngine::OpenAtlas(FontDesc(FLAGS_filter_png_atlas, "", 0, Color::white))) {
AtlasFontEngine::WriteGlyphFile(FLAGS_filter_png_atlas, f);
INFO("filtered ", FLAGS_filter_png_atlas);
}
}
if (FLAGS_input.empty()) FATAL("no input supplied");
Asset *asset_input = asset("input");
if (!FLAGS_shader.empty()) {
string vertex_shader = LocalFile::FileContents(StrCat(app->assetdir, FLAGS_input_3D ? "" : "lfapp_", "vertex.glsl"));
string fragment_shader = LocalFile::FileContents(FLAGS_shader);
Shader::Create("my_shader", vertex_shader, fragment_shader, ShaderDefines(0,0,1,0), &MyShader);
}
if (SuffixMatch(FLAGS_input, ".obj", false)) {
FLAGS_input_3D = true;
asset_input->cb = bind(&DrawInput3D, _1, _2);
asset_input->scale = FLAGS_input_scale;
asset_input->geometry = Geometry::LoadOBJ(FLAGS_input);
scene.Add(new Entity("axis", asset("axis")));
scene.Add(new Entity("grid", asset("grid")));
scene.Add(new Entity("input", asset_input));
if (!FLAGS_output.empty()) {
set<int> filter_prims;
bool filter_invert = FLAGS_input_filter == "notprims", filter = false;
if (filter_invert || FLAGS_input_filter == "prims") filter = true;
if (filter) Split(FLAGS_input_prims, isint2<',', ' '>, &filter_prims);
string out = Geometry::ExportOBJ(asset_input->geometry, filter ? &filter_prims : 0, filter_invert);
int ret = LocalFile::WriteFile(FLAGS_output, out);
INFO("write ", FLAGS_output, " = ", ret);
}
} else {
FLAGS_draw_grid = true;
Texture pb;
app->assets.default_video_loader->LoadVideo
(app->assets.default_video_loader->LoadVideoFile(FLAGS_input), &asset_input->tex, false);
pb.AssignBuffer(&asset_input->tex, true);
if (pb.width && pb.height) screen->Reshape(FLAGS_input_scale ? pb.width *FLAGS_input_scale : pb.width,
FLAGS_input_scale ? pb.height*FLAGS_input_scale : pb.height);
INFO("input dim = (", pb.width, ", ", pb.height, ") pf=", pb.pf);
if (FLAGS_input_filter == "dark2alpha") {
for (int i=0; i<pb.height; i++)
for (int j=0; j<pb.width; j++) {
int ind = (i*pb.width + j) * Pixel::size(pb.pf);
unsigned char *b = pb.buf + ind;
float dark = b[0]; // + b[1] + b[2] / 3.0;
// if (dark < 256*1/3.0) b[3] = 0;
b[3] = dark;
}
}
if (!FLAGS_output.empty()) {
int ret = PngWriter::Write(FLAGS_output, pb);
INFO("write ", FLAGS_output, " = ", ret);
}
}
if (!FLAGS_visualize) return 0;
// start our engine
return app->Main();
}
| [
"koldfuzor@users.noreply.github.com"
] | koldfuzor@users.noreply.github.com |
6648f0219aecec8622155899cca99f5d7490024b | 6cbb6558c1f4e87cc97162aa9caf6d2fdeb99369 | /Project/SDL2_Engine/SDL2_Engine/MainScene.cpp | 00318403baf138fcc904614bc8d95d64c04fb364 | [] | no_license | M2vH/GPA4300_0318 | 67b0c94c7e1a60577f37da41514f6d65a1839a68 | 38c579edc49148cde57441f637965824eb4ccae8 | refs/heads/develop | 2020-03-22T19:57:03.235115 | 2018-07-28T09:39:29 | 2018-07-28T09:39:29 | 138,725,217 | 1 | 0 | null | 2018-07-10T11:46:49 | 2018-06-26T10:56:24 | C | UTF-8 | C++ | false | false | 438 | cpp | #pragma region project include
#include "MainScene.h"
#include "World.h"
#include "ContentManagement.h"
#pragma endregion
#pragma region public override function
// initialize scene
void GMainScene::Init()
{
// create world
m_pWorld = new GWorld(CEngine::Get()->GetRenderer(), "Texture/World/T_WorldSide.png");
m_pWorld->Init();
}
// cleaning up scene
void GMainScene::Clean()
{
// delete world
delete m_pWorld;
}
#pragma endregion | [
"marc.friedrich@nyfa.edu"
] | marc.friedrich@nyfa.edu |
1606e7e983b4b60d73a6f3440e2a561af38f84b5 | b8497ccf4a134968985b19ccaf125a1a323af8e0 | /include/point_location/walking/walking_point_location.h | d7b2c1b2fc08d76efbc38a1c4166c1a2cb48e91f | [] | no_license | s-nandi/point-location-2d | 38f7d910246d2ecdc104840e4f7588785008b0cc | 12f5a047b2ecdf15b6bda5dc7d62927a8b6d1a9e | refs/heads/master | 2023-03-05T02:09:38.175170 | 2019-03-29T21:28:04 | 2019-03-29T21:28:04 | 177,846,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | h | #ifndef WALKING_POINT_LOCATION_H
#define WALKING_POINT_LOCATION_H
#include "point_location/point_location.h"
#include "point_location/walking/starting_edge_selector.h"
#include <memory>
class walking_point_location : public online_point_location
{
private:
std::unique_ptr <walking_scheme> locator;
std::unique_ptr <starting_edge_selector> selector;
public:
walking_point_location(std::unique_ptr<walking_scheme>&, std::unique_ptr<starting_edge_selector>&);
void init(plane&);
void addEdge(edge*);
void removeEdge(edge*);
edge* locate(point);
};
#endif
| [
"saujas.nandi@gmail.com"
] | saujas.nandi@gmail.com |
cca0b48ea2cbe082d72fdd77b9700e5913ce7b71 | 6581ff32670e4b30dd17c781975c95eac2153ebc | /artifacts/linux/include/unicode/enumset.h | 9c15b9a967529c61d01a6f394c39c42c75ff398c | [
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows"
] | permissive | pxscene/Spark-Externals | 6f3a16bafae1d89015f635b1ad1aa2efe342a001 | 92501a5d10c2a167bac07915eb9c078dc9aab158 | refs/heads/master | 2023-01-22T12:48:39.455338 | 2020-05-01T14:19:54 | 2020-05-01T14:19:54 | 205,173,203 | 1 | 35 | Apache-2.0 | 2023-01-07T09:41:55 | 2019-08-29T13:43:36 | C | UTF-8 | C++ | false | false | 2,115 | h | // Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
* Copyright (C) 2012,2014 International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*/
/**
* \file
* \brief C++: internal template EnumSet<>
*/
#ifndef ENUMSET_H
#define ENUMSET_H
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/* Can't use #ifndef U_HIDE_INTERNAL_API for the entire EnumSet class, needed in .h file declarations */
/**
* enum bitset for boolean fields. Similar to Java EnumSet<>.
* Needs to range check. Used for private instance variables.
* @internal
*/
template<typename T, uint32_t minValue, uint32_t limitValue>
class EnumSet {
public:
inline EnumSet() : fBools(0) {}
inline EnumSet(const EnumSet<T,minValue,limitValue>& other) : fBools(other.fBools) {}
inline ~EnumSet() {}
#ifndef U_HIDE_INTERNAL_API
inline void clear() { fBools=0; }
inline void add(T toAdd) { set(toAdd, 1); }
inline void remove(T toRemove) { set(toRemove, 0); }
inline int32_t contains(T toCheck) const { return get(toCheck); }
inline void set(T toSet, int32_t v) { fBools=(fBools&(~flag(toSet)))|(v?(flag(toSet)):0); }
inline int32_t get(T toCheck) const { return (fBools & flag(toCheck))?1:0; }
inline UBool isValidEnum(T toCheck) const { return (toCheck>=minValue&&toCheck<limitValue); }
inline UBool isValidValue(int32_t v) const { return (v==0||v==1); }
inline const EnumSet<T,minValue,limitValue>& operator=(const EnumSet<T,minValue,limitValue>& other) {
fBools = other.fBools;
return *this;
}
inline uint32_t getAll() const {
return fBools;
}
#endif /* U_HIDE_INTERNAL_API */
private:
inline uint32_t flag(T toCheck) const { return (1<<(toCheck-minValue)); }
private:
uint32_t fBools;
};
U_NAMESPACE_END
#endif /* U_SHOW_CPLUSPLUS_API */
#endif /* ENUMSET_H */
| [
"travis@example.org"
] | travis@example.org |
271513ff81e818fb04260ef76041342fd4ab4a72 | c3e1fce7a720bb66a3814123727b6f835b54c8fd | /src/OGLSamples_GTruc/external/glm-0.9.5.B/test/core/core_type_cast.cpp | cc5c600cc6dafb70518848f3376ac02c8e72f907 | [
"MIT"
] | permissive | isabella232/vogl | 6df37b32eb5c484a461b50eb50b75f2a95ffb733 | 172a86d9c4ee08dccbf4e342caa1ba63f1ea2b0e | refs/heads/master | 2022-04-18T21:11:14.760227 | 2014-03-14T21:55:20 | 2014-03-14T21:55:20 | 482,027,147 | 0 | 0 | MIT | 2022-04-16T02:59:09 | 2022-04-15T16:59:45 | null | UTF-8 | C++ | false | false | 2,480 | cpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2013-05-06
// Updated : 2013-05-06
// Licence : This source is under MIT License
// File : test/core/type_cast.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <glm/glm.hpp>
struct my_vec2
{
operator glm::vec2() { return glm::vec2(x, y); }
float x, y;
};
int test_vec2_cast()
{
glm::vec2 A(1.0f, 2.0f);
glm::lowp_vec2 B(A);
glm::mediump_vec2 C(A);
glm::highp_vec2 D(A);
glm::vec2 E = static_cast<glm::vec2>(A);
glm::lowp_vec2 F = static_cast<glm::lowp_vec2>(A);
glm::mediump_vec2 G = static_cast<glm::mediump_vec2>(A);
glm::highp_vec2 H = static_cast<glm::highp_vec2>(A);
//my_vec2 I;
//glm::vec2 J = static_cast<glm::vec2>(I);
int Error(0);
Error += glm::all(glm::equal(A, E)) ? 0 : 1;
Error += glm::all(glm::equal(B, F)) ? 0 : 1;
Error += glm::all(glm::equal(C, G)) ? 0 : 1;
Error += glm::all(glm::equal(D, H)) ? 0 : 1;
return Error;
}
int test_vec3_cast()
{
glm::vec3 A(1.0f, 2.0f, 3.0f);
glm::lowp_vec3 B(A);
glm::mediump_vec3 C(A);
glm::highp_vec3 D(A);
glm::vec3 E = static_cast<glm::vec3>(A);
glm::lowp_vec3 F = static_cast<glm::lowp_vec3>(A);
glm::mediump_vec3 G = static_cast<glm::mediump_vec3>(A);
glm::highp_vec3 H = static_cast<glm::highp_vec3>(A);
int Error(0);
Error += glm::all(glm::equal(A, E)) ? 0 : 1;
Error += glm::all(glm::equal(B, F)) ? 0 : 1;
Error += glm::all(glm::equal(C, G)) ? 0 : 1;
Error += glm::all(glm::equal(D, H)) ? 0 : 1;
return Error;
}
int test_vec4_cast()
{
glm::vec4 A(1.0f, 2.0f, 3.0f, 4.0f);
glm::lowp_vec4 B(A);
glm::mediump_vec4 C(A);
glm::highp_vec4 D(A);
glm::vec4 E = static_cast<glm::vec4>(A);
glm::lowp_vec4 F = static_cast<glm::lowp_vec4>(A);
glm::mediump_vec4 G = static_cast<glm::mediump_vec4>(A);
glm::highp_vec4 H = static_cast<glm::highp_vec4>(A);
int Error(0);
Error += glm::all(glm::equal(A, E)) ? 0 : 1;
Error += glm::all(glm::equal(B, F)) ? 0 : 1;
Error += glm::all(glm::equal(C, G)) ? 0 : 1;
Error += glm::all(glm::equal(D, H)) ? 0 : 1;
return Error;
}
int main()
{
int Error = 0;
Error += test_vec2_cast();
Error += test_vec3_cast();
Error += test_vec4_cast();
return Error;
}
| [
"mikesart@gmail.com"
] | mikesart@gmail.com |
9dfa6ee906d003b67305d9663874f6a95b6a7e14 | ab4156ca699182a749105ece73d26ecd66f4ff1d | /tests/test_threads_wait_queue.cpp | 2d381dc5946cefb2cee55e621240d090cc9ed2e6 | [
"MIT"
] | permissive | firebirdtools/CppCommon | 4c6057224f46c798960bf7d6751e5fff63afca58 | ad96c6739da0cb2c5b7144b2ff5e66249c9eb462 | refs/heads/master | 2020-04-13T19:56:52.219898 | 2018-12-21T19:51:31 | 2018-12-21T19:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,296 | cpp | //
// Created by Ivan Shynkarenka on 05.10.2016
//
#include "test.h"
#include "threads/wait_queue.h"
#include <thread>
using namespace CppCommon;
TEST_CASE("Multiple producers / multiple consumers wait queue", "[CppCommon][Threads]")
{
WaitQueue<int> queue;
REQUIRE(!queue.closed());
REQUIRE(queue.size() == 0);
int v = -1;
REQUIRE((queue.Enqueue(0) && (queue.size() == 1)));
REQUIRE((queue.Enqueue(1) && (queue.size() == 2)));
REQUIRE((queue.Enqueue(2) && (queue.size() == 3)));
REQUIRE(((queue.Dequeue(v) && (v == 0)) && (queue.size() == 2)));
REQUIRE(((queue.Dequeue(v) && (v == 1)) && (queue.size() == 1)));
REQUIRE((queue.Enqueue(3) && (queue.size() == 2)));
REQUIRE((queue.Enqueue(4) && (queue.size() == 3)));
REQUIRE(((queue.Dequeue(v) && (v == 2)) && (queue.size() == 2)));
REQUIRE(((queue.Dequeue(v) && (v == 3)) && (queue.size() == 1)));
REQUIRE(((queue.Dequeue(v) && (v == 4)) && (queue.size() == 0)));
REQUIRE((queue.Enqueue(5) && (queue.size() == 1)));
REQUIRE(((queue.Dequeue(v) && (v == 5)) && (queue.size() == 0)));
queue.Close();
REQUIRE(queue.closed());
REQUIRE(queue.size() == 0);
}
TEST_CASE("Multiple producers / multiple consumers wait queue threads", "[CppCommon][Threads]")
{
int items_to_produce = 10000;
int producers_count = 4;
int crc = 0;
WaitQueue<int> queue;
// Calculate result value
int result = 0;
for (int i = 0; i < items_to_produce; ++i)
result += i;
// Start producers threads
std::vector<std::thread> producers;
for (int producer = 0; producer < producers_count; ++producer)
{
producers.emplace_back([&queue, producer, items_to_produce, producers_count]()
{
int items = (items_to_produce / producers_count);
for (int i = 0; i < items; ++i)
if (!queue.Enqueue((producer * items) + i))
break;
});
}
// Consume items
for (int i = 0; i < items_to_produce; ++i)
{
int item;
if (!queue.Dequeue(item))
break;
crc += item;
}
// Wait for all producers threads
for (auto& producer : producers)
producer.join();
// Check result
REQUIRE(crc == result);
}
| [
"chronoxor@gmail.com"
] | chronoxor@gmail.com |
ea0b6d307bb05004a567784da859c97c6be0095f | ed68de35cc94bb7ee0680d7b523157f9afad85e3 | /tests/ubo-test.cc | b2676a3a379458cbbd03ec65de5035979ba13d61 | [
"MIT"
] | permissive | danem/SimpleGL | 7b4f2ba740504b76c59db58c23b9679577b305f3 | aa9e1a1b5ac8de0a294b5e1f3e3146aec4de4251 | refs/heads/master | 2021-06-20T03:47:22.301964 | 2019-04-15T22:03:23 | 2019-04-15T22:03:23 | 104,854,029 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cc | #include <SimpleGL/helpers/SimpleGLHelpers.h>
#include "sgl-test.h"
struct UBOData {
int x;
int y;
int z;
};
int main () {
sgl::Context ctx{500, 500, "ubo test"};
UBOData data;
sgl::UniformBuffer<UBOData> ubo{&data, 1};
sgl::Shader uboShader = sgl::loadShader(TEST_RES("ubo_vs.glsl"), TEST_RES("ubo_fs.glsl"));
sgl::MeshResource plane = sgl::createPlane();
glViewport(0, 0, ctx.attrs.width, ctx.attrs.height);
int frame = 0;
while (ctx.isAlive()){
ctx.pollEvents();
glClear(GL_COLOR_BUFFER_BIT);
{
data.x = data.y = data.z = frame;
auto bv = sgl::buffer_view<UBOData>(ubo, GL_WRITE_ONLY);
bv = data;
frame += 1;
}
auto sg = sgl::bind_guard(uboShader);
auto mg = sgl::bind_guard(plane);
ctx.swapBuffers();
}
}
| [
""
] | |
b38b75b44a9da2a6d45ff9b73a6291f9b995f3be | 0f0b2c5e9095ba273992ab0b74a82f986b4f941e | /opengl/tools/glgen/stubs/gles11/glGetProgramPipelineInfoLog.cpp | 5b556d5d82a5ab0db09a23c368935695535d0a8d | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | LineageOS/android_frameworks_native | 28274a8a6a3d2b16150702e0a34434bc45090b9a | c25b27db855a0a6d749bfd45d05322939d2ad39a | refs/heads/lineage-18.1 | 2023-08-04T11:18:47.942921 | 2023-05-05T12:54:26 | 2023-05-05T12:54:26 | 75,639,913 | 21 | 626 | NOASSERTION | 2021-06-11T19:11:21 | 2016-12-05T15:41:33 | C++ | UTF-8 | C++ | false | false | 688 | cpp | #include <stdlib.h>
/* void glGetProgramPipelineInfoLog ( GLuint shader, GLsizei maxLength, GLsizei* length, GLchar* infoLog ) */
static jstring android_glGetProgramPipelineInfoLog(JNIEnv *_env, jobject, jint shader) {
GLint infoLen = 0;
glGetProgramPipelineiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (!infoLen) {
return _env->NewStringUTF("");
}
char* buf = (char*) malloc(infoLen);
if (buf == NULL) {
jniThrowException(_env, "java/lang/OutOfMemoryError", "out of memory");
return NULL;
}
glGetProgramPipelineInfoLog(shader, infoLen, NULL, buf);
jstring result = _env->NewStringUTF(buf);
free(buf);
return result;
}
| [
"jessehall@google.com"
] | jessehall@google.com |
caf61d26b179a24608029f7b21121970cc509d8b | e71cf8bc0077df065f7778d19a3be85e4a894776 | /coderushdiv2_4.cpp | 0b6268d04a1f1814568613b66d7afdca0fa583e8 | [] | no_license | NishantRaj/program_files | c33ac91523a65dc6a1af7cdc35e6c18e969b10f3 | 934a9f1dcdbc2851c50f36e0f33c4e08d214e2e7 | refs/heads/master | 2021-01-21T04:54:46.691639 | 2019-05-11T09:22:25 | 2019-05-11T09:22:25 | 39,347,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | #include <bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long
ULL solve(int a,ULL sum)
{
ULL d = (ULL)sqrt(a*a + 8*a*sum);
d-=a;
return d / (2*a);
}
ULL calculate(ULL a[], ULL t , int sz)
{
ULL total = 0;
for(int i = 0 ; i < sz ; i++)
total += solve(a[i], t);
return total;
}
ULL b_search(ULL a[] , ULL b[], LL t ,int sa, int sc)
{
ULL low = 1 , high = t , mid , lhalf = 0 , rhalf , ma = 0 , m2;
while(low < high)
{
mid = (low + high)>>1;
lhalf = calculate(a,mid,sa);
rhalf = calculate(b,t - mid , sc);
if(lhalf <= rhalf){
low = mid + 1;
ma = max(lhalf , ma);
}
else if(lhalf > rhalf)
high = mid;
}
return ma;
}
int main()
{
int t;
cin>>t;
while(t--)
{
ULL p , n , m ;
cin>>p;
cin>>n>>m;
ULL a[n+9];
for(int i = 0 ; i < n ; i ++)
cin>>a[i];
ULL b[m+9];
for(int i = 0 ; i < m ; i++)
cin>>b[i];
cout<<b_search(a,b,p,n,m)<<endl;
}
return 0;
} | [
"raj.nishant360@gmail.com"
] | raj.nishant360@gmail.com |
6dd9d60635f29c7d8fa212430ae59e11368fef65 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/Source/core/svg/SVGPathBlender.cpp | bf5d68aa695e7bdaba3cc4cfde6ef0fda33127b6 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 12,092 | cpp | /*
* Copyright (C) Research In Motion Limited 2010, 2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/svg/SVGPathBlender.h"
#include "core/svg/SVGPathByteStreamSource.h"
#include "core/svg/SVGPathConsumer.h"
#include "core/svg/SVGPathData.h"
#include "platform/animation/AnimationUtilities.h"
namespace blink {
enum FloatBlendMode { kBlendHorizontal, kBlendVertical };
class SVGPathBlender::BlendState {
public:
BlendState(float progress, unsigned add_types_count = 0)
: progress_(progress),
add_types_count_(add_types_count),
is_in_first_half_of_animation_(progress < 0.5f),
types_are_equal_(false),
from_is_absolute_(false) {}
bool BlendSegments(const PathSegmentData& from_seg,
const PathSegmentData& to_seg,
PathSegmentData&);
private:
float BlendAnimatedDimensonalFloat(float, float, FloatBlendMode);
FloatPoint BlendAnimatedFloatPointSameCoordinates(const FloatPoint& from,
const FloatPoint& to);
FloatPoint BlendAnimatedFloatPoint(const FloatPoint& from,
const FloatPoint& to);
bool CanBlend(const PathSegmentData& from_seg, const PathSegmentData& to_seg);
FloatPoint from_sub_path_point_;
FloatPoint from_current_point_;
FloatPoint to_sub_path_point_;
FloatPoint to_current_point_;
float progress_;
unsigned add_types_count_;
bool is_in_first_half_of_animation_;
// This is per-segment blend state corresponding to the 'from' and 'to'
// segments currently being blended, and only used within blendSegments().
bool types_are_equal_;
bool from_is_absolute_;
};
// Helper functions
static inline FloatPoint BlendFloatPoint(const FloatPoint& a,
const FloatPoint& b,
float progress) {
return FloatPoint(Blend(a.X(), b.X(), progress),
Blend(a.Y(), b.Y(), progress));
}
float SVGPathBlender::BlendState::BlendAnimatedDimensonalFloat(
float from,
float to,
FloatBlendMode blend_mode) {
if (add_types_count_) {
DCHECK(types_are_equal_);
return from + to * add_types_count_;
}
if (types_are_equal_)
return Blend(from, to, progress_);
float from_value = blend_mode == kBlendHorizontal ? from_current_point_.X()
: from_current_point_.Y();
float to_value = blend_mode == kBlendHorizontal ? to_current_point_.X()
: to_current_point_.Y();
// Transform toY to the coordinate mode of fromY
float anim_value =
Blend(from, from_is_absolute_ ? to + to_value : to - to_value, progress_);
// If we're in the first half of the animation, we should use the type of the
// from segment.
if (is_in_first_half_of_animation_)
return anim_value;
// Transform the animated point to the coordinate mode, needed for the current
// progress.
float current_value = Blend(from_value, to_value, progress_);
return !from_is_absolute_ ? anim_value + current_value
: anim_value - current_value;
}
FloatPoint SVGPathBlender::BlendState::BlendAnimatedFloatPointSameCoordinates(
const FloatPoint& from_point,
const FloatPoint& to_point) {
if (add_types_count_) {
FloatPoint repeated_to_point = to_point;
repeated_to_point.Scale(add_types_count_, add_types_count_);
return from_point + repeated_to_point;
}
return BlendFloatPoint(from_point, to_point, progress_);
}
FloatPoint SVGPathBlender::BlendState::BlendAnimatedFloatPoint(
const FloatPoint& from_point,
const FloatPoint& to_point) {
if (types_are_equal_)
return BlendAnimatedFloatPointSameCoordinates(from_point, to_point);
// Transform toPoint to the coordinate mode of fromPoint
FloatPoint animated_point = to_point;
if (from_is_absolute_)
animated_point += to_current_point_;
else
animated_point.Move(-to_current_point_.X(), -to_current_point_.Y());
animated_point = BlendFloatPoint(from_point, animated_point, progress_);
// If we're in the first half of the animation, we should use the type of the
// from segment.
if (is_in_first_half_of_animation_)
return animated_point;
// Transform the animated point to the coordinate mode, needed for the current
// progress.
FloatPoint current_point =
BlendFloatPoint(from_current_point_, to_current_point_, progress_);
if (!from_is_absolute_)
return animated_point + current_point;
animated_point.Move(-current_point.X(), -current_point.Y());
return animated_point;
}
bool SVGPathBlender::BlendState::CanBlend(const PathSegmentData& from_seg,
const PathSegmentData& to_seg) {
// Update state first because we'll need it if we return true below.
types_are_equal_ = from_seg.command == to_seg.command;
from_is_absolute_ = IsAbsolutePathSegType(from_seg.command);
// If the types are equal, they'll blend regardless of parameters.
if (types_are_equal_)
return true;
// Addition require segments with the same type.
if (add_types_count_)
return false;
// Allow the segments to differ in "relativeness".
return ToAbsolutePathSegType(from_seg.command) ==
ToAbsolutePathSegType(to_seg.command);
}
static void UpdateCurrentPoint(FloatPoint& sub_path_point,
FloatPoint& current_point,
const PathSegmentData& segment) {
switch (segment.command) {
case kPathSegMoveToRel:
current_point += segment.target_point;
sub_path_point = current_point;
break;
case kPathSegLineToRel:
case kPathSegCurveToCubicRel:
case kPathSegCurveToQuadraticRel:
case kPathSegArcRel:
case kPathSegLineToHorizontalRel:
case kPathSegLineToVerticalRel:
case kPathSegCurveToCubicSmoothRel:
case kPathSegCurveToQuadraticSmoothRel:
current_point += segment.target_point;
break;
case kPathSegMoveToAbs:
current_point = segment.target_point;
sub_path_point = current_point;
break;
case kPathSegLineToAbs:
case kPathSegCurveToCubicAbs:
case kPathSegCurveToQuadraticAbs:
case kPathSegArcAbs:
case kPathSegCurveToCubicSmoothAbs:
case kPathSegCurveToQuadraticSmoothAbs:
current_point = segment.target_point;
break;
case kPathSegLineToHorizontalAbs:
current_point.SetX(segment.target_point.X());
break;
case kPathSegLineToVerticalAbs:
current_point.SetY(segment.target_point.Y());
break;
case kPathSegClosePath:
current_point = sub_path_point;
break;
default:
NOTREACHED();
}
}
bool SVGPathBlender::BlendState::BlendSegments(
const PathSegmentData& from_seg,
const PathSegmentData& to_seg,
PathSegmentData& blended_segment) {
if (!CanBlend(from_seg, to_seg))
return false;
blended_segment.command =
is_in_first_half_of_animation_ ? from_seg.command : to_seg.command;
switch (to_seg.command) {
case kPathSegCurveToCubicRel:
case kPathSegCurveToCubicAbs:
blended_segment.point1 =
BlendAnimatedFloatPoint(from_seg.point1, to_seg.point1);
/* fall through */
case kPathSegCurveToCubicSmoothRel:
case kPathSegCurveToCubicSmoothAbs:
blended_segment.point2 =
BlendAnimatedFloatPoint(from_seg.point2, to_seg.point2);
/* fall through */
case kPathSegMoveToRel:
case kPathSegMoveToAbs:
case kPathSegLineToRel:
case kPathSegLineToAbs:
case kPathSegCurveToQuadraticSmoothRel:
case kPathSegCurveToQuadraticSmoothAbs:
blended_segment.target_point =
BlendAnimatedFloatPoint(from_seg.target_point, to_seg.target_point);
break;
case kPathSegLineToHorizontalRel:
case kPathSegLineToHorizontalAbs:
blended_segment.target_point.SetX(BlendAnimatedDimensonalFloat(
from_seg.target_point.X(), to_seg.target_point.X(),
kBlendHorizontal));
break;
case kPathSegLineToVerticalRel:
case kPathSegLineToVerticalAbs:
blended_segment.target_point.SetY(BlendAnimatedDimensonalFloat(
from_seg.target_point.Y(), to_seg.target_point.Y(), kBlendVertical));
break;
case kPathSegClosePath:
break;
case kPathSegCurveToQuadraticRel:
case kPathSegCurveToQuadraticAbs:
blended_segment.target_point =
BlendAnimatedFloatPoint(from_seg.target_point, to_seg.target_point);
blended_segment.point1 =
BlendAnimatedFloatPoint(from_seg.point1, to_seg.point1);
break;
case kPathSegArcRel:
case kPathSegArcAbs:
blended_segment.target_point =
BlendAnimatedFloatPoint(from_seg.target_point, to_seg.target_point);
blended_segment.point1 = BlendAnimatedFloatPointSameCoordinates(
from_seg.ArcRadii(), to_seg.ArcRadii());
blended_segment.point2 = BlendAnimatedFloatPointSameCoordinates(
from_seg.point2, to_seg.point2);
if (add_types_count_) {
blended_segment.arc_large = from_seg.arc_large || to_seg.arc_large;
blended_segment.arc_sweep = from_seg.arc_sweep || to_seg.arc_sweep;
} else {
blended_segment.arc_large = is_in_first_half_of_animation_
? from_seg.arc_large
: to_seg.arc_large;
blended_segment.arc_sweep = is_in_first_half_of_animation_
? from_seg.arc_sweep
: to_seg.arc_sweep;
}
break;
default:
NOTREACHED();
}
UpdateCurrentPoint(from_sub_path_point_, from_current_point_, from_seg);
UpdateCurrentPoint(to_sub_path_point_, to_current_point_, to_seg);
return true;
}
SVGPathBlender::SVGPathBlender(SVGPathByteStreamSource* from_source,
SVGPathByteStreamSource* to_source,
SVGPathConsumer* consumer)
: from_source_(from_source), to_source_(to_source), consumer_(consumer) {
DCHECK(from_source_);
DCHECK(to_source_);
DCHECK(consumer_);
}
bool SVGPathBlender::AddAnimatedPath(unsigned repeat_count) {
BlendState blend_state(0, repeat_count);
return BlendAnimatedPath(blend_state);
}
bool SVGPathBlender::BlendAnimatedPath(float progress) {
BlendState blend_state(progress);
return BlendAnimatedPath(blend_state);
}
bool SVGPathBlender::BlendAnimatedPath(BlendState& blend_state) {
bool from_source_is_empty = !from_source_->HasMoreData();
while (to_source_->HasMoreData()) {
PathSegmentData to_seg = to_source_->ParseSegment();
if (to_seg.command == kPathSegUnknown)
return false;
PathSegmentData from_seg;
from_seg.command = to_seg.command;
if (from_source_->HasMoreData()) {
from_seg = from_source_->ParseSegment();
if (from_seg.command == kPathSegUnknown)
return false;
}
PathSegmentData blended_seg;
if (!blend_state.BlendSegments(from_seg, to_seg, blended_seg))
return false;
consumer_->EmitSegment(blended_seg);
if (from_source_is_empty)
continue;
if (from_source_->HasMoreData() != to_source_->HasMoreData())
return false;
}
return true;
}
} // namespace blink
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
92eebca2e65e719303ebf521b1f171458be02377 | 2f37b0b5ea900093ec3d06f835824270738c0556 | /剑指offer/002_替换空格.cc | a26f0f3d8c8f3b4d64b3d82c9e6876dc03b1c879 | [] | no_license | yanglin526000/Wu-Algorithm | d0da3fdc92748c21c2a96b096a260a608f04adab | 5259f8c81fc9a14ec35c5422d0edb9ec36304ae8 | refs/heads/master | 2021-09-11T12:41:48.195238 | 2018-04-07T04:48:17 | 2018-04-07T04:48:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cc | #include<string>
#include<limits.h>
using namespace std;
//请实现一个函数,将一个字符串中的空格替换成“%20”。
//例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution {
public:
void replaceSpace(char *str, int length) {
//保证字符串数组有足够的空间去容纳变长后的字母
int countSpaces = 0;
for (int i = 0; i < length; i++) {
if (str[i] == ' ')
countSpaces++;
}
if (countSpaces > 0) {
for (int i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
countSpaces--;
int index = countSpaces * 2 + i;
str[index] = '%';
str[index + 1] = '2';
str[index + 2] = '0';
} else {
str[i + countSpaces * 2] = str[i];
}
}
}
}
}; | [
"jt26wzz@icloud.com"
] | jt26wzz@icloud.com |
15f9e758f5b3b78c8dfbba3ec729e4ef124a4101 | 83f27e9b04c7c7772f8a64238d3b86d22e8b0eef | /chrome/browser/updates/update_notification_service_bridge.h | a77cbd28a9564831dda7cf73f91f14996f817948 | [
"BSD-3-Clause"
] | permissive | fxb20170613/chromium | 122a0dd9efa36ebd238a53a45dd799fcbff36b1c | 501061ccbb7b9fab6dad77babecf12e4ae9f7890 | refs/heads/master | 2023-03-02T08:47:05.969248 | 2020-02-03T16:18:55 | 2020-02-03T16:18:55 | 238,015,164 | 1 | 0 | BSD-3-Clause | 2020-02-03T16:54:31 | 2020-02-03T16:54:30 | null | UTF-8 | C++ | false | false | 1,867 | h | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UPDATES_UPDATE_NOTIFICATION_SERVICE_BRIDGE_H_
#define CHROME_BROWSER_UPDATES_UPDATE_NOTIFICATION_SERVICE_BRIDGE_H_
#include <memory>
#include "base/macros.h"
#include "base/optional.h"
#include "base/time/time.h"
namespace updates {
class UpdateNotificationServiceBridge {
public:
// Create the default UpdateNotificationServiceBridge.
static std::unique_ptr<UpdateNotificationServiceBridge> Create();
// Updates and persists |timestamp| in Android SharedPreferences.
virtual void UpdateLastShownTimeStamp(base::Time timestamp);
// Returns persisted timestamp of last shown notification from Android
// SharedPreferences. Return nullopt if there is no data.
virtual base::Optional<base::Time> GetLastShownTimeStamp();
// Updates and persists |interval| in Android SharedPreferences.
virtual void UpdateThrottleInterval(base::TimeDelta interval);
// Returns persisted interval that might be throttled from Android
// SharedPreferences. Return nullopt if there is no data.
virtual base::Optional<base::TimeDelta> GetThrottleInterval();
// Updates and persists |count| in Android SharedPreferences.
virtual void UpdateUserDismissCount(int count);
// Returns persisted count from Android SharedPreferences.
virtual int GetUserDismissCount();
// Launches Chrome activity after user clicked the notification.
virtual void LaunchChromeActivity();
virtual ~UpdateNotificationServiceBridge() = default;
protected:
UpdateNotificationServiceBridge() = default;
private:
DISALLOW_COPY_AND_ASSIGN(UpdateNotificationServiceBridge);
};
} // namespace updates
#endif // CHROME_BROWSER_UPDATES_UPDATE_NOTIFICATION_SERVICE_BRIDGE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8ef9164a2cfc38c167d66fb9d8f8b798efbc1e5e | 0f054d3440d94f27bc61c2b69c46d250fd1400a8 | /ModCpp/DemoCode/ProductivityFeatures/lambdas.h | 79dc252a46245cd573b26ef472a2c0a43492c77c | [] | no_license | Tomerder/Cpp | db73f34e58ff36e145af619f03c2f4d19d44dc5d | 18bfef5a571a74ea44e480bd085b4b789839f90d | refs/heads/master | 2020-04-13T21:37:06.400580 | 2018-12-29T02:35:50 | 2018-12-29T02:35:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,142 | h | #pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <numeric>
#include <random>
#include <iterator>
#include <future>
#pragma region STL is great
void stl_is_great1()
{
std::vector<int> ints;
std::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(ints)
);
std::copy(
ints.begin(), ints.end(),
std::ostream_iterator<int>(std::cout, "\n")
);
}
// stl_is_great2
int range_sum(std::set<int> const& s, int start, int end) {
return std::accumulate(
s.lower_bound(start),
s.upper_bound(end),
0
);
}
void stl_is_great3a()
{
std::vector<std::string> cards { "Jack of Spades", "8 of Hearts", "3 of Diamonds", "Queen of Hearts" };
std::random_shuffle(cards.begin(), cards.end());
}
// stl_is_great3b
bool is_palindrome(std::string s) {
return std::equal(
s.begin(),
s.begin() + s.size() / 2,
s.rbegin()
);
}
// stl_is_great4
template <typename InputIterator>
bool is_sorted(InputIterator first, InputIterator last) {
return std::adjacent_find(
first, last,
std::greater<decltype(*first)>()
) == last.end();
}
#pragma endregion
#pragma region Lambda
void stateless_lambdas()
{
std::vector<int> numbers(100);
std::mt19937 rng(std::random_device{}());
std::generate(numbers.begin(), numbers.end(), rng);
std::count_if(numbers.begin(), numbers.end(),
[](int n) { return n < 17; }
);
// AS IF
struct lambda_count_if
{
bool operator()(int n) const
{
return n < 17;
}
};
std::count_if(numbers.begin(), numbers.end(), lambda_count_if{});
std::vector<int> squares;
std::transform(numbers.begin(), numbers.end(), std::back_inserter(squares),
[](int n) { return n * n; }
);
// AS IF
struct lambda_transform
{
int operator()(int n) const
{
return n * n;
}
};
std::transform(numbers.begin(), numbers.end(), std::back_inserter(squares), lambda_transform{});
int x = 17;
auto lambda = [x]() mutable { ++x; };
lambda();
lambda();
// AS IF
struct lambda_17
{
int x_;
lambda_17(int x):x_(x){}
void operator()()
{
++x_;
}
};
}
#pragma endregion
#pragma region parallel_invoke machinery
bool is_prime(unsigned n)
{
if (n % 2 != 0)
{
auto root = static_cast<unsigned>(std::sqrt(static_cast<double>(n)));
for (auto d = 3u; d <= root; d += 3)
{
if (n % d == 0)
{
return false;
}
}
return true;
}
return n == 2;
}
void parallel_invoke()
{
}
template <typename F1, typename... Fs>
void parallel_invoke(F1&& f1, Fs&&... fs)
{
auto fut = std::async(std::forward<F1>(f1));
parallel_invoke(fs...);
fut.wait();
}
#pragma endregion
#pragma region stateful_lambdas
void stateful_lambdas()
{
std::vector<int> numbers(100);
std::mt19937 rng(std::random_device{}());
std::generate(numbers.begin(), numbers.end(), rng);
int less_than_what;
std::cin >> less_than_what;
std::count_if(numbers.begin(), numbers.end(),
[less_than_what](int n) { return n < less_than_what; }
);
// AS if
struct lambda_less_than_what
{
int _less_than_what;
lambda_less_than_what(int less_than_what) :_less_than_what{ less_than_what } {}
bool operator()(int n) { return n < _less_than_what; }
};
less_than_what = 0;
auto lm = lambda_less_than_what{ less_than_what };
std::count_if(numbers.begin(), numbers.end(), lm);
std::atomic<size_t> primes{ 0 };
auto l1 = [&primes]() {
for (auto n = 2u; n < 100000u; ++n)
{
if (is_prime(n))
{
++primes;
}
}
};
// AS if
struct lambda1
{
std::atomic<size_t>& _primes;
lambda1(std::atomic<size_t>& primes) :_primes{ primes } {}
void operator()() { _primes++; }
};
auto l2 = [&primes]() {
for (auto n = 100000u; n < 200000u; ++n)
{
if (is_prime(n))
{
++primes;
}
}
};
parallel_invoke(l1, l2);
}
template <typename Iter>
auto product(Iter first, Iter last)
{
auto initial = *first;
return std::accumulate(
++first, last,
initial,
[](auto x, auto y) { return x * y; }
);
}
void generic_lambdas()
{
std::vector<int> numbers{ 1,2,3,4,5 };
std::cout << product(numbers.begin(), numbers.end()) << std::endl;
}
#pragma endregion | [
"tomerder@gmail.com"
] | tomerder@gmail.com |
b59ec5cfa2e1fb0da9328186c71a6774669933b5 | ce420020aa4bcbbc562c55db16804e6f10013aef | /1379.cpp | 7f78b134a93177eacfca3b1926706f1d9e50b9c0 | [] | no_license | pbking1/cplusplus--algorithm | b0cfba3fd8d5e9fd7cba0a7d745219de69f925d6 | c6fbae99d77e3af6a433e9ae6a42885f9fb54bec | refs/heads/master | 2020-03-30T15:44:39.755972 | 2014-01-08T12:51:46 | 2014-01-08T12:51:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,368 | cpp | #include<iostream>
#include<queue>
#include<map>
using namespace std;
/*
Input
第一行是一个整数n,表示一共有多少组测试数据。
下面n行每行9个字符,用空格隔开,代表一个初始状态。
目标状态是 1 2 3 4 5 6 7 8 0。
Output
最小操作步数,无解时输出-1。
sample input
4
1 2 3 4 5 0 7 8 6
1 2 3 4 0 5 6 7 8
8 6 7 2 5 4 3 0 1
6 4 7 8 5 0 3 2 1
sample output
1
14
31
31
注意在 Release 模式下运行此程序,否则可能会很慢!
注意优先队列 priority_queue 是最大堆,因此在定义 STATE 结构的比较函数时要让 f 值较小的元素较大,
而当 f 相等的时候,启发函数 h 较小的状态应该优先考虑,故让该状态较大。
优先队列中仍然会存在一些 CLOSED 表中的状态,因为在生成新的状态时没有查找删除该新状态是否生成过。
*/
const int ten[9] = {100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10,1};
int dist[9][9], diff[9][9];
//dist[i][j]为位置i,j的曼哈顿距离,diff[i][j]为交换位置i,j使状态数改变的量
int goalPos[9] = {8, 0, 1, 2, 3, 4, 5, 6, 7};
//goalpos[i]为目标状态中i的位置
int goalNum = 123456780; //目标状态的状态数
int goallnv = 0; //目标状态忽略0后的逆序数
int state[9]; //当前状态
struct STATE{
int num, pos, g, h; //状态数, 0的位置, 到达此状态的耗费, 到达目标状态的启发函数值
STATE(int num, int pos, int g, int h):num(num), pos(pos), g(g), h(h){}
bool operator<(const STATE& other) const{ //状态的评价函数等于耗费加上启发函数值
if(g + h == other.g + other.h) //由于查询较少,此句帮助不大
return h > other.h;
return g + h > other.g + other.h;
}
};
void preprocess(){ //预处理
for(int i = 0; i < 9; i++){
dist[i][i] = 0;
for(int j = 0; j < i; j++){
dist[i][j] = dist[j][i] = abs(i/3 - j/3) + abs(i%3 - j%3);
diff[i][j] = diff[j][i] = abs(ten[i] - ten[j]);
}
}
}
//检查开始状态忽略0后的逆序数, 如果和目标装填的逆序数奇偶性不一致,则无解
bool noAnswer(int pos){
int inv = 0;
for(int i = 0; i < 9; i++)
for(int j = 0; j < i; j++)
if(state[j] > state[i])
inv++;
return (inv - pos - goallnv) % 2 != 0;
}
int heu(int pos){ //计算启发值
int h = 0;
for(int i = 0; i < 9; i++){
int j = goalPos[state[i]];
h += dist[i][j];
}
return h - dist[pos][goalPos[0]];
}
int astar(){
int num = 0, pos = 0;
for(int i = 0; i < 9; i++){
cin>>state[i];
}
for(int i = 0; i < 9; i++){
num = num * 10 + state[i];
}
for(int i = 0; state[i]; i++){
pos++;
}
if(noAnswer(pos))
return -1;
map<int, int> ng; //closed表, 已拓展结点(状态数 -》 到达该节点的最少耗费)
priority_queue<STATE> q; //opened表, 待拓展结点, 但是仍然会存在已拓展节点的记录
STATE start(num, pos, 1, heu(pos)); //因为map对不存在的key返回0, 故初始状态的耗费应该设为1
q.push(start);
while(q.size()){
STATE top = q.top(); //考察open表里面评价函数值最小的节点
q.pop();
int pos = top.pos, num = top.num, g = top.g, h = top.h;
if(num == goalNum){
return g - 1; //找到最优解,注意要减掉1
}
if(ng[num])
continue; //已经拓展过此节点则忽略
ng[num] = g; //节点加入closed表
//拓展词节点
if(pos > 2){
int p = pos - 3;
int i = num / ten[p] % 10, n = num - i * diff[pos][p];
int h2 = h - dist[p][goalPos[i]] + dist[pos][goalPos[i]];
if(!ng[n])
q.push(STATE(n, p, g + 1, h2));
}
if(pos < 6){
int p = pos + 3;
int i = num / ten[p] % 10, n = num + i * diff[pos][p];
int h2 = h - dist[p][goalPos[i]] + dist[pos][goalPos[i]];
if(!ng[n])
q.push(STATE(n, p, g + 1, h2));
}
if(pos % 3){
int p = pos - 1;
int i = num / ten[p] % 10, n = num - i * diff[pos][p];
int h2 = h - dist[p][goalPos[i]] + dist[pos][goalPos[i]];
if(!ng[n])
q.push(STATE(n, p, g + 1, h2));
}
if(pos % 3 != 2){
int p = pos + 1;
int i = num / ten[p] % 10, n = num + i * diff[pos][p];
int h2 = h - dist[p][goalPos[i]] + dist[pos][goalPos[i]];
if(!ng[n])
q.push(STATE(n, p, g + 1, h2));
}
}
return 0;
}
int main(){
preprocess();
int t;
cin>>t;
while(t--){
cout<<astar();
}
return 0;
}
| [
"731849410@qq.com"
] | 731849410@qq.com |
edfaa31e30516fb15419f9b9b88bc37fbbd05c0b | 6b6e19cb8b0ae8ec47cdadd2d7ba53c52e06d769 | /CIS4800/A3/Qix/bouncy.h | aa32b52bc87d15c94ddfd69acefda6c140534303 | [
"MIT"
] | permissive | Bananattack/uoguelph | b0b5a69a7b1ec267017685a9c13a5fdabcc889e3 | a5c46718ac15a5738eb58a0d75147f928df1dde2 | refs/heads/master | 2021-01-01T19:00:43.738084 | 2012-08-09T07:47:01 | 2012-08-09T07:47:01 | 5,338,004 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,352 | h | // CIS*4800 Computer Graphics
// Andrew Crowell
// acrowell@uoguelph.ca
// 0545826
#pragma once
namespace Qix
{
class Bouncy
{
private:
static const double SPEED = 0.1;
static const double MOVEMENT_STEP = 0.01;
public:
double speed;
double angle;
double bounceAngle;
int bounceCount;
Sphere shape;
Bouncy()
{
speed = angle = 0;
init();
}
Bouncy(Sphere sphere)
: shape(sphere)
{
speed = SPEED;
angle = 85 * M_PI / 180; //M_PI / 2;
init();
}
~Bouncy()
{
}
void init()
{
bounceCount = 0;
}
void update(std::vector<Wall>& walls)
{
for(double i = 0; i < speed; i += MOVEMENT_STEP)
{
handleCollision(walls);
Vector3& v = shape.transformation().translation;
v.data[Vector3::X] += cos(angle) * MOVEMENT_STEP;
v.data[Vector3::Y] += sin(angle) * MOVEMENT_STEP;
}
}
void render()
{
shape.render();
}
Vector2 getMapPosition()
{
Vector2 position = shape.transformation().translation.flatten();
double x = floor(position.data[Vector2::X] + 0.5);
double y = floor(position.data[Vector2::Y] + 0.5);
x -= Map::WORLD_START_X;
x += Map::UNIT_WIDTH / 2;
y -= Map::WORLD_START_Y;
y += Map::UNIT_HEIGHT / 2;
x /= Map::UNIT_WIDTH;
y /= Map::UNIT_HEIGHT;
position.data[Vector2::X] = (int) x;
position.data[Vector2::Y] = (int) y;
return position;
}
void handleCollision(std::vector<Wall>& walls)
{
Vector2 position = shape.transformation().translation.flatten();
Vector2::Scalar radiusSquared = shape.transformation().scale.flatten().lengthSquared();
for(unsigned int i = 0; i < walls.size(); i++)
{
Wall& wall = walls[i];
if(!wall.visible)
{
continue;
}
int q = quadrant(angle);
bool detect;
for(int e = 0; e < 4; e++)
{
switch(q)
{
case 0:
detect = e == 2 || e == 3;
break;
case 1:
detect = e == 2 || e == 1;
break;
case 2:
detect = e == 0 || e == 1;
break;
case 3:
detect = e == 0 || e == 3;
break;
}
if(detect && wall.visible && wall.distanceSquared(e, position) <= radiusSquared)
{
Vector2 v = Vector2(cos(angle) * MOVEMENT_STEP, sin(angle) * MOVEMENT_STEP);
angle = wall.reflectionAngle(e, v.normalize());
//printf("%lf angle, q = %d, BOUNCE w = %u i = %d e= %d\n", angle * 180 / M_PI, q, i, e, bounceCount);
//printf("%lf - %lf = %lf vs %lf\n", angle, modulo(bounceAngle + M_PI, 2 * M_PI), modulo(angle - bounceAngle, 2 * M_PI), M_PI);
if(bounceCount && near(wrapAngle(angle - bounceAngle), M_PI))
{
if(bounceCount == 2)
{
angle += (1 - ((double) rand() / ((double) RAND_MAX + 1.0) * 2)) * M_PI / 6;
angle += sgn(angle) * M_PI / 4;
bounceCount = 0;
}
}
else
{
bounceCount = 0;
}
bounceAngle = angle;
bounceCount++;
return;
}
}
}
}
};
}
| [
"overkill9999@gmail.com"
] | overkill9999@gmail.com |
066f362636a02988a45995364581ed190315d2f2 | 781f351347692832c17ebd43bb90accd1036572d | /Sources/MultiServer/S3Relay/StdAfx.cpp | 12350ddedaf134b288827ba66be90d7966477a5e | [] | no_license | fcccode/Jx | 71f9a549c7c6bbd1d00df5ad3e074a7c1c665bd1 | 4b436851508d76dd626779522a080b35cf8edc14 | refs/heads/master | 2020-04-14T07:59:12.814607 | 2017-05-23T07:57:15 | 2017-05-23T07:57:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | // stdafx.cpp : source file that includes just the standard includes
// S3Relay.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"tuan.n0s0und@gmail.com"
] | tuan.n0s0und@gmail.com |
c0e5383015e817a27552b73163034221cfd87362 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/net/upnp/common/upnetwork/interfacetable.cpp | 96f550411c54ec07f2383dd6a37c724bb6da45cc | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,778 | cpp | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 2000.
//
// File: I N T E R F A C E T A B L E . C P P
//
// Contents: Builds a mapping from IP addresses to interface guids
//
// Notes:
//
// Author: mbend 7 Feb 2001
//
//----------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
#include "InterfaceTable.h"
#include <winsock2.h>
#include <iphlpapi.h>
CInterfaceTable::CInterfaceTable()
{
}
CInterfaceTable::~CInterfaceTable()
{
}
HRESULT CInterfaceTable::HrInitialize()
{
HRESULT hr = S_OK;
PIP_ADAPTER_INFO pip = NULL;
ULONG ulSize = 0;
GetAdaptersInfo(NULL, &ulSize);
if(ulSize)
{
pip = reinterpret_cast<PIP_ADAPTER_INFO>(malloc(ulSize));
DWORD dwRet = GetAdaptersInfo(pip, &ulSize);
hr = HRESULT_FROM_WIN32(dwRet);
if(SUCCEEDED(hr))
{
PIP_ADAPTER_INFO pipIter = pip;
while(pipIter && SUCCEEDED(hr))
{
wchar_t szAdapter[MAX_ADAPTER_NAME_LENGTH + 4];
wchar_t * pchAdapter = szAdapter;
wchar_t * pchAdapterEnd = szAdapter;
MultiByteToWideChar(CP_ACP, 0, pipIter->AdapterName, -1, szAdapter, MAX_ADAPTER_NAME_LENGTH + 4);
// Make sure it's not an empty string first
if (*pchAdapter)
{
// skip over the '{'
pchAdapter++;
// chop off the '}'
pchAdapterEnd = wcschr(szAdapter, '\0');
if (pchAdapterEnd)
{
pchAdapterEnd--;
*pchAdapterEnd = 0;
}
}
GUID guidInterface;
if (RPC_S_OK == UuidFromString(pchAdapter, &guidInterface))
{
hr = S_OK;
}
else
{
hr = E_FAIL;
}
PIP_ADDR_STRING pipaddr = &pipIter->IpAddressList;
while(pipaddr && SUCCEEDED(hr))
{
InterfaceMapping interfaceMapping;
interfaceMapping.m_guidInterface = guidInterface;
interfaceMapping.m_dwIpAddress = inet_addr(pipaddr->IpAddress.String);
interfaceMapping.m_dwIndex = htonl(pipIter->Index);
if(interfaceMapping.m_dwIpAddress)
{
hr = m_interfaceMappingList.HrPushBack(interfaceMapping);
}
pipaddr = pipaddr->Next;
}
pipIter = pipIter->Next;
}
}
free(pip);
}
TraceHr(ttidSsdpNetwork, FAL, hr, FALSE, "CInterfaceTable::HrInitialize");
return hr;
}
HRESULT CInterfaceTable::HrMapIpAddressToGuid(DWORD dwIpAddress, GUID & guidInterface)
{
HRESULT hr = S_OK;
ZeroMemory(&guidInterface, sizeof(GUID));
long nCount = m_interfaceMappingList.GetCount();
for(long n = 0; n < nCount; ++n)
{
if(m_interfaceMappingList[n].m_dwIpAddress == dwIpAddress)
{
guidInterface = m_interfaceMappingList[n].m_guidInterface;
break;
}
}
TraceHr(ttidSsdpNetwork, FAL, hr, FALSE, "CInterfaceTable::HrMapIpAddressToGuid");
return hr;
}
HRESULT CInterfaceTable::HrGetMappingList(InterfaceMappingList & interfaceMappingList)
{
HRESULT hr = S_OK;
interfaceMappingList.Swap(m_interfaceMappingList);
TraceHr(ttidSsdpNetwork, FAL, hr, FALSE, "CInterfaceTable::HrGetMappingList");
return hr;
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
60f437ece81a99760c51b3d933884225f8bd45c6 | e9ade5ea33cf3382f8ab3ad980e7f6d8cb76faf8 | /solved/abc188/aa.cpp | cfe3b55f4f4bbe433d38fac7b4fd028e841f8794 | [] | no_license | Creamy1137689/kyopro | 75bc3f92edb7bff2cbf27dc79d384b422a0a4702 | dcacbf27defe840ea7998e06a5f3fb78718e7d53 | refs/heads/master | 2023-05-10T19:28:56.447493 | 2021-06-03T12:54:11 | 2021-06-03T12:54:11 | 266,143,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,887 | cpp | //https://atcoder.jp/contests/abc188/submissions/19356072
#ifdef LOCAL
//#define _GLIBCXX_DEBUG
#endif
//#pragma GCC target("avx512f,avx512dq,avx512cd,avx512bw,avx512vl")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef pair<int, int> Pi;
typedef vector<ll> Vec;
typedef vector<int> Vi;
typedef vector<string> Vs;
typedef vector<char> Vc;
typedef vector<P> VP;
typedef vector<vector<ll>> VV;
typedef vector<vector<int>> VVi;
typedef vector<vector<char>> VVc;
typedef vector<vector<vector<ll>>> VVV;
typedef vector<vector<vector<vector<ll>>>> VVVV;
#define endl '\n'
#define REP(i, a, b) for(ll i=(a); i<(b); i++)
#define PER(i, a, b) for(ll i=(a); i>=(b); i--)
#define rep(i, n) REP(i, 0, n)
#define per(i, n) PER(i, n, 0)
const ll INF=1e18+18;
const ll MOD=1000000007;
#define Yes(n) cout << ((n) ? "Yes" : "No") << endl;
#define YES(n) cout << ((n) ? "YES" : "NO") << endl;
#define ALL(v) v.begin(), v.end()
#define rALL(v) v.rbegin(), v.rend()
#define pb(x) push_back(x)
#define mp(a, b) make_pair(a,b)
#define Each(a,b) for(auto &a :b)
#define rEach(i, mp) for (auto i = mp.rbegin(); i != mp.rend(); ++i)
#ifdef LOCAL
#define dbg(x_) cerr << #x_ << ":" << x_ << endl;
#define dbgmap(mp) cerr << #mp << ":"<<endl; for (auto i = mp.begin(); i != mp.end(); ++i) { cerr << i->first <<":"<<i->second << endl;}
#define dbgset(st) cerr << #st << ":"<<endl; for (auto i = st.begin(); i != st.end(); ++i) { cerr << *i <<" ";}cerr<<endl;
#define dbgarr(n,m,arr) rep(i,n){rep(j,m){cerr<<arr[i][j]<<" ";}cerr<<endl;}
#define dbgdp(n,arr) rep(i,n){cerr<<arr[i]<<" ";}cerr<<endl;
#else
#define dbg(...)
#define dbgmap(...)
#define dbgset(...)
#define dbgarr(...)
#define dbgdp(...)
#endif
#define out(a) cout<<a<<endl
#define out2(a,b) cout<<a<<" "<<b<<endl
#define vout(v) rep(i,v.size()){cout<<v[i]<<" ";}cout<<endl
#define Uniq(v) v.erase(unique(v.begin(), v.end()), v.end())
#define fi first
#define se second
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
template<typename T1, typename T2>
ostream &operator<<(ostream &s, const pair<T1, T2> &p) { return s<<"("<<p.first<<", "<<p.second<<")"; }
template<typename T>istream& operator>>(istream&i,vector<T>&v)
{rep(j,v.size())i>>v[j];return i;}
// vector
template<typename T>
ostream &operator<<(ostream &s, const vector<T> &v) {
int len=v.size();
for(int i=0; i<len; ++i) {
s<<v[i];
if(i<len-1) s<<" ";
}
return s;
}
// 2 dimentional vector
template<typename T>
ostream &operator<<(ostream &s, const vector<vector<T> > &vv) {
s<<endl;
int len=vv.size();
for(int i=0; i<len; ++i) {
s<<vv[i]<<endl;
}
return s;
}
int solve(){
ll x;
ll y;
cin>>x>>y;
if(x>y){
cout << x-y << endl;
return 0;
}
if(x==y){
out(0);
return 0;
}
map<ll,ll> memo;
auto dfs = [&](auto dfs, ll n)->ll {
dbg(n);
if(memo.count(n) > 0) {
return memo[n];
}
if(n <= x){
return memo[n] = abs(n-x);
}
ll res = abs(n-x);
if( (n % 2) == 1){
chmin(res, 1 + dfs(dfs, n+1));
chmin(res, 1 + dfs(dfs, n-1));
}else{
chmin(res, 1 + dfs(dfs, n/2));
}
return memo[n] = res;
};
ll ans = dfs(dfs, y);
out(ans);
dbgmap(memo);
return 0;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cout<<std::setprecision(10);
// ll T;
// cin>>T;
// while(T--)
solve();
}
| [
"exception031noexist@gmail.com"
] | exception031noexist@gmail.com |
e5daf0b67af9300a8a7d963b0b2f79210a63f132 | 65aae4f8be2ec8f12a7b91df0fb4c797716046c9 | /machine.cc | 2c352f30d4394057022b0f2723df20ea61fa054b | [] | no_license | ramprakash-k/compilers | ef9a688d4c282eded8c5ef86a2d53964a2f0b3f9 | 7b87baf4964be5a2a527343517af48a172fe58f6 | refs/heads/master | 2021-03-24T10:43:23.562294 | 2015-04-28T10:44:24 | 2015-04-28T10:44:24 | 34,562,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,426 | cc | #include<iostream>
#define STACK_SIZE 10000
#define j(l) goto l
#define je(l) if(_flag==0) goto l
#define jne(l) if(_flag!=0) goto l
#define jl(l) if(_flag==-1) goto l
#define jle(l) if(_flag==-1||_flag==0) goto l
#define jg(l) if(_flag==1) goto l
#define jge(l) if(_flag==1||_flag==0) goto l
using namespace std;
class CMachineBase {
protected:
int _flag;
enum Reg {
eax, ebx, ecx, edx, esp, ebp, edi, esi
};
int I, F, P;
void intTofloat(Reg reg) {
char* r = getReg(reg);
*((float*) r) = (float) (*((int *) r));
}
void floatToint(Reg reg) {
char* r = getReg(reg);
*((int*) r) = (int) (*((float *) r));
}
void move(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
for (int i = 0; i < F; i++) {
des[i] = src[i];
}
}
void move(int i, Reg r) {
char* reg = getReg(r);
*((int*) reg) = i;
}
void move(double f, Reg r) {
char* reg = getReg(r);
*((float*) reg) = (float) f;
}
// Load an integer from memory to register
void loadi(char* mem, Reg r) {
char* reg = getReg(r);
*((int*) reg) = *((int*) mem);
}
// Load a floating point number from memory to register
void loadf(char* mem, Reg r) {
char* reg = getReg(r);
*((float*) reg) = *((float*) mem);
}
// Store an immediate integer to memory
void storei(int i, char* mem) {
*((int*) mem) = i;
}
// Store an integer from register to memory
void storei(Reg r, char* mem) {
char* reg = getReg(r);
*((int*) mem) = *((int*) reg);
}
// Store an immediate floating point number to memory
void storef(double i, char* mem) {
*((float*) mem) = (float)i;
}
// Store a floating point number from register to memory
void storef(Reg r, char* mem) {
char* reg = getReg(r);
*((float*) mem) = *((float*) reg);
}
void addi(int i, Reg r) {
char* reg = getReg(r);
int j = *((int*) reg);
int ans = i + j;
*((int*) reg) = ans;
}
void addi(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
int i = *((int*) src);
int j = *((int*) des);
int ans = i + j;
*((int*) des) = ans;
}
void addf(double i, Reg r) {
char* reg = getReg(r);
float j = *((float*) reg);
float ans = ((float)i) + j;
*((float*) reg) = ans;
}
void addf(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
float i = *((float*) src);
float j = *((float*) des);
float ans = i + j;
*((float*) des) = ans;
}
void muli(int i, Reg r) {
char* reg = getReg(r);
int j = *((int*) reg);
int ans = i * j;
*((int*) reg) = ans;
}
void muli(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
int i = *((int*) src);
int j = *((int*) des);
int ans = i * j;
*((int*) des) = ans;
}
void mulf(double i, Reg r) {
char* reg = getReg(r);
float j = *((float*) reg);
float ans = ((float)i) * j;
*((float*) reg) = ans;
}
void mulf(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
float i = *((float*) src);
float j = *((float*) des);
float ans = i * j;
*((float*) des) = ans;
}
void divi(int i, Reg r) {
char* reg = getReg(r);
int j = *((int*) reg);
int ans = i / j;
*((int*) reg) = ans;
}
void divi(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
int i = *((int*) src);
int j = *((int*) des);
int ans = i / j;
*((int*) des) = ans;
}
void divf(double i, Reg r) {
char* reg = getReg(r);
float j = *((float*) reg);
float ans = ((float)i) / j;
*((float*) reg) = ans;
}
void divf(Reg rSrc, Reg rDes) {
char* src = getReg(rSrc);
char* des = getReg(rDes);
float i = *((float*) src);
float j = *((float*) des);
float ans = i / j;
*((float*) des) = ans;
}
void cmpi(Reg r1, Reg r2) {
char* reg1 = getReg(r1);
char* reg2 = getReg(r2);
int val1 = *((int*) reg1);
int val2 = *((int*) reg2);
if (val1 == val2)
_flag = 0;
else if (val1 < val2)
_flag = -1;
else
_flag = 1;
}
void cmpi(int val1, Reg r2) {
char* reg2 = getReg(r2);
int val2 = *((int*) reg2);
if (val1 == val2)
_flag = 0;
else if (val1 < val2)
_flag = -1;
else
_flag = 1;
}
void cmpf(Reg r1, Reg r2) {
char* reg1 = getReg(r1);
char* reg2 = getReg(r2);
float val1 = *((float*) reg1);
float val2 = *((float*) reg2);
if (val1 == val2)
_flag = 0;
else if (val1 < val2)
_flag = -1;
else
_flag = 1;
}
void cmpf(double val1, Reg r2) {
char* reg2 = getReg(r2);
float val2 = *((float*) reg2);
if (((float)val1) == val2)
_flag = 0;
else if (((float)val1) < val2)
_flag = -1;
else
_flag = 1;
}
void pushi(int val) {
*((char **) _esp) -= I;
**((int**) _esp) = val;
}
void pushi(Reg r) {
char* reg = getReg(r);
*((char **) _esp) -= I;
int val = *((int*) reg);
**((int **) _esp) = val;
}
void pushf(double val) {
*((char **) _esp) -= F;
**((float**) _esp) = (float)val;
}
void pushf(Reg r) {
char* reg = getReg(r);
*((char **) _esp) -= F;
float val = *((float*) reg);
**((float **) _esp) = val;
}
// Pops 'i' integers from the stack
void popi(int i) {
*((char **) _esp) += i * I;
}
// Pops 'i' number of floats from the stack
void popf(int i) {
*((char **) _esp) += i * F;
}
// Register indirection operator
char* ind(Reg r) {
char* reg = getReg(r);
return ((*((char**) (reg))));
}
// Register indirection operator
char* ind(Reg r, int offset) {
char* reg = getReg(r);
return ((*((char**) (reg))) + offset);
}
// Register indirection operator. Second register holds the integer offet from base register r
char* ind(Reg r, Reg offset) {
char* reg = getReg(r);
int intOffset = *((int*)getReg(offset));
return ((*((char**) (reg))) + intOffset);
}
// Special print methods
void print_int(Reg r) {
char* reg = getReg(r);
int val = *((int*) reg);
cout << val;
}
void print_int(int i) {
cout << i;
}
void print_float(Reg r) {
char* reg = getReg(r);
float val = *((float*) reg);
cout << val;
}
void print_float(double i) {
cout << ((float)i);
}
void print_char(Reg r) {
char* reg = getReg(r);
char val = *((char*) reg);
cout << val;
}
void print_char(char val) {
cout << val;
}
void print_string(Reg r) {
char* reg = getReg(r);
cout << (char*) reg;
}
void print_string(char* val) {
cout << val;
}
CMachineBase() {
I = sizeof(int);
F = sizeof(float);
P = sizeof(char*);
int max = F>I?F:I;
max = max>P?max:P;
_flag = 0;
_eax = new char[max];
_ebx = new char[max];
_ecx = new char[max];
_edx = new char[max];
_ebp = new char[max];
_esp = new char[max];
_edi = new char[max];
_esi = new char[max];
*((char**) _ebp) = &_stack[STACK_SIZE - 1];
*((char**) _esp) = &_stack[STACK_SIZE - 1];
}
virtual ~CMachineBase() {
delete[] _eax;
delete[] _ebx;
delete[] _ecx;
delete[] _edx;
delete[] _ebp;
delete[] _esp;
delete[] _edi;
delete[] _esi;
}
virtual void main() {
}
public:
void execute() {
this->main();
}
private:
char *_eax, *_ebx, *_ecx, *_edx, *_esp, *_ebp, *_edi, *_esi;
char _stack[STACK_SIZE];
char* getReg(Reg r) {
switch (r) {
case eax:
return _eax;
case ebx:
return _ebx;
case ecx:
return _ecx;
case edx:
return _edx;
case esp:
return _esp;
case ebp:
return _ebp;
case edi:
return _edi;
case esi:
return _esi;
default:
return (char*) 0;
}
}
};
class CMachine: public CMachineBase {
#include "code.asm"
};
int main() {
CMachine M;
M.execute();
}
| [
"rampsbb27@gmail.com"
] | rampsbb27@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.