hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d0d0058950a4176a24de8d223669ec2d476de9d2
| 1,091
|
hpp
|
C++
|
include/Nyengine/geometry/Point.hpp
|
NyantasticUwU/nyengine
|
b6a47d2bfb101366eeda1b318e66f09d37317688
|
[
"MIT"
] | 2
|
2021-12-26T05:10:41.000Z
|
2022-01-30T19:51:23.000Z
|
include/Nyengine/geometry/Point.hpp
|
NyantasticUwU/Nyengine
|
b6a47d2bfb101366eeda1b318e66f09d37317688
|
[
"MIT"
] | null | null | null |
include/Nyengine/geometry/Point.hpp
|
NyantasticUwU/Nyengine
|
b6a47d2bfb101366eeda1b318e66f09d37317688
|
[
"MIT"
] | null | null | null |
#ifndef NYENGINE_GEOMETRY_POINT_HPP_INCLUDED
#define NYENGINE_GEOMETRY_POINT_HPP_INCLUDED
#include "../type/types.hpp"
/// Contains Nyengine geometry helpers.
namespace nyengine::geometry
{
/// Represents a 2D point.
template <typename T>
struct Point2D
{
T x;
T y;
};
/// Point2D represented by signed integral type.
using Point2DI = Point2D<type::int32_dynamic_t>;
/// Point2D represented by unsigned integral type.
using Point2DU = Point2D<type::uint32_dynamic_t>;
/// Point2D represented by floating point type.
using Point2DF = Point2D<type::float32_dynamic_t>;
/// Represents a 3D point.
template <typename T>
struct Point3D
{
T x;
T y;
T z;
};
/// Point3D represented by signed integral type.
using Point3DI = Point3D<type::int32_dynamic_t>;
/// Point3D represented by unsigned integral type.
using Point3DU = Point3D<type::uint32_dynamic_t>;
/// Point3D represented by floating point type.
using Point3DF = Point3D<type::float32_dynamic_t>;
}
#endif
| 26.609756
| 54
| 0.678277
|
NyantasticUwU
|
d0d458081e465741613614c4084425fa51ef7a5b
| 491
|
hpp
|
C++
|
src/Engine/Scene/GeometrySystem.hpp
|
Yasoo31/Radium-Engine
|
e22754d0abe192207fd946509cbd63c4f9e52dd4
|
[
"Apache-2.0"
] | 78
|
2017-12-01T12:23:22.000Z
|
2022-03-31T05:08:09.000Z
|
src/Engine/Scene/GeometrySystem.hpp
|
neurodiverseEsoteric/Radium-Engine
|
ebebc29d889a9d32e0637e425e589e403d8edef8
|
[
"Apache-2.0"
] | 527
|
2017-09-25T13:05:32.000Z
|
2022-03-31T18:47:44.000Z
|
src/Engine/Scene/GeometrySystem.hpp
|
neurodiverseEsoteric/Radium-Engine
|
ebebc29d889a9d32e0637e425e589e403d8edef8
|
[
"Apache-2.0"
] | 48
|
2018-01-04T22:08:08.000Z
|
2022-03-03T08:13:41.000Z
|
#pragma once
#include <Engine/Scene/System.hpp>
namespace Ra {
namespace Engine {
namespace Scene {
class RA_ENGINE_API GeometrySystem : public System
{
public:
GeometrySystem();
~GeometrySystem() override = default;
void handleAssetLoading( Entity* entity, const Ra::Core::Asset::FileData* fileData ) override;
void generateTasks( Ra::Core::TaskQueue* taskQueue, const FrameInfo& frameInfo ) override;
};
} // namespace Scene
} // namespace Engine
} // namespace Ra
| 21.347826
| 98
| 0.725051
|
Yasoo31
|
d0d750ac8d8d08fd75030c52baa1dadb284b7aef
| 31,939
|
cc
|
C++
|
io/reader_test.cc
|
chronos-tachyon/mojo
|
8d268932dd927a24a2b5de167d63869484e1433a
|
[
"MIT"
] | 3
|
2017-04-24T07:00:59.000Z
|
2020-04-13T04:53:06.000Z
|
io/reader_test.cc
|
chronos-tachyon/mojo
|
8d268932dd927a24a2b5de167d63869484e1433a
|
[
"MIT"
] | 1
|
2017-01-10T04:23:55.000Z
|
2017-01-10T04:23:55.000Z
|
io/reader_test.cc
|
chronos-tachyon/mojo
|
8d268932dd927a24a2b5de167d63869484e1433a
|
[
"MIT"
] | 1
|
2020-04-13T04:53:07.000Z
|
2020-04-13T04:53:07.000Z
|
// Copyright © 2016 by Donald King <chronos@chronos-tachyon.net>
// Available under the MIT License. See LICENSE for details.
#include "gtest/gtest.h"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <condition_variable>
#include <mutex>
#include <thread>
#include "base/cleanup.h"
#include "base/fd.h"
#include "base/logging.h"
#include "base/result_testing.h"
#include "event/task.h"
#include "io/reader.h"
#include "io/util.h"
#include "io/writer.h"
namespace {
class TempFile {
public:
TempFile() {
CHECK_OK(base::make_tempfile(&path_, &fd_, "mojo-io-reader-test.XXXXXX"));
}
~TempFile() noexcept {
::unlink(path_.c_str());
}
const std::string& path() const noexcept { return path_; }
const base::FD fd() const noexcept { return fd_; }
void rewind() {
CHECK_OK(base::seek(nullptr, fd_, 0, SEEK_SET));
}
void truncate() {
CHECK_OK(base::truncate(fd_));
}
void write(const char* ptr, std::size_t len) {
CHECK_OK(base::write_exactly(fd_, ptr, len, path_.c_str()));
}
void write(base::StringPiece sp) {
write(sp.data(), sp.size());
}
void set(const char* ptr, std::size_t len) {
rewind();
truncate();
write(ptr, len);
rewind();
}
void set(base::StringPiece sp) {
set(sp.data(), sp.size());
}
TempFile(const TempFile&) = delete;
TempFile(TempFile&&) = delete;
TempFile& operator=(const TempFile&) = delete;
TempFile& operator=(TempFile&&) = delete;
private:
std::string path_;
base::FD fd_;
};
} // anonymous namespace
// StringReader {{{
TEST(StringReader, ZeroThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, OneThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, ZeroFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, OneFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, ThreeFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::stringreader("abcdef");
r.read(&task, buf, &len, 3, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(StringReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
char buf[16];
std::size_t len = 0;
std::size_t copied = 42;
r = io::stringreader("abcdefg");
w = io::bufferwriter(buf, sizeof(buf), &len);
r.write_to(&task, &copied, ~std::size_t(0), w);
EXPECT_OK(task.result());
EXPECT_EQ(7U, copied);
EXPECT_EQ(7U, len);
EXPECT_EQ("abcdefg", std::string(buf, len));
}
TEST(StringReader, Close) {
event::Task task;
io::Reader r = io::stringreader("");
r.close(&task);
EXPECT_OK(task.result());
task.reset();
r.close(&task);
EXPECT_FAILED_PRECONDITION(task.result());
}
// }}}
// BufferReader {{{
TEST(BufferReader, ZeroThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 3);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, OneThree) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("def", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, ZeroFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 0, 4);
EXPECT_OK(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, OneFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, ThreeFour) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::bufferreader("abcdef", 6);
r.read(&task, buf, &len, 3, 4);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ef", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 3, 4);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(BufferReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
char buf[16];
std::size_t len = 0;
std::size_t copied = 42;
r = io::bufferreader("abcdefg", 7);
w = io::bufferwriter(buf, sizeof(buf), &len);
r.write_to(&task, &copied, ~std::size_t(0), w);
EXPECT_OK(task.result());
EXPECT_EQ(7U, copied);
EXPECT_EQ(7U, len);
EXPECT_EQ("abcdefg", std::string(buf, len));
}
TEST(BufferReader, Close) {
event::Task task;
io::Reader r = io::bufferreader("", 0);
r.close(&task);
EXPECT_OK(task.result());
task.reset();
r.close(&task);
EXPECT_FAILED_PRECONDITION(task.result());
}
// }}}
// IgnoreCloseReader {{{
TEST(IgnoreCloseReader, Close) {
int n = 0;
auto rfn = [](event::Task* task, char* ptr, std::size_t* len, std::size_t min,
std::size_t max, const base::Options& o) {
*len = 0;
if (task->start()) task->finish(base::Result::not_implemented());
};
auto cfn = [&n](event::Task* task, const base::Options& o) {
++n;
if (task->start()) task->finish_ok();
};
io::Reader r;
event::Task task;
r = io::reader(rfn, cfn);
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(1, n);
task.reset();
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(2, n);
r = io::ignore_close(std::move(r));
task.reset();
r.close(&task);
EXPECT_OK(task.result());
EXPECT_EQ(2, n);
}
// }}}
// LimitedReader {{{
TEST(LimitedReader, BigRead) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 16);
EXPECT_OK(task.result());
EXPECT_EQ(4U, len);
EXPECT_EQ("abcd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 16);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, SmallReadAligned) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 2);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("ab", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 2);
EXPECT_OK(task.result());
EXPECT_EQ(2U, len);
EXPECT_EQ("cd", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 2);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, SmallReadUnaligned) {
io::Reader r;
event::Task task;
char buf[16];
std::size_t len;
r = io::limited_reader(io::stringreader("abcdef"), 4);
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(3U, len);
EXPECT_EQ("abc", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_OK(task.result());
EXPECT_EQ(1U, len);
EXPECT_EQ("d", std::string(buf, len));
task.reset();
r.read(&task, buf, &len, 1, 3);
EXPECT_EOF(task.result());
EXPECT_EQ(0U, len);
}
TEST(LimitedReader, WriteTo) {
io::Reader r;
io::Writer w;
event::Task task;
std::string in(8192, 'a');
std::string out;
std::size_t n = 0;
r = io::limited_reader(io::stringreader(in), 4096);
w = io::stringwriter(&out);
r.write_to(&task, &n, 4096, w);
EXPECT_OK(task.result());
EXPECT_EQ(4096U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 4096, w);
EXPECT_OK(task.result());
EXPECT_EQ(0U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
out.clear();
r = io::limited_reader(io::stringreader(in), 4096);
w = io::stringwriter(&out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(3072U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(1024U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
task.reset();
r.write_to(&task, &n, 3072, w);
EXPECT_OK(task.result());
EXPECT_EQ(0U, n);
EXPECT_EQ(in.substr(0, out.size()), out);
}
// }}}
// NullReader {{{
TEST(NullReader, Read) {
io::Reader r = io::nullreader();
base::Options o;
char buf[16];
std::size_t n = 42;
EXPECT_OK(r.read(buf, &n, 0, sizeof(buf), o));
EXPECT_EQ(0U, n);
n = 42;
EXPECT_EOF(r.read(buf, &n, 1, sizeof(buf), o));
EXPECT_EQ(0U, n);
}
// }}}
// ZeroReader {{{
TEST(ZeroReader, Read) {
io::Reader r = io::zeroreader();
base::Options o;
char buf[16];
std::size_t n = 42;
std::string expected;
expected.assign(sizeof(buf), '\0');
EXPECT_OK(r.read(buf, &n, 0, sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
n = 42;
EXPECT_OK(r.read(buf, &n, 1, sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
n = 42;
EXPECT_OK(r.read(buf, &n, sizeof(buf), sizeof(buf), o));
EXPECT_EQ(sizeof(buf), n);
EXPECT_EQ(expected, std::string(buf, n));
}
// }}}
// FDReader {{{
static void TestFDReader_Read(const base::Options& o) {
base::Pipe pipe;
ASSERT_OK(base::make_pipe(&pipe));
LOG(INFO) << "made pipes";
std::mutex mu;
std::condition_variable cv;
std::size_t x = 0, y = 0;
std::thread t1([&pipe, &mu, &cv, &x, &y] {
auto lock = base::acquire_lock(mu);
while (x < 1) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "abcd", 4, "pipe"));
LOG(INFO) << "wrote: abcd";
while (x < 2) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "efgh", 4, "pipe"));
LOG(INFO) << "wrote: efgh";
++y;
cv.notify_all();
LOG(INFO) << "woke T0: y = " << y;
while (x < 3) cv.wait(lock);
LOG(INFO) << "T1 awoken: x = " << x;
EXPECT_OK(base::write_exactly(pipe.write, "ijkl", 4, "pipe"));
LOG(INFO) << "wrote: ijkl";
});
LOG(INFO) << "spawned thread";
io::Reader r = io::fdreader(pipe.read);
LOG(INFO) << "made fdreader";
char buf[8];
std::size_t n;
EXPECT_OK(r.read(buf, &n, 0, 8, o));
EXPECT_EQ(0U, n);
LOG(INFO) << "read zero bytes";
auto lock = base::acquire_lock(mu);
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
lock.unlock();
LOG(INFO) << "initiating read #1";
EXPECT_OK(r.read(buf, &n, 1, 8, o));
LOG(INFO) << "read #1 complete";
EXPECT_EQ(4U, n);
EXPECT_EQ("abcd", std::string(buf, n));
lock.lock();
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
while (y < 1) cv.wait(lock);
LOG(INFO) << "T0 awoken: y = " << y;
lock.unlock();
event::Task task;
LOG(INFO) << "initiating read #2";
r.read(&task, buf, &n, 8, 8, o);
lock.lock();
++x;
cv.notify_all();
LOG(INFO) << "woke T1: x = " << x;
lock.unlock();
event::wait(io::get_manager(o), &task);
LOG(INFO) << "read #2 complete";
EXPECT_OK(task.result());
EXPECT_EQ(8U, n);
EXPECT_EQ("efghijkl", std::string(buf, n));
t1.join();
base::log_flush();
}
static void TestFDReader_WriteTo(const base::Options& o) {
TempFile tempfile;
for (std::size_t i = 0; i < 16; ++i) {
std::string tmp;
tmp.assign(4096, 'A' + i);
tempfile.write(tmp);
}
tempfile.rewind();
LOG(INFO) << "temp file is ready";
base::SocketPair s;
ASSERT_OK(base::make_socketpair(&s, AF_UNIX, SOCK_STREAM, 0));
ASSERT_OK(base::set_blocking(s.right, true));
LOG(INFO) << "socketpair is ready";
std::mutex mu;
std::condition_variable cv;
bool ready = false;
std::size_t sunk = 0;
std::thread t([&s, &mu, &cv, &ready, &sunk] {
base::Result r;
std::vector<char> buf;
std::string expected;
std::size_t i = 0;
buf.resize(4096);
expected.resize(4096);
auto lock = base::acquire_lock(mu);
while (!ready) cv.wait(lock);
LOG(INFO) << "sink thread running";
while (true) {
expected.assign(4096, 'A' + i);
r = base::read_exactly(s.right, buf.data(), buf.size(), "socket");
if (!r) break;
EXPECT_EQ(expected, std::string(buf.data(), buf.size()));
sunk += buf.size();
++i;
}
EXPECT_EOF(r);
});
LOG(INFO) << "thread launched";
io::Reader r = io::fdreader(tempfile.fd());
io::Writer w = io::fdwriter(s.left);
event::Task task;
std::size_t n;
io::copy(&task, &n, w, r, o);
auto lock = base::acquire_lock(mu);
ready = true;
cv.notify_all();
lock.unlock();
event::wait(io::get_manager(o), &task);
LOG(INFO) << "task done";
EXPECT_OK(task.result());
EXPECT_EQ(16U * 4096U, n);
ASSERT_OK(base::shutdown(s.left, SHUT_WR));
t.join();
LOG(INFO) << "thread done";
EXPECT_EQ(sunk, n);
base::log_flush();
}
TEST(FDReader, AsyncRead) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestFDReader_Read(o);
m.shutdown();
}
TEST(FDReader, ThreadedRead) {
event::ManagerOptions mo;
mo.set_minimal_threaded_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestFDReader_Read(o);
m.shutdown();
}
TEST(FDReader, WriteToFallback) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::read_write;
TestFDReader_WriteTo(o);
m.shutdown();
}
TEST(FDReader, WriteToSendfile) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::sendfile;
TestFDReader_WriteTo(o);
m.shutdown();
}
TEST(FDReader, WriteToSplice) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
o.get<io::Options>().transfer_mode = io::TransferMode::splice;
TestFDReader_WriteTo(o);
m.shutdown();
}
// }}}
// MultiReader {{{
void TestMultiReader_LineUp(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string c = "ABCDEFGH";
std::string d = "!@#$%^&*";
std::string expected;
expected.reserve(8 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[8];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 8, 8, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_Half(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string expected;
expected.reserve(8 * 2);
expected.append(a);
expected.append(b);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b),
});
base::Result result;
char buf[4];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 4, 4, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_Double(const base::Options& o) {
std::string a = "01234567";
std::string b = "abcdefgh";
std::string c = "ABCDEFGH";
std::string d = "!@#$%^&*";
std::string expected;
expected.reserve(8 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[16];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 16, 16, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader_OffAxis(const base::Options& o) {
std::string a = "01234";
std::string b = "abcde";
std::string c = "ABCDE";
std::string d = "!@#$%";
std::string expected;
expected.reserve(5 * 4);
expected.append(a);
expected.append(b);
expected.append(c);
expected.append(d);
io::Reader r = io::multireader({
io::stringreader(a), io::stringreader(b), io::stringreader(c),
io::stringreader(d),
});
base::Result result;
char buf[8];
std::size_t n;
std::string actual;
while (true) {
result = r.read(buf, &n, 8, 8, o);
actual.append(buf, n);
if (!result) break;
}
EXPECT_EOF(result);
EXPECT_EQ(expected, actual);
}
void TestMultiReader(const base::Options& o, const char* what) {
LOG(INFO) << "[TestMultiReader_LineUp:" << what << "]";
TestMultiReader_LineUp(o);
LOG(INFO) << "[TestMultiReader_Half:" << what << "]";
TestMultiReader_Half(o);
LOG(INFO) << "[TestMultiReader_Double:" << what << "]";
TestMultiReader_Double(o);
LOG(INFO) << "[TestMultiReader_OffAxis:" << what << "]";
TestMultiReader_OffAxis(o);
LOG(INFO) << "[Done:" << what << "]";
base::log_flush();
}
TEST(MultiReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestMultiReader(o, "async");
m.shutdown();
}
TEST(MultiReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestMultiReader(o, "threaded");
m.shutdown();
}
// }}}
// BufferedReader {{{
static io::Reader wrap(bool do_buffer, io::Reader r) {
if (do_buffer) r = io::bufferedreader(std::move(r));
return r;
};
static void TestBufferedReader_Fixed(const base::Options& o, bool do_buffer, const char* what) {
constexpr unsigned char kBytes[] = {
0x00, // 8-bit datum #0
0x7f, // 8-bit datum #1
0x81, // 8-bit datum #2
0xff, // 8-bit datum #3
0x00, 0x00, // 16-bit datum #0
0x7f, 0xff, // 16-bit datum #1
0x80, 0x01, // 16-bit datum #2
0xff, 0xff, // 16-bit datum #3
0x00, 0x00, 0x00, 0x00, // 32-bit datum #0
0x7f, 0xff, 0xff, 0xff, // 32-bit datum #1
0x80, 0x00, 0x00, 0x01, // 32-bit datum #2
0xff, 0xff, 0xff, 0xff, // 32-bit datum #3
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 64-bit datum #0
0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 64-bit datum #1
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // 64-bit datum #2
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 64-bit datum #3
};
LOG(INFO) << "[TestBufferedReader_Fixed:" << what << ":unsigned]";
TempFile tempfile;
tempfile.set(reinterpret_cast<const char*>(kBytes), sizeof(kBytes));
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
uint8_t u8 = 0;
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x00U, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x7fU, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0x81U, u8);
EXPECT_OK(r.read_u8(&u8, o));
EXPECT_EQ(0xffU, u8);
uint16_t u16 = 0;
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x0000U, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x7fffU, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0x8001U, u16);
EXPECT_OK(r.read_u16(&u16, base::kBigEndian, o));
EXPECT_EQ(0xffffU, u16);
uint32_t u32 = 0;
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x00000000U, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffU, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0x80000001U, u32);
EXPECT_OK(r.read_u32(&u32, base::kBigEndian, o));
EXPECT_EQ(0xffffffffU, u32);
uint64_t u64 = 0;
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x0000000000000000ULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffffffffffULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0x8000000000000001ULL, u64);
EXPECT_OK(r.read_u64(&u64, base::kBigEndian, o));
EXPECT_EQ(0xffffffffffffffffULL, u64);
EXPECT_EOF(r.read_u8(&u8, o));
LOG(INFO) << "[TestBufferedReader_Fixed:" << what << ":signed]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
int8_t s8 = 0;
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(0x00, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(0x7f, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(-0x7f, s8);
EXPECT_OK(r.read_s8(&s8, o));
EXPECT_EQ(-0x01, s8);
int16_t s16 = 0;
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(0x0000, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(0x7fff, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(-0x7fff, s16);
EXPECT_OK(r.read_s16(&s16, base::kBigEndian, o));
EXPECT_EQ(-0x0001, s16);
int32_t s32 = 0;
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(0x00000000, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(0x7fffffff, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(-0x7fffffff, s32);
EXPECT_OK(r.read_s32(&s32, base::kBigEndian, o));
EXPECT_EQ(-0x00000001, s32);
int64_t s64 = 0;
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(0x0000000000000000LL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(0x7fffffffffffffffLL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(-0x7fffffffffffffffLL, s64);
EXPECT_OK(r.read_s64(&s64, base::kBigEndian, o));
EXPECT_EQ(-0x0000000000000001LL, s64);
EXPECT_EOF(r.read_u8(&u8, o));
}
static void TestBufferedReader_Varint(const base::Options& o, bool do_buffer, const char* what) {
constexpr unsigned char kBytes[] = {
0x00, // 0, 0, 0
0x01, // 1, 1, -1
0x02, // 2, 2, 1
0x03, // 3, 3, -2
0x04, // 4, 4, 2
0x7f, // 127, 127, -64
0xac, 0x02, // 300, 300, 150
0xff, 0x7f, // 16383, 16383, -8192
0xff, 0xff, 0x03, // 65535, 65535, -32768
0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x01, // UINT64MAX - 1, -2, INT64MAX
};
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":unsigned]";
TempFile tempfile;
tempfile.set(reinterpret_cast<const char*>(kBytes), sizeof(kBytes));
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
uint64_t u64;
int64_t s64;
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(0U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(1U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(2U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(3U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(4U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(127U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(300U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(16383U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(65535U, u64);
EXPECT_OK(r.read_uvarint(&u64, o));
EXPECT_EQ(0xfffffffffffffffeULL, u64);
EXPECT_EOF(r.read_uvarint(&u64, o));
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":signed]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(0, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(1, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(2, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(3, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(4, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(127, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(300, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(16383, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(65535, s64);
EXPECT_OK(r.read_svarint(&s64, o));
EXPECT_EQ(-2, s64);
EXPECT_EOF(r.read_svarint(&s64, o));
LOG(INFO) << "[TestBufferedReader_Varint:" << what << ":zigzag]";
tempfile.rewind();
r = wrap(do_buffer, io::fdreader(tempfile.fd()));
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(0, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-1, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(1, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-2, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(2, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-64, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(150, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-8192, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(-32768, s64);
EXPECT_OK(r.read_svarint_zigzag(&s64, o));
EXPECT_EQ(0x7fffffffffffffffLL, s64);
EXPECT_EOF(r.read_svarint_zigzag(&s64, o));
}
static void TestBufferedReader_ReadLine(const base::Options& o, bool do_buffer, const char* what) {
constexpr char kBytes[] =
"Line 1\n"
"Line 2\r\n"
"Line 3 is a very long line\r\n"
"Line 4";
LOG(INFO) << "[TestBufferedReader_ReadLine:" << what << "]";
TempFile tempfile;
tempfile.set(kBytes, sizeof(kBytes) - 1);
io::Reader r = wrap(do_buffer, io::fdreader(tempfile.fd()));
std::string str;
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 1\n", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 2\r\n", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("Line 3 is ", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("a very lon", str);
EXPECT_OK(r.readline(&str, 10, o));
EXPECT_EQ("g line\r\n", str);
EXPECT_EOF(r.readline(&str, 10, o));
EXPECT_EQ("Line 4", str);
}
static void TestBufferedReader(const base::Options& o, bool do_buffer, const char* what) {
TestBufferedReader_Fixed(o, do_buffer, what);
TestBufferedReader_Varint(o, do_buffer, what);
TestBufferedReader_ReadLine(o, do_buffer, what);
base::log_flush();
}
TEST(BufferedReader, Inline) {
event::ManagerOptions mo;
mo.set_inline_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/inline");
m.shutdown();
}
TEST(BufferedReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/async");
m.shutdown();
}
TEST(BufferedReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, true, "buffered/threaded");
m.shutdown();
}
TEST(UnbufferedReader, Inline) {
event::ManagerOptions mo;
mo.set_inline_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/inline");
m.shutdown();
}
TEST(UnbufferedReader, Async) {
event::ManagerOptions mo;
mo.set_async_mode();
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/async");
m.shutdown();
}
TEST(UnbufferedReader, Threaded) {
event::ManagerOptions mo;
mo.set_threaded_mode();
mo.set_num_pollers(2);
mo.dispatcher().set_num_workers(2);
event::Manager m;
ASSERT_OK(event::new_manager(&m, mo));
base::Options o;
o.get<io::Options>().manager = m;
TestBufferedReader(o, false, "unbuffered/threaded");
m.shutdown();
}
// }}}
static void init() __attribute__((constructor));
static void init() { base::log_stderr_set_level(VLOG_LEVEL(6)); }
| 23.96024
| 99
| 0.616832
|
chronos-tachyon
|
d0d849b10ed26b212ddc9b843f578b538bed3146
| 5,099
|
cpp
|
C++
|
launcher/src/launcher/ExecutableLoader.cpp
|
norelock/Project-MP-1
|
31dbb5c74b29a47df4cf41280887a66794fdc5ff
|
[
"MIT"
] | 1
|
2022-02-19T15:52:29.000Z
|
2022-02-19T15:52:29.000Z
|
launcher/src/launcher/ExecutableLoader.cpp
|
cleoppa/norasa
|
6f8d697922dca2fcc42a5830a384e790c687833a
|
[
"MIT"
] | 2
|
2020-11-08T08:12:41.000Z
|
2022-01-08T07:20:45.000Z
|
launcher/src/launcher/ExecutableLoader.cpp
|
cleoppa/norasa
|
6f8d697922dca2fcc42a5830a384e790c687833a
|
[
"MIT"
] | 3
|
2020-03-23T06:56:35.000Z
|
2021-06-06T02:30:06.000Z
|
#include "stdafx.h"
/*
#pragma bss_seg(".cdummy")
char dummy_seg[0x2500000];
#pragma data_seg(".zdata")
char zdata[0x50000] = { 1 };
*/
ExecutableLoader::ExecutableLoader(const BYTE* origBinary)
{
m_origBinary = origBinary;
m_loadLimit = UINT_MAX;
SetLibraryLoader([](const char* name)
{
return LoadLibraryA(name);
});
SetFunctionResolver([](HMODULE module, const char* name)
{
return reinterpret_cast<LPVOID>(GetProcAddress(module, name));
});
}
std::wstring s2ws(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
bool ExecutableLoader::LoadDependentLibraries(IMAGE_NT_HEADERS* ntHeader)
{
IMAGE_DATA_DIRECTORY* importDirectory = &ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
IMAGE_IMPORT_DESCRIPTOR* descriptor = GetTargetRVA<IMAGE_IMPORT_DESCRIPTOR>(importDirectory->VirtualAddress);
while (descriptor->Name)
{
const char* name = GetTargetRVA<char>(descriptor->Name);
HMODULE module = ResolveLibrary(name);
if (!module)
{
std::ostringstream os;
os << GetLastError();
std::string str = "Could not load dependent module " + std::string(name) + ". Error code: " + os.str();
MessageBox(NULL, s2ws(str).c_str(), L"Launch error", MB_OK);
//FatalError(va("Could not load dependent module %s. Error code was %i.", name, GetLastError()));
return false;
}
if (reinterpret_cast<unsigned>(module) == 0xFFFFFFFF)
{
descriptor++;
continue;
}
auto nameTableEntry = GetTargetRVA<unsigned>(descriptor->OriginalFirstThunk);
auto addressTableEntry = GetTargetRVA<unsigned>(descriptor->FirstThunk);
while (*nameTableEntry)
{
FARPROC function;
const char* functionName;
if (IMAGE_SNAP_BY_ORDINAL(*nameTableEntry))
{
function = reinterpret_cast<FARPROC>(
ResolveLibraryFunction(module, MAKEINTRESOURCEA(IMAGE_ORDINAL(*nameTableEntry))));
char buff[256];
snprintf(buff, sizeof(buff), "#%d", IMAGE_ORDINAL(*nameTableEntry));
std::string buffAsStdStr = buff;
functionName = buffAsStdStr.c_str();
}
else
{
auto import = GetTargetRVA<IMAGE_IMPORT_BY_NAME>(*nameTableEntry);
function = reinterpret_cast<FARPROC>(ResolveLibraryFunction(module, (const char*)import->Name));
functionName = static_cast<const char*>(import->Name);
}
if (!function)
{
char pathName[MAX_PATH];
GetModuleFileNameA(module, pathName, sizeof(pathName));
MessageBox(NULL, L"Could not load function in dependent module", L"Launch error", MB_OK);
//FatalError(va("Could not load function %s in dependent module %s (%s).", functionName, name, pathName));
return false;
}
*addressTableEntry = reinterpret_cast<unsigned>(function);
nameTableEntry++;
addressTableEntry++;
}
descriptor++;
}
return true;
}
void ExecutableLoader::LoadSection(IMAGE_SECTION_HEADER* section)
{
void* targetAddress = GetTargetRVA<uint8_t>(section->VirtualAddress);
const void* sourceAddress = m_origBinary + section->PointerToRawData;
if ((uintptr_t)targetAddress >= m_loadLimit)
{
MessageBox(NULL, L"Exceeded load limit.", L"Launch error", MB_OK);
//FatalError("Exceeded load limit.");
return;
}
if (section->SizeOfRawData > 0)
{
uint32_t sizeOfData = section->SizeOfRawData < section->Misc.VirtualSize ? section->SizeOfRawData : section->Misc.VirtualSize;
DWORD oldProtect;
VirtualProtect(targetAddress, sizeOfData, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(targetAddress, sourceAddress, sizeOfData);
}
}
void ExecutableLoader::LoadSections(IMAGE_NT_HEADERS* ntHeader)
{
IMAGE_SECTION_HEADER* section = IMAGE_FIRST_SECTION(ntHeader);
for (int i = 0; i < ntHeader->FileHeader.NumberOfSections; i++)
{
// Load the given section into memory
LoadSection(section);
section++;
}
}
void ExecutableLoader::LoadIntoModule(HMODULE module)
{
m_executableHandle = module;
IMAGE_DOS_HEADER* header = (IMAGE_DOS_HEADER*)m_origBinary;
if (header->e_magic != IMAGE_DOS_SIGNATURE)
{
MessageBox(NULL, L"Cannot find dos signature.", L"Launch error", MB_OK);
return;
}
IMAGE_DOS_HEADER* sourceHeader = (IMAGE_DOS_HEADER*)module;
IMAGE_NT_HEADERS* sourceNtHeader = GetTargetRVA<IMAGE_NT_HEADERS>(sourceHeader->e_lfanew);
IMAGE_NT_HEADERS* ntHeader = (IMAGE_NT_HEADERS*)(m_origBinary + header->e_lfanew);
LoadSections(ntHeader);
LoadDependentLibraries(ntHeader);
m_entryPoint = GetTargetRVA<void>(ntHeader->OptionalHeader.AddressOfEntryPoint);
DWORD oldProtect;
VirtualProtect(sourceNtHeader, 0x1000, PAGE_EXECUTE_READWRITE, &oldProtect);
sourceNtHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
}
HMODULE ExecutableLoader::ResolveLibrary(const char* name)
{
return m_libraryLoader(name);
}
LPVOID ExecutableLoader::ResolveLibraryFunction(HMODULE module, const char* name)
{
return m_functionResolver(module, name);
}
| 28.171271
| 147
| 0.741322
|
norelock
|
d0dd4f6265b888ac8b8da9558df840ec2de1453f
| 2,709
|
cpp
|
C++
|
Source/Arnoldi/Select_Shifts.cpp
|
evstigneevnm/NS3DPeriodic
|
094c168f153e36f00ac9103675416ddb9ee6b586
|
[
"BSD-3-Clause"
] | null | null | null |
Source/Arnoldi/Select_Shifts.cpp
|
evstigneevnm/NS3DPeriodic
|
094c168f153e36f00ac9103675416ddb9ee6b586
|
[
"BSD-3-Clause"
] | null | null | null |
Source/Arnoldi/Select_Shifts.cpp
|
evstigneevnm/NS3DPeriodic
|
094c168f153e36f00ac9103675416ddb9ee6b586
|
[
"BSD-3-Clause"
] | null | null | null |
#include "Select_Shifts.h"
#include "Products.h"
#include "LAPACK_routines.h"
void check_nans_H(int N, real *H){
for(int i=0;i<N;i++)
if(H[i]!=H[i]){
printf("\nNANs in H-matrix detected!!!\n");
}
}
int struct_cmp_by_value(const void *a, const void *b)
{
struct sort_struct *ia = (struct sort_struct *)a;
struct sort_struct *ib = (struct sort_struct *)b;
real val_a=ia->value;
real val_b=ib->value;
if(val_a>val_b)
return 1;
else if (val_a<val_b)
return -1;
else
return 0;
}
void get_sorted_index(int m, char which[2], real complex *eigenvaluesH, int *sorted_list){
sort_struct *eigs_struct=new sort_struct[m];
real complex *eigs_local=new real complex[m];
for(int i=0;i<m;i++){
real value=0.0;
if((which[0]=='L')&&(which[1]=='R'))
value=-creal(eigenvaluesH[i]);
else if((which[0]=='L')&&(which[1]=='M'))
value=-cabs(eigenvaluesH[i]);
eigs_struct[i].index=i;
eigs_struct[i].value=value;
eigs_local[i]=eigenvaluesH[i];
}
size_t structs_len = m;
qsort(eigs_struct, structs_len, sizeof(struct sort_struct), struct_cmp_by_value);
for(int i=0;i<m;i++){
int j=eigs_struct[i].index;
sorted_list[i]=j;
eigenvaluesH[i]=eigs_local[j];
}
delete [] eigs_struct;
delete [] eigs_local;
}
void filter_small_imags(int N, real complex *eigenvaluesH){
for(int i=0;i<N;i++){
real eig_imag=cimag(eigenvaluesH[i]);
real eig_real=creal(eigenvaluesH[i]);
if(fabsf(eig_imag)<Im_eig_tol)
eig_imag=0.0;
real complex Ctemp=eig_real+eig_imag*I;
eigenvaluesH[i]=Ctemp;
}
}
void select_shifts(int m, real *H, char which[2], real complex *eigenvectorsH, real complex *eigenvaluesH, real *ritz_vector){
real complex *HC=new real complex[m*m];
real complex *eigs_local=new real complex[m];
//real complex *eigvs_local=new real complex[m*m];
check_nans_H(m*m, H);
real_to_complex_matrix(m, m, H, HC);
MatrixComplexEigensystem(eigenvectorsH, eigs_local, HC, m);
//filter_small_imags(m, eigs_local);
sort_struct *eigs_struct=new sort_struct[m];
for(int i=0;i<m;i++){
real value=0.0;
if((which[0]=='L')&&(which[1]=='R'))
value=-creal(eigs_local[i]);
else if((which[0]=='L')&&(which[1]=='M'))
value=-cabs(eigs_local[i]);
eigs_struct[i].index=i;
eigs_struct[i].value=value;
}
size_t structs_len = m;
qsort(eigs_struct, structs_len, sizeof(struct sort_struct), struct_cmp_by_value);
for(int i=0;i<m;i++){
int j=eigs_struct[i].index;
eigenvaluesH[i]=eigs_local[j];
//for(int k=0;k<m;k++){
// eigenvectorsH[I2(k,i,m)]=eigvs_local[I2(k,j,m)];
//}
ritz_vector[i]=cabs(eigenvectorsH[I2(m-1,j,m)]);
}
delete [] eigs_struct;
delete [] HC;
delete [] eigs_local;
//delete [] eigvs_local;
}
| 20.216418
| 127
| 0.670727
|
evstigneevnm
|
d0e3f1cfbabbe3e3f5baa0e292ede09e18cea908
| 838
|
cpp
|
C++
|
Problems/0096. Unique Binary Search Trees.cpp
|
KrKush23/LeetCode
|
2a87420a65347a34fba333d46e1aa6224c629b7a
|
[
"MIT"
] | null | null | null |
Problems/0096. Unique Binary Search Trees.cpp
|
KrKush23/LeetCode
|
2a87420a65347a34fba333d46e1aa6224c629b7a
|
[
"MIT"
] | null | null | null |
Problems/0096. Unique Binary Search Trees.cpp
|
KrKush23/LeetCode
|
2a87420a65347a34fba333d46e1aa6224c629b7a
|
[
"MIT"
] | null | null | null |
class Solution {
vector<int> dp;
public:
int uniqueBST(int n) {
// BASE CASE
if (n == 0 or n == 1)
return 1;
// MEMOIZATION
if (dp[n] != -1)
return dp[n];
//RECURSIVE
int res{0};
for (int i = 1; i <= n; i++) { // selecting each node one by one
res += uniqueBST(i - 1) * uniqueBST(n - i); // will have (i-1)LEFT NODES and (n-i)RIGHT NODES
}
return dp[n] = res;
}
int numTrees(int n) {
// MEMOIZATION ================
dp.resize(n + 1, -1);
return uniqueBST(n);
// TABULAR ====================
//CATALAN NUMBERS
if (n < 2)
return n;
vector<int> dp(n + 1);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) // finding unique BSTs for i nodes
for (int j = 0; j < i; j++)
dp[i] += dp[j] * dp[i - j - 1]; //select each node one by oneas root..solving subproblems
return dp[n];
}
};
| 22.648649
| 96
| 0.52148
|
KrKush23
|
d0e8c437cc7f6fc0049650f97977094f121ea048
| 1,040
|
cpp
|
C++
|
CS Academy/Overlapping Matrices/28.57 points.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
CS Academy/Overlapping Matrices/28.57 points.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
CS Academy/Overlapping Matrices/28.57 points.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created:
* solution_verdict: 28.57 points language: C++
* run_time: 94 ms memory_used: 5492 KB
* problem:
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
int h,w,x,y,mat[1010][1010],ans[1010][1010],tmp[1010][1010];
int main()
{
cin>>h>>w>>x>>y;
for(int i=1;i<=h+x;i++)
{
for(int j=1;j<=w+y;j++)
{
cin>>mat[i][j];
}
}
for(int i=1;i<=h;i++)
{
if(i<=x)
{
for(int j=1;j<=w;j++)ans[i][j]=mat[i][j];
for(int j=1;j<=w;j++)tmp[i+x][j+y]=mat[i][j];
}
else
{
for(int j=1;j<=w;j++)ans[i][j]=mat[i][j]-tmp[i][j];
}
}
for(int i=1;i<=h;i++)
{
for(int j=1;j<=w;j++)cout<<ans[i][j]<<" ";
cout<<endl;
}
return 0;
}
| 26.666667
| 111
| 0.35
|
kzvd4729
|
d0eb0778f46b42091d041d80c65db5dbed3348ba
| 545
|
cpp
|
C++
|
src/enclave/ServiceProvider/KeyGen.cpp
|
brucechin/opaque
|
29e1755078412c46706608b17b4932ebd92d34b2
|
[
"Apache-2.0"
] | null | null | null |
src/enclave/ServiceProvider/KeyGen.cpp
|
brucechin/opaque
|
29e1755078412c46706608b17b4932ebd92d34b2
|
[
"Apache-2.0"
] | null | null | null |
src/enclave/ServiceProvider/KeyGen.cpp
|
brucechin/opaque
|
29e1755078412c46706608b17b4932ebd92d34b2
|
[
"Apache-2.0"
] | 1
|
2021-09-23T03:06:08.000Z
|
2021-09-23T03:06:08.000Z
|
#include "ServiceProvider.h"
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: ./keygen <public_key_cpp_file>\n");
return 1;
}
const char *private_key_path = "/home/lqp0562/opaque/private_key.pem";
if (!private_key_path) {
printf("Set $PRIVATE_KEY_PATH to the file generated by openssl ecparam -genkey, probably "
"called ${OPAQUE_HOME}/private_key.pem.");
return 1;
}
service_provider.load_private_key(private_key_path);
service_provider.export_public_key_code(argv[1]);
return 0;
}
| 27.25
| 94
| 0.695413
|
brucechin
|
d0ecd90e65a39df4df042ee391c3afe1a91f6e45
| 3,546
|
hpp
|
C++
|
Rx/v2/src/rxcpp/rx-test.hpp
|
guhwanbae/RxCpp
|
7f97aa901701343593869acad1ee5a02292f39cf
|
[
"Apache-2.0"
] | 1
|
2022-02-20T18:08:22.000Z
|
2022-02-20T18:08:22.000Z
|
Rx/v2/src/rxcpp/rx-test.hpp
|
ivan-cukic/wip-fork-rxcpp
|
483963939e4a2adf674450dcb829005d84be1d59
|
[
"Apache-2.0"
] | null | null | null |
Rx/v2/src/rxcpp/rx-test.hpp
|
ivan-cukic/wip-fork-rxcpp
|
483963939e4a2adf674450dcb829005d84be1d59
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#if !defined(RXCPP_RX_TEST_HPP)
#define RXCPP_RX_TEST_HPP
#include "rx-includes.hpp"
namespace rxcpp {
namespace test {
namespace detail {
template<class T>
struct test_subject_base
: public std::enable_shared_from_this<test_subject_base<T>>
{
using recorded_type = rxn::recorded<typename rxn::notification<T>::type>;
using type = std::shared_ptr<test_subject_base<T>>;
virtual ~test_subject_base() {}
virtual void on_subscribe(subscriber<T>) const =0;
virtual std::vector<recorded_type> messages() const =0;
virtual std::vector<rxn::subscription> subscriptions() const =0;
};
template<class T>
struct test_source
: public rxs::source_base<T>
{
explicit test_source(typename test_subject_base<T>::type ts)
: ts(std::move(ts))
{
if (!this->ts) std::terminate();
}
typename test_subject_base<T>::type ts;
void on_subscribe(subscriber<T> o) const {
ts->on_subscribe(std::move(o));
}
template<class Subscriber>
typename std::enable_if<!std::is_same_v<Subscriber, subscriber<T>>, void>::type
on_subscribe(Subscriber o) const {
static_assert(is_subscriber<Subscriber>::value, "on_subscribe must be passed a subscriber.");
ts->on_subscribe(o.as_dynamic());
}
};
}
template<class T>
class testable_observer
: public observer<T>
{
using observer_base = observer<T>;
using test_subject = typename detail::test_subject_base<T>::type;
test_subject ts;
public:
using recorded_type = typename detail::test_subject_base<T>::recorded_type;
testable_observer(test_subject ts, observer_base ob)
: observer_base(std::move(ob))
, ts(std::move(ts))
{
}
std::vector<recorded_type> messages() const {
return ts->messages();
}
};
//struct tag_test_observable : public tag_observable {};
/*!
\brief a source of values that records the time of each subscription/unsubscription and all the values and the time they were emitted.
\ingroup group-observable
*/
template<class T>
class testable_observable
: public observable<T, typename detail::test_source<T>>
{
using observable_base = observable<T, typename detail::test_source<T>>;
using test_subject = typename detail::test_subject_base<T>::type;
test_subject ts;
//typedef tag_test_observable observable_tag;
public:
using recorded_type = typename detail::test_subject_base<T>::recorded_type;
explicit testable_observable(test_subject ts)
: observable_base(detail::test_source<T>(ts))
, ts(ts)
{
}
std::vector<rxn::subscription> subscriptions() const {
return ts->subscriptions();
}
std::vector<recorded_type> messages() const {
return ts->messages();
}
};
}
namespace rxt=test;
}
//
// support range() >> filter() >> subscribe() syntax
// '>>' is spelled 'stream'
//
template<class T, class OperatorFactory>
auto operator >> (const rxcpp::test::testable_observable<T>& source, OperatorFactory&& of)
-> decltype(source.op(std::forward<OperatorFactory>(of))) {
return source.op(std::forward<OperatorFactory>(of));
}
//
// support range() | filter() | subscribe() syntax
// '|' is spelled 'pipe'
//
template<class T, class OperatorFactory>
auto operator | (const rxcpp::test::testable_observable<T>& source, OperatorFactory&& of)
-> decltype(source.op(std::forward<OperatorFactory>(of))) {
return source.op(std::forward<OperatorFactory>(of));
}
#include "schedulers/rx-test.hpp"
#endif
| 25.695652
| 138
| 0.688099
|
guhwanbae
|
d0ede1d40781c2931400b92d1159f53961e4f744
| 36,164
|
cc
|
C++
|
tests/core/test_core_focus_manager.cc
|
nugulinux/nugu-linux
|
c166d61b2037247d4574b7f791c31ba79ceb575e
|
[
"Apache-2.0"
] | null | null | null |
tests/core/test_core_focus_manager.cc
|
nugulinux/nugu-linux
|
c166d61b2037247d4574b7f791c31ba79ceb575e
|
[
"Apache-2.0"
] | null | null | null |
tests/core/test_core_focus_manager.cc
|
nugulinux/nugu-linux
|
c166d61b2037247d4574b7f791c31ba79ceb575e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "focus_manager.hh"
using namespace NuguCore;
#define ASR_USER_FOCUS_TYPE "ASRUser"
#define ASR_USER_FOCUS_PRIORITY 100
#define INFO_FOCUS_TYPE "Info"
#define INFO_FOCUS_PRIORITY 200
#define ALERTS_FOCUS_TYPE "Alerts"
#define ALERTS_FOCUS_PRIORITY 300
#define MEDIA_FOCUS_TYPE "Media"
#define MEDIA_FOCUS_PRIORITY 400
#define INVALID_FOCUS_NAME "Invalid"
#define ASR_USER_NAME "asr_user"
#define ANOTHER_ASR_USER_NAME "another_asr_user"
#define INFO_NAME "information"
#define ALERTS_NAME "alerts"
#define MEDIA_NAME "media"
#define REQUEST_FOCUS(resource, type, name) \
resource->requestFocus(type, name)
#define RELEASE_FOCUS(resource, type) \
resource->releaseFocus(type)
#define HOLD_FOCUS(resource, type) \
resource->holdFocus(type)
#define UNHOLD_FOCUS(resource, type) \
resource->unholdFocus(type)
#define ASSERT_EXPECTED_STATE(resource, state) \
g_assert(resource->getState() == state);
class FocusManagerObserver : public IFocusManagerObserver {
public:
explicit FocusManagerObserver(IFocusManager* focus_manager)
: focus_manager_interface(focus_manager)
{
}
virtual ~FocusManagerObserver() = default;
void onFocusChanged(const FocusConfiguration& configuration, FocusState state, const std::string& name) override
{
std::string msg;
msg.append("==================================================\n[")
.append(configuration.type)
.append(" - ")
.append(name)
.append("] ")
.append(focus_manager_interface->getStateString(state))
.append(" (priority: ")
.append(std::to_string(configuration.priority))
.append(")\n==================================================");
std::cout << msg << std::endl;
}
private:
IFocusManager* focus_manager_interface;
};
class TestFocusResorce : public IFocusResourceListener {
public:
explicit TestFocusResorce(IFocusManager* focus_manager)
: focus_manager_interface(focus_manager)
, cur_state(FocusState::NONE)
{
}
virtual ~TestFocusResorce() = default;
bool requestFocus(const std::string& type, const std::string& name)
{
this->name = name;
return focus_manager_interface->requestFocus(type, name, this);
}
bool releaseFocus(const std::string& type)
{
return focus_manager_interface->releaseFocus(type, name);
}
bool holdFocus(const std::string& type)
{
return focus_manager_interface->holdFocus(type);
}
bool unholdFocus(const std::string& type)
{
return focus_manager_interface->unholdFocus(type);
}
void stopAllFocus()
{
focus_manager_interface->stopAllFocus();
}
void stopForegroundFocus()
{
focus_manager_interface->stopForegroundFocus();
}
void onFocusChanged(FocusState state) override
{
cur_state = state;
}
FocusState getState()
{
return cur_state;
}
private:
IFocusManager* focus_manager_interface;
FocusState cur_state;
std::string name;
};
typedef struct {
FocusManager* focus_manager;
FocusManagerObserver* focus_observer;
TestFocusResorce* asr_resource;
TestFocusResorce* info_resource;
TestFocusResorce* alert_resource;
TestFocusResorce* media_resource;
TestFocusResorce* another_asr_resource;
} ntimerFixture;
static void setup(ntimerFixture* fixture, gconstpointer user_data)
{
fixture->focus_manager = new FocusManager();
fixture->focus_observer = new FocusManagerObserver(fixture->focus_manager);
fixture->focus_manager->addObserver(fixture->focus_observer);
fixture->asr_resource = new TestFocusResorce(fixture->focus_manager);
fixture->info_resource = new TestFocusResorce(fixture->focus_manager);
fixture->alert_resource = new TestFocusResorce(fixture->focus_manager);
fixture->media_resource = new TestFocusResorce(fixture->focus_manager);
fixture->another_asr_resource = new TestFocusResorce(fixture->focus_manager);
std::vector<FocusConfiguration> focus_configuration;
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
fixture->focus_manager->setConfigurations(focus_configuration, focus_configuration);
}
static void teardown(ntimerFixture* fixture, gconstpointer user_data)
{
delete fixture->focus_manager;
delete fixture->focus_observer;
delete fixture->asr_resource;
delete fixture->info_resource;
delete fixture->alert_resource;
delete fixture->media_resource;
delete fixture->another_asr_resource;
}
#define G_TEST_ADD_FUNC(name, func) \
g_test_add(name, ntimerFixture, NULL, setup, func, teardown);
static void test_focusmanager_configurations(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_configuration;
// Add asr user Resource to FocusManager
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_configuration, focus_configuration);
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == ASR_USER_FOCUS_PRIORITY);
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == -1);
// Add asr user Resource with higher priority and Information Resource to FocusManager
focus_configuration.clear();
focus_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY + 100 });
focus_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_configuration, focus_configuration);
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == (ASR_USER_FOCUS_PRIORITY + 100));
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == INFO_FOCUS_PRIORITY);
}
static void test_focusmanager_request_resource_with_invalid_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(!REQUEST_FOCUS(fixture->asr_resource, INVALID_FOCUS_NAME, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_request_resource_with_no_activate_resource(ntimerFixture* fixture, gconstpointer igresource)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_with_higher_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_resource_with_lower_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_two_resources_with_highest_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_two_resources_with_medium_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_two_resources_with_lowest_priority_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_resource_on_foreground(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_same_resource_on_background(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_resource_with_other_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->another_asr_resource, ASR_USER_FOCUS_TYPE, ANOTHER_ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_no_activity_resource(ntimerFixture* fixture, gconstpointer ignored)
{
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
}
static void test_focusmanager_release_resource_with_other_name(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->another_asr_resource, ASR_USER_FOCUS_TYPE, ANOTHER_ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->another_asr_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_foreground_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_release_foreground_resource_with_background_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_background_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::NONE);
}
static void test_focusmanager_stop_foreground_focus_with_one_activity(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
fixture->asr_resource->stopForegroundFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_stop_foreground_focus_with_one_activity_one_pending(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
fixture->asr_resource->stopForegroundFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_stop_all_focus_with_no_resource(ntimerFixture* fixture, gconstpointer ignored)
{
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
fixture->asr_resource->stopAllFocus();
}
static void test_focusmanager_stop_all_focus_with_one_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
fixture->asr_resource->stopAllFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
}
static void test_focusmanager_stop_all_focus_with_two_resources(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
fixture->asr_resource->stopAllFocus();
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::NONE);
}
static void test_focusmanager_request_resource_hold_and_unhold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_with_hold_higher_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_release_resource_with_hold_higher_resource(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// hold info priority: asr user > info > media
g_assert(HOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// media focus is still background because info is holded with higher priority.
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_request_same_holded_resource_and_auto_unhold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
// unhold focus because of request with same priority
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_higher_resource_with_hold(ntimerFixture* fixture, gconstpointer ignored)
{
g_assert(HOLD_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE));
// maintain hold focus because of request with higher priority than hold priority
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(UNHOLD_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_and_release_configurations(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Add asr user Resource to FocusManager
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
// Focus resource's priority is followed by focus release configuration.
g_assert(focus_manager->getFocusResourcePriority(ASR_USER_FOCUS_TYPE) == ASR_USER_FOCUS_PRIORITY);
g_assert(focus_manager->getFocusResourcePriority(INFO_FOCUS_TYPE) == -1);
}
static void test_focusmanager_release_resource_with_different_request_and_same_release_priority_resources(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Add asr user Resource to FocusManager
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// stacked resource: asr user > info
g_assert(REQUEST_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE, INFO_NAME));
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::BACKGROUND);
// stacked resource: asr user > info = alerts
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
// stacked resource: info = alerts
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
// pop fifo resource
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::FOREGROUND);
g_assert(RELEASE_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->info_resource, FocusState::NONE);
// pop fifo resource
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_steal_resource_with_higher_resource_by_request_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// asr user focus is stealed by media focus caused by equal to request priority
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_no_steal_resource_with_higher_resource_request_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user > media
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
// Release Priority: asr user > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
// asr user focus can't be stolen because media focus has a low request priority
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
}
static void test_focusmanager_release_resources_by_release_priority(ntimerFixture* fixture, gconstpointer igresource)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media > alerts
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > alerts > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
static void test_focusmanager_request_resource_hold_and_unhold_with_different_request_release_priority(ntimerFixture* fixture, gconstpointer ignored)
{
FocusManager* focus_manager = fixture->focus_manager;
std::vector<FocusConfiguration> focus_request_configuration;
std::vector<FocusConfiguration> focus_release_configuration;
// Request Priority: asr user = media > info > alerts
focus_request_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_request_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_request_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_request_configuration.push_back({ MEDIA_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
// Release Priority: asr user > info > alerts > media
focus_release_configuration.push_back({ ASR_USER_FOCUS_TYPE, ASR_USER_FOCUS_PRIORITY });
focus_release_configuration.push_back({ INFO_FOCUS_TYPE, INFO_FOCUS_PRIORITY });
focus_release_configuration.push_back({ ALERTS_FOCUS_TYPE, ALERTS_FOCUS_PRIORITY });
focus_release_configuration.push_back({ MEDIA_FOCUS_TYPE, MEDIA_FOCUS_PRIORITY });
focus_manager->setConfigurations(focus_request_configuration, focus_release_configuration);
g_assert(HOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
// request priority: info > alerts
g_assert(REQUEST_FOCUS(fixture->alert_resource, ALERTS_FOCUS_TYPE, ALERTS_NAME));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
// request priority: info < media
g_assert(REQUEST_FOCUS(fixture->media_resource, MEDIA_FOCUS_TYPE, MEDIA_NAME));
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::FOREGROUND);
// request priority: asr user = media
g_assert(REQUEST_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE, ASR_USER_NAME));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::FOREGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// release priority: info > alert > media
g_assert(RELEASE_FOCUS(fixture->asr_resource, ASR_USER_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->asr_resource, FocusState::NONE);
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::BACKGROUND);
ASSERT_EXPECTED_STATE(fixture->media_resource, FocusState::BACKGROUND);
// release priority: alert > media
g_assert(UNHOLD_FOCUS(fixture->info_resource, INFO_FOCUS_TYPE));
ASSERT_EXPECTED_STATE(fixture->alert_resource, FocusState::FOREGROUND);
}
int main(int argc, char* argv[])
{
#if !GLIB_CHECK_VERSION(2, 36, 0)
g_type_init();
#endif
g_test_init(&argc, &argv, (void*)NULL);
g_log_set_always_fatal((GLogLevelFlags)G_LOG_FATAL_MASK);
G_TEST_ADD_FUNC("/core/FocusManager/FocusConfigurations", test_focusmanager_configurations);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceInvalidName", test_focusmanager_request_resource_with_invalid_name);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithNoActivateResource", test_focusmanager_request_resource_with_no_activate_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithHigherPriorityResource", test_focusmanager_request_resource_with_higher_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithLowerPriorityResource", test_focusmanager_request_resource_with_lower_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithHighestPriorityResource", test_focusmanager_request_two_resources_with_highest_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithMediumPriorityResource", test_focusmanager_request_two_resources_with_medium_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestTowResourcesWithLowestPriorityResource", test_focusmanager_request_two_resources_with_lowest_priority_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceOnForeground", test_focusmanager_request_same_resource_on_foreground);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceOnBackground", test_focusmanager_request_same_resource_on_background);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameResourceWithOtherInterfaceName", test_focusmanager_request_same_resource_with_other_name);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseNoActivityResource", test_focusmanager_release_no_activity_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourceWithOtherInterfaceName", test_focusmanager_release_resource_with_other_name);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseForegroundResource", test_focusmanager_release_foreground_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseForegroundResourceWithBackgroundResource", test_focusmanager_release_foreground_resource_with_background_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseBackgroundResource", test_focusmanager_release_background_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopForegroundFocusWithOneActivity", test_focusmanager_stop_foreground_focus_with_one_activity);
G_TEST_ADD_FUNC("/core/FocusManager/StopForegroundFocusWithOneActivityOnePending", test_focusmanager_stop_foreground_focus_with_one_activity_one_pending);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithNoResource", test_focusmanager_stop_all_focus_with_no_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithOneResource", test_focusmanager_stop_all_focus_with_one_resource);
G_TEST_ADD_FUNC("/core/FocusManager/StopAllFocusWithTwoResources", test_focusmanager_stop_all_focus_with_two_resources);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceHoldAndUnHold", test_focusmanager_request_resource_hold_and_unhold);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceWithHoldHigherResource", test_focusmanager_request_resource_with_hold_higher_resource);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourceWithHoldHigherResource", test_focusmanager_release_resource_with_hold_higher_resource);
G_TEST_ADD_FUNC("/core/FocusManager/RequestSameHoldedResourceAndAutoUnhold", test_focusmanager_request_same_holded_resource_and_auto_unhold);
G_TEST_ADD_FUNC("/core/FocusManager/RequestHigherResourceWithHold", test_focusmanager_request_higher_resource_with_hold);
G_TEST_ADD_FUNC("/core/FocusManager/FocusRequestAndReleaseConfigurations", test_focusmanager_request_and_release_configurations);
G_TEST_ADD_FUNC("/core/FocusManager/FocusReleaseResourceWithDifferentRequestAndSameReleasePriorityResources", test_focusmanager_release_resource_with_different_request_and_same_release_priority_resources);
G_TEST_ADD_FUNC("/core/FocusManager/StealResourceWithHigherResourceByRequestPriority", test_focusmanager_steal_resource_with_higher_resource_by_request_priority);
G_TEST_ADD_FUNC("/core/FocusManager/NoStealResourceWithHigherResourceByRequestPriority", test_focusmanager_no_steal_resource_with_higher_resource_request_priority);
G_TEST_ADD_FUNC("/core/FocusManager/ReleaseResourcesByReleasePriority", test_focusmanager_release_resources_by_release_priority);
G_TEST_ADD_FUNC("/core/FocusManager/RequestResourceHoldAndUnHoldWithDifferentRequestReleasePriority", test_focusmanager_request_resource_hold_and_unhold_with_different_request_release_priority);
return g_test_run();
}
| 50.019364
| 209
| 0.808428
|
nugulinux
|
d0f48c9d8316176fa6633b420486642150f6f79e
| 1,009
|
hpp
|
C++
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
plugins/d3d9/include/sge/d3d9/state/core/depth_stencil/stencil/enabled_visitor.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_STATE_CORE_DEPTH_STENCIL_STENCIL_ENABLED_VISITOR_HPP_INCLUDED
#define SGE_D3D9_STATE_CORE_DEPTH_STENCIL_STENCIL_ENABLED_VISITOR_HPP_INCLUDED
#include <sge/d3d9/state/render_vector.hpp>
#include <sge/renderer/state/core/depth_stencil/stencil/combined_fwd.hpp>
#include <sge/renderer/state/core/depth_stencil/stencil/separate_fwd.hpp>
namespace sge
{
namespace d3d9
{
namespace state
{
namespace core
{
namespace depth_stencil
{
namespace stencil
{
class enabled_visitor
{
public:
typedef sge::d3d9::state::render_vector result_type;
result_type
operator()(sge::renderer::state::core::depth_stencil::stencil::combined const &) const;
result_type
operator()(sge::renderer::state::core::depth_stencil::stencil::separate const &) const;
};
}
}
}
}
}
}
#endif
| 21.934783
| 89
| 0.77106
|
cpreh
|
d0f957374b6a73dd463c98489d59005bb92124e0
| 890
|
cpp
|
C++
|
COS1511/Part3/Lesson21/aii.cpp
|
GalliWare/UNISA-studies
|
32bab94930b176c4dfe943439781ef102896fab5
|
[
"Unlicense"
] | null | null | null |
COS1511/Part3/Lesson21/aii.cpp
|
GalliWare/UNISA-studies
|
32bab94930b176c4dfe943439781ef102896fab5
|
[
"Unlicense"
] | null | null | null |
COS1511/Part3/Lesson21/aii.cpp
|
GalliWare/UNISA-studies
|
32bab94930b176c4dfe943439781ef102896fab5
|
[
"Unlicense"
] | null | null | null |
// compute the average of 3 marks for 2 students and display the better average
// my code with the addition of the reference so input can be turned into a function.
#include <iostream>
using namespace std;
float averageMark(float mark1, float mark2, float mark3)
{
float average = 0, divider = 3;
average = (mark1 + mark2 + mark3) / divider;
return average;
}
void inputMark(float &m1P, float &m2P, float &m3P)
{
cout << "Enter the 3 marks: ";
cin >> m1P >> m2P >> m3P;
}
int main()
{
float student1Average, student2Average, m1, m2, m3;
inputMark(m1, m2, m3);
student1Average = averageMark(m1, m2, m3);
inputMark(m1, m2, m3);
student2Average = averageMark(m1, m2, m3);
if (student1Average > student2Average)
cout << "The first student has the higher average" << endl;
else
cout << "The second student has the higher average" << endl;
return 0;
}
| 23.421053
| 85
| 0.682022
|
GalliWare
|
d0fafcfdb8f8a6871c6e2180216b295eb5740119
| 630
|
cc
|
C++
|
sdk/src/http/HttpClient.cc
|
OpenInspur/inspur-oss-cpp-sdk
|
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
|
[
"Apache-2.0"
] | null | null | null |
sdk/src/http/HttpClient.cc
|
OpenInspur/inspur-oss-cpp-sdk
|
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
|
[
"Apache-2.0"
] | null | null | null |
sdk/src/http/HttpClient.cc
|
OpenInspur/inspur-oss-cpp-sdk
|
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
|
[
"Apache-2.0"
] | null | null | null |
#include "HttpClient.h"
using namespace InspurCloud::OSS;
HttpClient::HttpClient():
disable_(false)
{
}
HttpClient::~HttpClient()
{
}
bool HttpClient::isEnable()
{
return disable_.load() == false;
}
void HttpClient::disable()
{
disable_ = true;
requestSignal_.notify_all();
}
void HttpClient::enable()
{
disable_ = false;
}
void HttpClient::waitForRetry(long milliseconds)
{
if (milliseconds == 0)
return;
std::unique_lock<std::mutex> lck(requestLock_);
requestSignal_.wait_for(lck, std::chrono::milliseconds(milliseconds), [this] ()-> bool { return disable_.load() == true; });
}
| 16.153846
| 128
| 0.669841
|
OpenInspur
|
cb9c0d8189012fbe41d8ea09293342927a1b3d2e
| 1,707
|
cpp
|
C++
|
Barometer/src/main.cpp
|
michprev/drone
|
51c659cdd4e1d50446a563bb11e800defda9a298
|
[
"MIT"
] | 2
|
2017-06-03T01:07:16.000Z
|
2017-07-14T17:49:16.000Z
|
Barometer/src/main.cpp
|
michprev/drone
|
51c659cdd4e1d50446a563bb11e800defda9a298
|
[
"MIT"
] | 5
|
2017-04-24T20:29:04.000Z
|
2017-06-26T17:40:53.000Z
|
Barometer/src/main.cpp
|
michprev/drone
|
51c659cdd4e1d50446a563bb11e800defda9a298
|
[
"MIT"
] | null | null | null |
/**
******************************************************************************
* @file main.c
* @author Ac6
* @version V1.0
* @date 01-December-2013
* @brief Default main function.
******************************************************************************
*/
#include "stm32f4xx_hal.h"
#include "MS5611.h"
using namespace flyhero;
extern "C" void initialise_monitor_handles(void);
int main(void)
{
HAL_Init();
initialise_monitor_handles();
if (__GPIOB_IS_CLK_DISABLED())
__GPIOB_CLK_ENABLE();
if (__I2C1_IS_CLK_DISABLED())
__I2C1_CLK_ENABLE();
I2C_HandleTypeDef hi2c;
GPIO_InitTypeDef gpio;
gpio.Pin = GPIO_PIN_8 | GPIO_PIN_9;
gpio.Mode = GPIO_MODE_AF_OD;
gpio.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
gpio.Pull = GPIO_PULLUP;
gpio.Alternate = GPIO_AF4_I2C1;
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8 | GPIO_PIN_9);
HAL_GPIO_Init(GPIOB, &gpio);
hi2c.Instance = I2C1;
hi2c.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c.Init.ClockSpeed = 400000;
hi2c.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
hi2c.Init.OwnAddress1 = 0;
hi2c.Init.OwnAddress2 = 0;
HAL_I2C_DeInit(&hi2c);
HAL_I2C_Init(&hi2c);
MS5611& ms5611 = MS5611::Instance();
ms5611.Init(&hi2c);
int32_t press, temp;
ms5611.ConvertD1();
while (true) {
if (ms5611.D1_Ready())
ms5611.ConvertD2();
else if (ms5611.D2_Ready()) {
ms5611.GetData(&temp, &press);
printf("Temp: %d, press: %d\n", temp, press);
HAL_Delay(100);
ms5611.ConvertD1();
}
}
}
| 23.383562
| 81
| 0.620972
|
michprev
|
cb9e0823aad36f6d2f7eef03549bbaa15a5f3002
| 514
|
hpp
|
C++
|
src/LovelaceConfig/FanCardConfig.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | 2
|
2020-10-23T19:53:56.000Z
|
2020-11-06T08:59:48.000Z
|
src/LovelaceConfig/FanCardConfig.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | null | null | null |
src/LovelaceConfig/FanCardConfig.hpp
|
RobinSinghNanda/Home-assistant-display
|
6f59104012c0956b54d4b55e190aa89941c2c1af
|
[
"MIT"
] | null | null | null |
#ifndef __FANCARDCONFIG_H__
#define __FANCARDCONFIG_H__
#include "BaseEntityCardConfig.hpp"
#include <string.h>
class FanCardConfig : public BaseEntityCardConfig {
public:
FanCardConfig(const char * entity, const char * title, const char * icon, const char * rowIcon, bool state_color);
FanCardConfig(const char * entity, const char * title, const char * icon, bool state_color);
FanCardConfig(const char * entity);
static constexpr const char * TYPE = "fan";
};
#endif // __FANCARDCONFIG_H__
| 32.125
| 118
| 0.745136
|
RobinSinghNanda
|
cba0569739e874dce90f679b8584d0275a0621ed
| 1,482
|
cxx
|
C++
|
src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 45
|
2015-02-10T15:45:22.000Z
|
2022-02-24T07:45:01.000Z
|
src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 58
|
2015-02-27T10:03:18.000Z
|
2021-08-10T04:21:42.000Z
|
src/sdp_read/read_input/read_json/JSON_Parser/Key.cxx
|
ChrisPattison/sdpb
|
4668f72c935e7feba705dd8247d9aacb23185f1c
|
[
"MIT"
] | 38
|
2015-02-10T11:11:27.000Z
|
2022-02-11T20:59:42.000Z
|
#include "../JSON_Parser.hxx"
bool JSON_Parser::Key(const Ch *str, rapidjson::SizeType length, bool)
{
std::string key(str, length);
if(inside)
{
if(parsing_objective)
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside '" + objective_state.name
+ "'.");
}
else if(parsing_normalization)
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside '" + normalization_state.name
+ "'.");
}
else if(parsing_positive_matrices_with_prefactor)
{
positive_matrices_with_prefactor_state.json_key(key);
}
else if(key == objective_state.name)
{
parsing_objective = true;
}
else if(key == normalization_state.name)
{
parsing_normalization = true;
}
else if(key == positive_matrices_with_prefactor_state.name)
{
parsing_positive_matrices_with_prefactor = true;
}
else
{
throw std::runtime_error("Invalid input file. Found the key '" + key
+ "' inside the main object.");
}
}
else
{
throw std::runtime_error("Found a key outside of the main object: "
+ key);
}
return true;
}
| 30.244898
| 79
| 0.503374
|
ChrisPattison
|
cba42f85d77a37f23b5b06b555e43d2c6793f139
| 1,068
|
hpp
|
C++
|
include/stl2/detail/concepts/urng.hpp
|
melton1968/cmcstl2
|
15052dda39c93c460b8e0e16fff62d8eb4388627
|
[
"MIT"
] | null | null | null |
include/stl2/detail/concepts/urng.hpp
|
melton1968/cmcstl2
|
15052dda39c93c460b8e0e16fff62d8eb4388627
|
[
"MIT"
] | null | null | null |
include/stl2/detail/concepts/urng.hpp
|
melton1968/cmcstl2
|
15052dda39c93c460b8e0e16fff62d8eb4388627
|
[
"MIT"
] | null | null | null |
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
// Copyright Eric Niebler 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_CONCEPTS_URNG_HPP
#define STL2_DETAIL_CONCEPTS_URNG_HPP
#include <stl2/detail/concepts/callable.hpp>
STL2_OPEN_NAMESPACE {
template<auto> struct __require_constant; // not defined
template<class G>
META_CONCEPT UniformRandomBitGenerator =
Invocable<G&> && UnsignedIntegral<invoke_result_t<G&>> &&
requires {
G::min(); requires Same<decltype(G::min()), invoke_result_t<G&>>;
G::max(); requires Same<decltype(G::max()), invoke_result_t<G&>>;
#if 1 // This is the PR for https://wg21.link/lwg3150
typename __require_constant<G::min()>;
typename __require_constant<G::min()>;
requires G::min() < G::max();
#endif
};
} STL2_CLOSE_NAMESPACE
#endif
| 29.666667
| 68
| 0.725655
|
melton1968
|
cba7aac455f42b3c965db0784984de83aab58298
| 5,002
|
cpp
|
C++
|
mcu/timer/LPTimer.cpp
|
sourcebox/mcu_stm32l4xx
|
509433f5fbbd6f3238b1694b681d21241412a400
|
[
"MIT"
] | null | null | null |
mcu/timer/LPTimer.cpp
|
sourcebox/mcu_stm32l4xx
|
509433f5fbbd6f3238b1694b681d21241412a400
|
[
"MIT"
] | null | null | null |
mcu/timer/LPTimer.cpp
|
sourcebox/mcu_stm32l4xx
|
509433f5fbbd6f3238b1694b681d21241412a400
|
[
"MIT"
] | null | null | null |
/**
* @file LPTimer.cpp
*
* Driver for low power timer peripherals on STM32L4xx
*
* @author: Oliver Rockstedt <info@sourcebox.de>
* @license MIT
*/
// Corresponding header
#include "LPTimer.h"
// This component
#include "../core/NVIC.h"
#include "../rcc/RCC.h"
#include "../rcc/RCC_Registers.h"
#include "../utility/bit_manipulation.h"
#include "../utility/log2.h"
// System libraries
#include <cstdlib>
namespace mcu {
// ============================================================================
// Public members
// ============================================================================
LPTimer::LPTimer(Id id)
: id(id)
{
}
void LPTimer::init()
{
enableClock();
auto registers = getRegisters();
registers->CFGR |= (1 << LPTimer_Registers::CFGR::PRELOAD);
}
void LPTimer::init(uint16_t prescaler, uint32_t period)
{
init();
setPrescaler(prescaler);
setPeriod(period);
}
void LPTimer::init(int freq)
{
init();
setFrequency(freq);
}
void LPTimer::init(Config& config)
{
init();
setPrescaler(config.prescaler);
setPeriod(config.period);
}
void LPTimer::deinit()
{
disableClock();
}
uint32_t LPTimer::getPrescaler()
{
auto registers = getRegisters();
return (1 << bitsValue(registers->CFGR, 3, LPTimer_Registers::CFGR::PRESC_0));
}
void LPTimer::setPrescaler(uint16_t value)
{
disable();
auto registers = getRegisters();
registers->CFGR = bitsReplace(registers->CFGR, log2(value), 3,
LPTimer_Registers::CFGR::PRESC_0);
enable();
}
uint32_t LPTimer::getPeriod()
{
auto registers = getRegisters();
return registers->ARR;
}
void LPTimer::setPeriod(volatile uint32_t value)
{
enable();
auto registers = getRegisters();
registers->ARR = value;
}
void LPTimer::setFrequency(uint32_t freq)
{
uint32_t clockFreq = RCC::get().getPCLK1Freq();
auto periodCycles = clockFreq / freq;
uint16_t prescaler = (periodCycles / 0xFFFF) + 1;
// Force prescaler to a power of 2
prescaler = 1 << log2(prescaler);
auto period = (periodCycles + (prescaler / 2)) / prescaler;
if (period > 0xFFFF) {
prescaler <<= 1;
period = (periodCycles + (prescaler / 2)) / prescaler;
}
setPrescaler(prescaler);
setPeriod(period);
}
void LPTimer::enable()
{
auto registers = getRegisters();
registers->CR |= (1 << LPTimer_Registers::CR::ENABLE);
}
void LPTimer::disable()
{
auto registers = getRegisters();
registers->CR &= ~(1 << LPTimer_Registers::CR::ENABLE);
}
void LPTimer::start()
{
auto registers = getRegisters();
registers->CR |= 1 << LPTimer_Registers::CR::CNTSTRT;
}
void LPTimer::stop()
{
disable();
enable();
}
uint32_t LPTimer::getCounter()
{
auto registers = getRegisters();
return registers->CNT;
}
void LPTimer::setCounter(uint32_t value)
{
auto registers = getRegisters();
registers->CNT = value;
}
void LPTimer::setUpdateCallback(CallbackFunc func)
{
disable();
updateCallback = func;
auto registers = getRegisters();
if (func != nullptr) {
registers->IER |= (1 << LPTimer_Registers::IER::ARRMIE);
auto& nvic = NVIC::get();
nvic.enableIrq(getIRQNumber(id));
} else {
registers->IER &= ~(1 << LPTimer_Registers::IER::ARRMIE);
}
enable();
}
void LPTimer::irq()
{
auto registers = getRegisters();
if (registers->ISR & (1 << LPTimer_Registers::ISR::ARRM)) {
registers->ICR |= (1 << LPTimer_Registers::ICR::ARRMCF);
if (updateCallback != nullptr) {
updateCallback();
}
}
if (registers->ISR & (1 << LPTimer_Registers::ISR::CMPM)) {
registers->ICR |= (1 << LPTimer_Registers::ICR::CMPMCF);
auto callback = channels[0].ch1Callbacks[id];
if (callback != nullptr) {
callback();
}
}
}
// ============================================================================
// Protected members
// ============================================================================
void LPTimer::enableClock()
{
auto rccRegisters = RCC_Registers::get();
switch (id) {
case LPTIM1:
rccRegisters->APB1ENR1 |= (1 << RCC_Registers::APB1ENR1::LPTIM1EN);
break;
case LPTIM2:
rccRegisters->APB1ENR2 |= (1 << RCC_Registers::APB1ENR2::LPTIM2EN);
break;
default:
break;
}
}
void LPTimer::disableClock()
{
auto rccRegisters = RCC_Registers::get();
switch (id) {
case LPTIM1:
rccRegisters->APB1ENR1 &= ~(1 << RCC_Registers::APB1ENR1::LPTIM1EN);
break;
case LPTIM2:
rccRegisters->APB1ENR2 &= ~(1 << RCC_Registers::APB1ENR2::LPTIM2EN);
break;
default:
break;
}
}
LPTimer LPTimer::lptimer1 = LPTimer(LPTimer::LPTIM1);
LPTimer LPTimer::lptimer2 =LPTimer(LPTimer::LPTIM2);
} // namespace mcu
| 18.594796
| 82
| 0.570972
|
sourcebox
|
cba7e87ac1438fe9452d7660e49845d7e8ea457c
| 1,253
|
cpp
|
C++
|
problems/triangle/src/Solution.cpp
|
bbackspace/leetcode
|
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
|
[
"CC0-1.0"
] | null | null | null |
problems/triangle/src/Solution.cpp
|
bbackspace/leetcode
|
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
|
[
"CC0-1.0"
] | null | null | null |
problems/triangle/src/Solution.cpp
|
bbackspace/leetcode
|
bc3f235fcd42c37800e6ef7eefab4c826d70f3d3
|
[
"CC0-1.0"
] | null | null | null |
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<vector<int>> dp(triangle.size(), vector<int>(triangle.size(), 0));
dp[0][0] = triangle[0][0];
for (int i = 1; i < triangle.size(); i++) {
dp[i][0] = dp[i - 1][0] + triangle[i][0];
for (int j = 1; j < triangle[i].size(); j++) {
if (j == triangle[i].size() - 1) {
dp[i][j] = dp[i - 1][j - 1] + triangle[i][j];
} else {
dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle[i][j];
}
}
}
int ans = dp[triangle.size() - 1][0];
for (int i = 1; i < triangle.size(); i++) {
ans = min(ans, dp[triangle.size() - 1][i]);
}
return ans;
}
void print(vector<vector<int>> v) {
cout << "[";
print(v[0]);
for (int i = 1; i < v.size(); i++) {
cout << ",\n";
print(v[i]);
}
cout << "]";
}
void print(vector<int> v) {
cout << "[";
cout << (v[0]);
for (int i = 1; i < v.size(); i++) {
cout << ",";
cout << (v[i]);
}
cout << "]";
}
};
| 29.139535
| 84
| 0.365523
|
bbackspace
|
cbbb20203048656dfd071519280ec9992fd02140
| 1,678
|
cpp
|
C++
|
src/distance_functions.cpp
|
ChristianDueben/conleyreg
|
73d71fa50b02adcd8dae3b8b407db50403d8017b
|
[
"MIT"
] | 3
|
2021-11-03T12:35:58.000Z
|
2022-03-30T11:21:42.000Z
|
src/distance_functions.cpp
|
ChristianDueben/conleyreg
|
73d71fa50b02adcd8dae3b8b407db50403d8017b
|
[
"MIT"
] | 2
|
2021-04-19T17:32:47.000Z
|
2021-11-29T21:13:14.000Z
|
src/distance_functions.cpp
|
ChristianDueben/conleyreg
|
73d71fa50b02adcd8dae3b8b407db50403d8017b
|
[
"MIT"
] | null | null | null |
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_num_threads() 1
#define omp_get_thread_num() 0
#define omp_get_max_threads() 1
#define omp_get_thread_limit() 1
#define omp_get_num_procs() 1
#endif
// [[Rcpp::plugins(openmp)]]
#include <cmath>
#include "distance_functions.h"
// 1a Function computing haversine distance
double haversine_dist(double lat1, double lat2, double lon1, double lon2) {
double the_terms = (std::pow(std::sin((lat2 - lat1) / 2), 2)) + (std::cos(lat1) * std::cos(lat2) * std::pow(std::sin((lon2 - lon1) / 2), 2));
double delta_sigma = 2 * std::atan2(std::sqrt(the_terms), std::sqrt(1 - the_terms));
return (6371.01 * delta_sigma);
}
// 1b Function computing euclidean distance
double euclidean_dist(double lat1, double lat2, double lon1, double lon2) {
return (std::sqrt(std::pow(lon1 - lon2, 2) + std::pow(lat1 - lat2, 2)));
}
// 1c Function computing rounded haversine distance
unsigned int haversine_dist_r(double lat1, double lat2, double lon1, double lon2) {
double the_terms = (std::pow(std::sin((lat2 - lat1) / 2), 2)) + (std::cos(lat1) * std::cos(lat2) * std::pow(std::sin((lon2 - lon1) / 2), 2));
double delta_sigma = 2 * std::atan2(std::sqrt(the_terms), std::sqrt(1 - the_terms));
unsigned int dist_r = (int)(6371.01 * delta_sigma + 0.5);
return dist_r;
}
// 1d Function computing rounded euclidean distance
unsigned int euclidean_dist_r(double lat1, double lat2, double lon1, double lon2) {
unsigned int dist_r = (int)(std::sqrt(std::pow(lon1 - lon2, 2) + std::pow(lat1 - lat2, 2)));
return dist_r;
}
| 38.136364
| 143
| 0.68534
|
ChristianDueben
|
cbbb2c1c702f560230f2291b6406139381713261
| 3,327
|
cc
|
C++
|
lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc
|
PaddleLite-EB/Paddle-Lite
|
40cae8672712552de5eb0894d0b5316ae89d3c17
|
[
"Apache-2.0"
] | 6
|
2020-07-01T02:52:16.000Z
|
2021-06-22T12:15:59.000Z
|
lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc
|
PaddleLite-EB/Paddle-Lite
|
40cae8672712552de5eb0894d0b5316ae89d3c17
|
[
"Apache-2.0"
] | null | null | null |
lite/backends/nnadapter/nnadapter/driver/huawei_kirin_npu/converter/elementwise.cc
|
PaddleLite-EB/Paddle-Lite
|
40cae8672712552de5eb0894d0b5316ae89d3c17
|
[
"Apache-2.0"
] | 1
|
2021-07-24T15:30:46.000Z
|
2021-07-24T15:30:46.000Z
|
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "driver/huawei_kirin_npu/converter.h"
#include "utility/debug.h"
namespace nnadapter {
namespace huawei_kirin_npu {
int Program::ConvertElementwise(hal::Operation* operation) {
auto& input_operands = operation->input_operands;
auto& output_operands = operation->output_operands;
auto input_count = input_operands.size();
auto output_count = output_operands.size();
NNADAPTER_CHECK_EQ(input_count, 3);
NNADAPTER_CHECK_EQ(output_count, 1);
// Input0
auto input0_operand = input_operands[0];
NNADAPTER_VLOG(5) << "input0: " << OperandToString(input0_operand);
// Input1
auto input1_operand = input_operands[1];
NNADAPTER_VLOG(5) << "input1: " << OperandToString(input1_operand);
// Fuse code
auto fuse_code = *reinterpret_cast<int32_t*>(input_operands[2]->buffer);
NNADAPTER_VLOG(5) << "fuse_code=" << fuse_code;
// Output
auto output_operand = output_operands[0];
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
// Convert to HiAI operators
auto input0_operator = ConvertOperand(input0_operand);
auto input1_operator = ConvertOperand(input1_operand);
std::shared_ptr<ge::Operator> eltwise_operator = nullptr;
if (operation->type == NNADAPTER_ADD) {
auto add_operator = AddOperator<ge::op::Add>(output_operand);
add_operator->set_input_x1(*input0_operator);
add_operator->set_input_x2(*input1_operator);
eltwise_operator = add_operator;
} else if (operation->type == NNADAPTER_SUB) {
auto sub_operator = AddOperator<ge::op::Sub>(output_operand);
sub_operator->set_input_x1(*input0_operator);
sub_operator->set_input_x2(*input1_operator);
eltwise_operator = sub_operator;
} else if (operation->type == NNADAPTER_MUL) {
auto mul_operator = AddOperator<ge::op::Mul>(output_operand);
mul_operator->set_input_x(*input0_operator);
mul_operator->set_input_y(*input1_operator);
eltwise_operator = mul_operator;
} else if (operation->type == NNADAPTER_DIV) {
auto div_operator = AddOperator<ge::op::RealDiv>(output_operand);
div_operator->set_input_x1(*input0_operator);
div_operator->set_input_x2(*input1_operator);
eltwise_operator = div_operator;
} else {
NNADAPTER_LOG(FATAL) << "Unsupported element-wise operation type "
<< OperationTypeToString(operation->type)
<< " is found.";
}
if (fuse_code != NNADAPTER_FUSED_NONE) {
auto act_operator = AddOperator<ge::op::Activation>(output_operand);
act_operator->set_input_x(*eltwise_operator);
act_operator->set_attr_mode(ConvertFuseCode(fuse_code));
}
return NNADAPTER_NO_ERROR;
}
} // namespace huawei_kirin_npu
} // namespace nnadapter
| 41.5875
| 75
| 0.733093
|
PaddleLite-EB
|
cbbc838b43269f4e27c7ac866427322f0dd802df
| 40,733
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_GiantTurtle_Character_BP_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_GiantTurtle_Character_BP_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass GiantTurtle_Character_BP.GiantTurtle_Character_BP_C
// 0x06D8 (0x2940 - 0x2268)
class AGiantTurtle_Character_BP_C : public ADino_Character_BP_C
{
public:
class UBoxComponent* PlatformSaddleBuildArea; // 0x2268(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAudioComponent* BreathSound; // 0x2270(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* IdleWake; // 0x2278(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Submerage; // 0x2280(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* ParticleSystem1; // 0x2288(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* Wake; // 0x2290(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* AirCone; // 0x2298(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UParticleSystemComponent* BubbleCone; // 0x22A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Back_Leg; // 0x22A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Middle_Leg; // 0x22B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Right_Front_Leg; // 0x22B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Back_Leg; // 0x22C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Middle_Leg; // 0x22C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* Target_Left_Front_Leg; // 0x22D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* FlockRoot; // 0x22D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USkeletalMeshComponent* InvisibleSaddle; // 0x22E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UDinoCharacterStatusComponent_BP_GiantTurtle_C* DinoCharacterStatus_BP_GiantTurtle_C1; // 0x22E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
double LastGiveOxygenTime; // 0x22F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UStaticMeshComponent* CropSMTest; // 0x22F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<struct FGiantTurtle_Crop_Struct> CropDataStructs; // 0x2300(0x0010) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame)
TArray<class ACropPlotLarge_SM_C*> CropPlots; // 0x2310(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
float TimeintervalToAddOxygen; // 0x2320(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float OxygenRadius; // 0x2324(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TotalGrowthTime; // 0x2328(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float GrowthTimeInterval; // 0x232C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float CurrentGrowthTime; // 0x2330(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlowerGrowthPercentage; // 0x2334(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
float MushroomGrowthPercentage; // 0x2338(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x233C(0x0004) MISSED OFFSET
class UClass* FlowerToGiveOnGrowth; // 0x2340(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UClass* MushroomToGiveOnGrowth; // 0x2348(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
int FlowersToGivePerGrowth; // 0x2350(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
int MushroomToGivePerGrowth; // 0x2354(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
TArray<class UStaticMeshComponent*> CropBaseMeshes; // 0x2358(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
bool bIsDebugging; // 0x2368(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData01[0x7]; // 0x2369(0x0007) MISSED OFFSET
double LastAddOxygenVFXTime; // 0x2370(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<int> TakenLocationIndex; // 0x2378(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
double LastCheckInventoryForSeedTime; // 0x2388(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int AmountOfBubblePerAttack; // 0x2390(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsBreathing; // 0x2394(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData02[0x3]; // 0x2395(0x0003) MISSED OFFSET
struct FVector TPVCamera; // 0x2398(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector KCamera; // 0x23A4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastBubbleTime; // 0x23B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeMaxLength; // 0x23B8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector BreathDirection; // 0x23BC(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector BreathViewStartLocation; // 0x23C8(0x000C) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeCurrentLength; // 0x23D4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeFilledTime; // 0x23D8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleConeAngleDegree; // 0x23DC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FHUDElement BubbleCooldownHudTemplate; // 0x23E0(0x0150) (Edit, BlueprintVisible, DisableEditOnInstance)
float BubbleCooldownTick; // 0x2530(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackCooldown; // 0x2534(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackMinRequireStamina; // 0x2538(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackMaxDuration; // 0x253C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackStaminaCostPerSecond; // 0x2540(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float BubbleAttackDuration; // 0x2544(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsFullyInWater; // 0x2548(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData03[0x3]; // 0x2549(0x0003) MISSED OFFSET
struct FVector InWaterCheckOffset; // 0x254C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDestroyFlock; // 0x2558(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SpawnFlockCooldown; // 0x2560(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector SpawnFlockOffset; // 0x2564(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class APrimalCharacter* MicrobeSwarm; // 0x2570(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
int FlockSize; // 0x2578(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int NumLeaderBoids; // 0x257C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<struct FBoid> FlockData; // 0x2580(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
bool bHasFlock; // 0x2590(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData04[0x7]; // 0x2591(0x0007) MISSED OFFSET
class UStaticMesh* BoidStaticMesh; // 0x2598(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool DebugFlock; // 0x25A0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData05[0x7]; // 0x25A1(0x0007) MISSED OFFSET
TArray<class UStaticMeshComponent*> FlockStaticMeshComps; // 0x25A8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
unsigned char UnknownData06[0x8]; // 0x25B8(0x0008) MISSED OFFSET
struct UObject_FTransform CurrentFlockTarget; // 0x25C0(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData)
float CurAngle; // 0x25F0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData07[0xC]; // 0x25F4(0x000C) MISSED OFFSET
struct UObject_FTransform CurrentFlockTarget_Smoothed; // 0x2600(0x0030) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData)
struct FFlockPersistentData FlockPersistentData; // 0x2630(0x0038) (Edit, BlueprintVisible, DisableEditOnInstance)
struct FBoidBehavior Behavior; // 0x2668(0x0040) (Edit, BlueprintVisible, DisableEditOnInstance)
float TamingProcess; // 0x26A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlockDuration; // 0x26AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float FlockCooldown; // 0x26B0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData08[0x4]; // 0x26B4(0x0004) MISSED OFFSET
double LastTimeToggleFlock; // 0x26B8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TestFloat; // 0x26C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector CurrentDisappearingLocationOffset; // 0x26C4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CurrentDisapperaingMultiplier; // 0x26D0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
struct FVector FlockFlyingOffset; // 0x26D4(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<class UClass*> SeedToGiveClass; // 0x26E0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
double LastTamingProcessIncrease; // 0x26F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class APrimalDinoCharacter* TamingFish; // 0x26F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
double LastTimeTamingFishDie; // 0x2700(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTimeDamageMicrobe; // 0x2708(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class AShooterCharacter* Tamer; // 0x2710(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
float MinTimeBetweenOxygenVFX; // 0x2718(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float MaxTimeBetweenOxygenVFX; // 0x271C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MinBubblesToSpawnPerWave; // 0x2720(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxBubblesToSpawnPerWave; // 0x2724(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float WakeThreshold; // 0x2728(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData09[0x4]; // 0x272C(0x0004) MISSED OFFSET
TArray<class APrimalDinoCharacter*> TamingFishes; // 0x2730(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
TArray<class UClass*> SpawnFishClasses; // 0x2740(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float SubmergedRotationRate; // 0x2750(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float UnsubmergedRotationRate; // 0x2754(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float AffinityBasePerSec; // 0x2758(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TPVOffsetMultiplier; // 0x275C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TameRate; // 0x2760(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float UnsubmergeBuoyancy; // 0x2764(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float SubmergeBuoyancy; // 0x2768(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bIsInRaftMode; // 0x276C(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, SaveGame, IsPlainOldData)
bool UseWidgetHUD; // 0x276D(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData10[0x2]; // 0x276E(0x0002) MISSED OFFSET
class UClass* HudWidgetClass; // 0x2770(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UUserWidget* HUDWidgetInstance; // 0x2778(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float CloseHUDWidgetDelay; // 0x2780(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
bool bAllowMating; // 0x2784(0x0001) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData11[0x3]; // 0x2785(0x0003) MISSED OFFSET
class FString UnableToMateString; // 0x2788(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance)
float TotalGrowthTimeFastGrowth; // 0x2798(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float GrowthTimeIntervalFastGrowth; // 0x279C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
double LastTickTime; // 0x27A0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float TamingFishRespawnTimer; // 0x27A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData12[0x4]; // 0x27AC(0x0004) MISSED OFFSET
class APrimalBuff* RaftModeDisplayBuff; // 0x27B0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData)
int MaxMushroomsToGiveOnUnstasis; // 0x27B8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxFlowersToGiveOnUnstasis; // 0x27BC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
int MaxSeedsToGiveOnUnstasis; // 0x27C0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData13[0x4]; // 0x27C4(0x0004) MISSED OFFSET
TArray<class APrimalCharacter*> BlowedAwayPawns; // 0x27C8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance)
class UTexture2D* BubbleHUDFillTexture; // 0x27D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UTexture2D* BubbleHUDInUseTexture; // 0x27E0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
float K2Node_Event_DeltaSeconds; // 0x27E8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData14[0x4]; // 0x27EC(0x0004) MISSED OFFSET
class FString CallFunc_Conv_FloatToString_ReturnValue; // 0x27F0(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Concat_StrStr_ReturnValue; // 0x2800(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Conv_FloatToString_ReturnValue2; // 0x2810(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
class FString CallFunc_Concat_StrStr_ReturnValue2; // 0x2820(0x0010) (ZeroConstructor, Transient, DuplicateTransient)
bool K2Node_CustomEvent_bIsBreathing; // 0x2830(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_BoolBool_ReturnValue; // 0x2831(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData15[0x2]; // 0x2832(0x0002) MISSED OFFSET
struct FVector K2Node_CustomEvent_BreathViewStartLocation; // 0x2834(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector K2Node_CustomEvent_BreathDirection; // 0x2840(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData16[0x4]; // 0x284C(0x0004) MISSED OFFSET
class AShooterPlayerController* K2Node_CustomEvent_OwnerContoler; // 0x2850(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_BPGetCurrentStatusValue_ReturnValue; // 0x2858(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_GreaterEqual_FloatFloat_ReturnValue; // 0x285C(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_LessEqual_FloatFloat_ReturnValue; // 0x285D(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData17[0x2]; // 0x285E(0x0002) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue; // 0x2860(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ByteByte_ReturnValue; // 0x2864(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData18[0x3]; // 0x2865(0x0003) MISSED OFFSET
float CallFunc_PlayAnimEx_ReturnValue2; // 0x2868(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData19[0x4]; // 0x286C(0x0004) MISSED OFFSET
class UAnimMontage* CallFunc_GetCurrentMontage_ReturnValue; // 0x2870(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ObjectObject_ReturnValue; // 0x2878(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ByteByte_ReturnValue2; // 0x2879(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_EqualEqual_ObjectObject_ReturnValue2; // 0x287A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool CallFunc_BooleanOR_ReturnValue; // 0x287B(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimEx_ReturnValue3; // 0x287C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_PlayAnimEx_ReturnValue4; // 0x2880(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData20[0x4]; // 0x2884(0x0004) MISSED OFFSET
class UAnimMontage* CallFunc_GetCurrentMontage_ReturnValue2; // 0x2888(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UAnimInstance* CallFunc_GetAnimInstance_ReturnValue; // 0x2890(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class UGiantTurtle_AnimBlueprintNew_C* K2Node_DynamicCast_AsGiantTurtle_AnimBlueprintNew_C; // 0x2898(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast_CastSuccess; // 0x28A0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
TEnumAsByte<ENetworkModeResult> CallFunc_CanRunCosmeticEvents_OutNetworkMode; // 0x28A1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_SwitchEnum_CmpSuccess; // 0x28A2(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData21[0x1]; // 0x28A3(0x0001) MISSED OFFSET
float CallFunc_SelectFloat_ReturnValue; // 0x28A4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue; // 0x28A8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FInterpTo_ReturnValue; // 0x28B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_FClamp_ReturnValue; // 0x28B8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue; // 0x28BC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
float CallFunc_Subtract_FloatFloat_ReturnValue; // 0x28C8(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_MakeVector_ReturnValue2; // 0x28CC(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
struct FVector CallFunc_Multiply_VectorFloat_ReturnValue2; // 0x28D8(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData22[0x4]; // 0x28E4(0x0004) MISSED OFFSET
double CallFunc_GetNetworkTimeInSeconds_ReturnValue; // 0x28E8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
class ABuff_Client_GiantTurtleRaftState_C* K2Node_DynamicCast_AsBuff_Client_GiantTurtleRaftState_C; // 0x28F0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
bool K2Node_DynamicCast2_CastSuccess; // 0x28F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData)
unsigned char UnknownData23[0x7]; // 0x28F9(0x0007) MISSED OFFSET
TArray<class AActor*> CallFunc_BoxOverlapActors_NEW_ActorsToIgnore_RefProperty; // 0x2900(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<int> CallFunc_FlockTickFollowersAndFreeAgents_BoidIndexWhitelist_RefProperty;// 0x2910(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<int> CallFunc_FlockTickLeaders_BoidIndexWhitelist_RefProperty; // 0x2920(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
TArray<class AActor*> CallFunc_LineTraceSingle_NEW_ActorsToIgnore_RefProperty; // 0x2930(0x0010) (OutParm, ZeroConstructor, Transient, DuplicateTransient, ReferenceParm)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass GiantTurtle_Character_BP.GiantTurtle_Character_BP_C");
return ptr;
}
bool BPCanBaseOnCharacter(class APrimalCharacter** BaseCharacter);
void BPBecomeAdult();
void BPBecomeBaby();
void BPUnstasis();
void BPOnDinoCheat(struct FName* CheatName, bool* bSetValue, float* Value);
void BPNotifyToggleHUD(bool* bHudHidden);
void OnRep_bAllowMating();
void ReceiveBeginPlay();
void GetAllowMating(bool* Allow);
void BlueprintDrawFloatingHUD(class AShooterHUD** HUD, float* CenterX, float* CenterY, float* DrawScale);
void UpdateAllowMating();
void BPTimerServer();
void ReceiveDestroyed();
void DestroyHUDWidget(bool DestroyNow);
void BPNotifyClearRider(class AShooterCharacter** RiderClearing);
void BPNotifySetRider(class AShooterCharacter** RiderSetting);
void BPNotifyLevelUp(int* ExtraCharacterLevel);
bool AllowPlayMontage(class UAnimMontage** AnimMontage);
bool BP_InterceptMoveForward(float* AxisValue);
void CheckRaftMode(float DeltaTime);
void BPPostLoadedFromSaveGame();
void ClearPreventHurtAnim();
void AnimBpSetBreathing(bool On);
void DestroySaddle();
void BPPlayDying(float* KillingDamage, class APawn** InstigatingPawn, class AActor** DamageCauser, struct FDamageEvent* DamageEvent);
void TickWake();
void UpdateMaterial();
void BubbleAttackToggle(bool On);
void BlueprintAnimNotifyCustomEvent(struct FName* CustomEventName, class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation, class UAnimNotify** AnimNotifyObject);
class UAnimMontage* BPOverrideHurtAnim(float* DamageTaken, class APawn** PawnInstigator, class AActor** DamageCauser, bool* bIsLocalPath, bool* bIsPointDamage, struct FVector* PointDamageLocation, struct FVector* PointDamageHitNormal, struct FDamageEvent* DamageEvent);
void CheckCave();
void TurnOffFlock();
float BPAdjustDamage(float* IncomingDamage, struct FDamageEvent* TheDamageEvent, class AController** EventInstigator, class AActor** DamageCauser, bool* bIsPointDamage, struct FHitResult* PointHitInfo);
void Setup_Flock();
void CheckTurtleTargetForFollowers();
void TickTaming(float DeltaSeconds);
void CheckFullyInWater();
void STATIC_TickBirdsFlock(float DeltaSeconds);
void PushBackPawnNotInWater(class APrimalCharacter* Pawn);
void TickBubbleCooldown(float DeltaSeconds);
void BPGetHUDElements(class APlayerController** ForPC, TArray<struct FHUDElement>* OutElements);
void UpdateBreath_Rotation();
void Tick_Breathing(float DeltSeconds);
float BPGetCrosshairAlpha();
bool BPHandleControllerInitiatedAttack(int* AttackIndex);
bool BPHandleOnStopTargeting();
void STATIC_GetPlayersOnSeats();
void K2_OnMovementModeChanged(TEnumAsByte<EMovementMode>* PrevMovementMode, TEnumAsByte<EMovementMode>* NewMovementMode, unsigned char* PrevCustomMode, unsigned char* NewCustomMode);
bool BlueprintCanRiderAttack(int* AttackIndex);
void SpawnBubble();
float BP_GetCustomModifier_RotationRate();
void STATIC_Setup_New_Crop_DataStruct(int LocationIndex, class UPrimalItemConsumableSeed_C* SeedItem);
void Check_Inventory_for_Seed_Items();
void GetCropGrowLocation(int* LocationIndex);
void SpawnOxygenVFX();
void Update_CropsVisuals();
void UpdateFlowerAndMushroom(float DeltaSecond);
void STATIC_UpdateCropStructs(float DeltaSeconds);
void STATIC_AddOxygenBuff();
void BPNotifyInventoryItemChange(bool* bIsItemAdd, class UPrimalItem** theItem, bool* bEquipItem);
void GetMovementMontage(TEnumAsByte<ERootMotionMovementMode> Mode, class UAnimMontage** Montage);
struct FVector BPGetRiderUnboardLocation(class APrimalCharacter** RidingCharacter);
void UserConstructionScript();
void ReceiveTick(float* DeltaSeconds);
void SpawnBubbles();
void Server_SetIsBreathing(bool bIsBreathing);
void Server_SetBreathDirection(const struct FVector& BreathViewStartLocation, const struct FVector& BreathDirection);
void Server_TryBubbleAttack(class AShooterPlayerController* OwnerContoler);
void Server_StopBubbleAttack();
void Multi_StopCurrentMontage();
void ExecuteUbergraph_GiantTurtle_Character_BP(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 137.611486
| 270
| 0.558859
|
2bite
|
cbc0c05ba53e0d28b2d17504ee3360b3a1f1e423
| 1,455
|
cpp
|
C++
|
trees/priority_queue.cpp
|
triffon/sdp-2015-16
|
bb15cea4b4cad7791d82f55d106c3975b287af4e
|
[
"MIT"
] | 3
|
2015-10-12T14:02:43.000Z
|
2021-06-22T13:02:48.000Z
|
trees/priority_queue.cpp
|
triffon/sdp-2015-16
|
bb15cea4b4cad7791d82f55d106c3975b287af4e
|
[
"MIT"
] | null | null | null |
trees/priority_queue.cpp
|
triffon/sdp-2015-16
|
bb15cea4b4cad7791d82f55d106c3975b287af4e
|
[
"MIT"
] | null | null | null |
/*
* priority_queue.cpp
*
* Created on: 4.12.2015 г.
* Author: trifon
*/
#include "bintree.cpp"
template <typename T>
class PriorityQueue : BinaryTree<T> {
private:
using P = BinaryTreePosition<T>;
void insertAndSiftUp(P pos, T const& x) {
if (pos) {
P newpos = (x % 2) ? -pos : +pos;
insertAndSiftUp(newpos, x);
// sift up
if (*newpos > *pos)
swap(*newpos, *pos);
} else {
// insert
BinaryTree<T>::assignFrom(pos, BinaryTree<T>(x));
}
}
P findLeaf(P pos) const {
if (!pos || (!-pos && !+pos))
return pos;
if (!-pos)
return findLeaf(+pos);
if (!+pos)
return findLeaf(-pos);
return findLeaf((*pos % 2) ? -pos : +pos);
}
P maxChild(P pos) {
if (!-pos)
return +pos;
if (!+pos)
return -pos;
return *-pos > *+pos ? -pos : +pos;
}
void siftDown(P pos) {
if (pos) {
P maxcpos = maxChild(pos);
if (maxcpos && *pos < *maxcpos)
swap(*maxcpos, *pos);
siftDown(maxcpos);
}
}
public:
bool empty() const { return BinaryTree<T>::empty(); }
T head() { return *BinaryTree<T>::root(); }
void enqueue_prioritized(T const& x) {
insertAndSiftUp(BinaryTree<T>::root(), x);
}
T dequeue_highest() {
P rpos = BinaryTree<T>::root();
T result = head();
P pos = findLeaf(rpos);
swap(*pos,*rpos);
BinaryTree<T>::deleteAt(pos);
siftDown(rpos);
return result;
}
void printDOT(char const* filename) {
::printDOT((BinaryTree<T>&)(*this), filename);
}
};
| 17.962963
| 54
| 0.58488
|
triffon
|
cbc52e1b7326324fe9d676e4322614e29ea60d75
| 1,128
|
cpp
|
C++
|
leetcode_solutions/others/leetcode_492.cpp
|
EatAllBugs/leetcode_cpp
|
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
|
[
"MIT"
] | 4
|
2021-12-07T19:39:03.000Z
|
2021-12-23T09:15:08.000Z
|
leetcode_solutions/others/leetcode_492.cpp
|
EatAllBugs/leetcode_cpp
|
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
|
[
"MIT"
] | null | null | null |
leetcode_solutions/others/leetcode_492.cpp
|
EatAllBugs/leetcode_cpp
|
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<limits.h>
#include<algorithm>
#include<numeric>
#include<unordered_set>
#include<cmath>
using namespace std;
/*
作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:
1. 你设计的矩形页面必须等于给定的目标面积。
2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。
3. 长度 L 和宽度 W 之间的差距应当尽可能小。
你需要按顺序输出你设计的页面的长度 L 和宽度 W。
示例:
输入: 4
输出: [2, 2]
解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。
说明:
给定的面积不大于 10,000,000 且为正整数。
你设计的页面的长度和宽度必须都是正整数。
*/
class Solution {
public:
vector<int> constructRectangle(int area) {
int mid = sqrt(area);
int w = mid, l = mid;
vector<int> ans;
while (w > 0 && l < area && w <= l) {
if (area % w == 0 && l * w == area) {
vector<int> ans = {l, w};
return ans;
} else if (l * w < area) {
l++;
} else if (l * w > area) {
w--;
}
}
return ans;
}
};
int main() {
int g = 10000000;
Solution app;
vector<int> ans = app.constructRectangle(g);
cout << ans[0] << endl;
cout << ans[1] << endl;
return 0;
}
| 20.888889
| 87
| 0.590426
|
EatAllBugs
|
cbc810cfeb0de84d45088c9b9ecb861e9f28e79d
| 586
|
cpp
|
C++
|
zoe/src/zoe/display/Game/Sprite.cpp
|
NudelErde/zoe
|
456e38bba86058f006a7c0fd5168af5039714c6c
|
[
"MIT"
] | 7
|
2019-12-16T20:23:39.000Z
|
2020-10-26T08:46:12.000Z
|
zoe/src/zoe/display/Game/Sprite.cpp
|
NudelErde/zoe
|
456e38bba86058f006a7c0fd5168af5039714c6c
|
[
"MIT"
] | 13
|
2020-01-13T20:19:06.000Z
|
2021-09-10T21:23:52.000Z
|
zoe/src/zoe/display/Game/Sprite.cpp
|
NudelErde/zoe
|
456e38bba86058f006a7c0fd5168af5039714c6c
|
[
"MIT"
] | 7
|
2019-12-29T22:46:23.000Z
|
2020-07-15T19:56:32.000Z
|
//
// Created by Florian on 10.07.2020.
//
#include "Sprite.h"
namespace Zoe{
void Sprite::onDraw(const Camera& camera) {}
void Sprite::onUpdate(double time) {}
void Sprite::onInputEvent(Event &event) {}
void Sprite::fill(const XMLNode &node) {
if(node.attributes.count("x")>0){
position.x = std::stof(node.attributes.at("x"));
}
if(node.attributes.count("y")>0){
position.y = std::stof(node.attributes.at("y"));
}
if(node.attributes.count("z")>0){
position.z = std::stof(node.attributes.at("z"));
}
}
void Sprite::postFill() {
}
}
| 20.206897
| 56
| 0.616041
|
NudelErde
|
cbce4032e94199fa3e8d2c448f4278774f45f7fa
| 2,692
|
cpp
|
C++
|
sources/http/response.cpp
|
deguangchow/NetFlex
|
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
|
[
"MIT"
] | null | null | null |
sources/http/response.cpp
|
deguangchow/NetFlex
|
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
|
[
"MIT"
] | null | null | null |
sources/http/response.cpp
|
deguangchow/NetFlex
|
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
|
[
"MIT"
] | null | null | null |
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// 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 <netflex/http/response.hpp>
#include <netflex/misc/output.hpp>
namespace netflex {
namespace http {
//!
//! ctor & dtor
//!
response::response(void)
: m_sHttpVersion("HTTP/1.1")
, m_uStatusCode(200)
, m_sReason("OK") {}
//!
//! convert response to http packet
//!
std::string
response::to_http_packet(void) const {
return misc::status_line_to_http_packet(m_sHttpVersion, m_uStatusCode, m_sReason) +
misc::header_list_to_http_packet(m_mapHeaders) + m_sBody;
}
//!
//! status line
//!
const std::string&
response::get_http_version(void) const {
return m_sHttpVersion;
}
unsigned int
response::get_status_code(void) const {
return m_uStatusCode;
}
const std::string&
response::get_reason_phase(void) const {
return m_sReason;
}
void
response::set_http_version(const std::string& version) {
m_sHttpVersion = version;
}
void
response::set_status_code(unsigned int code) {
m_uStatusCode = code;
}
void
response::set_reason_phrase(const std::string& reason) {
m_sReason = reason;
}
//!
//! headers
//!
const header_list_t&
response::get_headers(void) const {
return m_mapHeaders;
}
void
response::add_header(const header& header) {
m_mapHeaders[header.field_name] = header.field_value;
}
void
response::set_headers(const header_list_t& headers) {
m_mapHeaders = headers;
}
//!
//! body
//!
const std::string&
response::get_body(void) const {
return m_sBody;
}
void
response::set_body(const std::string& body) {
m_sBody = body;
}
} // namespace http
} // namespace netflex
| 22.813559
| 85
| 0.737741
|
deguangchow
|
cbd0cecbc1a854b0bac056d1739c3577662fc95e
| 1,155
|
cpp
|
C++
|
C++/problem0594.cpp
|
1050669722/LeetCode-Answers
|
c8f4d1ccaac09cda63b60d75144335347b06dc81
|
[
"MIT"
] | null | null | null |
C++/problem0594.cpp
|
1050669722/LeetCode-Answers
|
c8f4d1ccaac09cda63b60d75144335347b06dc81
|
[
"MIT"
] | null | null | null |
C++/problem0594.cpp
|
1050669722/LeetCode-Answers
|
c8f4d1ccaac09cda63b60d75144335347b06dc81
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <windows.h>
#include <string>
#include <numeric>
using namespace std;
class Solution
{
public:
int findLHS(vector<int>& nums) {
map<int, int> d;
vector<int>::iterator it;
for (it = nums.begin(); it < nums.end(); ++it)
{
// if (d.count(*it))
// {
// d[*it]++;
// }
// else
// {
// d[*it] = 1;
// }
d[*it]++;
}
map<int, int>::iterator iter;
int ans = 0;
for (iter = d.begin(); iter != d.end(); ++iter)
{
cout << iter->first << ' ' << iter->second << endl;
if (d.count(iter->first-1))
{
ans = max(ans, iter->second+d[iter->first-1]);
}
}
return ans;
}
};
int main()
{
vector<int> nums {1,3,2,2,5,2,3,7};
Solution solu;
int ans = solu.findLHS(nums);
cout << ans << endl;
return 0;
}
| 21
| 63
| 0.442424
|
1050669722
|
cbd7b33cdc290bfc98be048f396e031fd1ca7586
| 1,472
|
hpp
|
C++
|
include/Jam/Instance.hpp
|
DrJonki/Kajak-Games-Finlandia-Jam
|
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
|
[
"MIT"
] | null | null | null |
include/Jam/Instance.hpp
|
DrJonki/Kajak-Games-Finlandia-Jam
|
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
|
[
"MIT"
] | null | null | null |
include/Jam/Instance.hpp
|
DrJonki/Kajak-Games-Finlandia-Jam
|
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
|
[
"MIT"
] | null | null | null |
#pragma once
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Network/TcpSocket.hpp>
#include <SFML/Network/UdpSocket.hpp>
#include <rapidjson/document.h>
#include <memory>
#include <Jam/ResourceManager.hpp>
#include <Jam/ConfigManager.hpp>
#include <Jam/PostProcessor.hpp>
#include <set>
namespace sf
{
class TcpSocket;
class UdpSocket;
class Socket;
}
namespace jam
{
class Scene;
class Instance final
{
Instance(const Instance&) = delete;
void operator =(const Instance&) = delete;
public:
Instance();
~Instance();
void operator ()();
bool sendMessage(const char* message, const bool tcp);
bool sendMessage(const char* message, rapidjson::Value& data, const bool tcp);
sf::Time getLastPingTime() const;
private:
sf::TcpSocket& tcpSocket();
sf::UdpSocket& udpSocket();
void connectTcp();
public:
// Globals
ConfigManager config;
sf::RenderWindow window;
sf::RenderTexture framebuffer[2];
std::unique_ptr<Scene> currentScene;
ResourceManager resourceManager;
PostProcessor postProcessor;
public:
sf::Clock m_clock;
private:
std::pair<sf::TcpSocket, sf::UdpSocket> m_sockets;
sf::RectangleShape m_quad;
sf::Clock m_pingTimer;
sf::Clock m_pingClock;
sf::Time m_lastPingTime;
std::string m_udpId;
};
}
| 19.116883
| 82
| 0.696332
|
DrJonki
|
cbdbda7941c47992cd7ca837bfd8134df0947c23
| 3,439
|
cpp
|
C++
|
secure_tunneling/source/IotSecureTunnelingClient.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 88
|
2019-11-29T19:30:29.000Z
|
2022-03-28T02:29:51.000Z
|
secure_tunneling/source/IotSecureTunnelingClient.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 194
|
2019-12-01T15:54:42.000Z
|
2022-03-31T22:06:11.000Z
|
secure_tunneling/source/IotSecureTunnelingClient.cpp
|
gregbreen/aws-iot-device-sdk-cpp-v2
|
57ded0046d1cda3b35fbe9298eed308392961435
|
[
"Apache-2.0"
] | 64
|
2019-12-17T14:13:40.000Z
|
2022-03-12T07:43:13.000Z
|
/* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* This file is generated
*/
#include <aws/iotsecuretunneling/IotSecureTunnelingClient.h>
#include <aws/iotsecuretunneling/SecureTunnelingNotifyResponse.h>
#include <aws/iotsecuretunneling/SubscribeToTunnelsNotifyRequest.h>
namespace Aws
{
namespace Iotsecuretunneling
{
IotSecureTunnelingClient::IotSecureTunnelingClient(
const std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> &connection)
: m_connection(connection)
{
}
IotSecureTunnelingClient::operator bool() const noexcept { return *m_connection; }
int IotSecureTunnelingClient::GetLastError() const noexcept { return aws_last_error(); }
bool IotSecureTunnelingClient::SubscribeToTunnelsNotify(
const Aws::Iotsecuretunneling::SubscribeToTunnelsNotifyRequest &request,
Aws::Crt::Mqtt::QOS qos,
const OnSubscribeToTunnelsNotifyResponse &handler,
const OnSubscribeComplete &onSubAck)
{
(void)request;
auto onSubscribeComplete = [handler, onSubAck](
Aws::Crt::Mqtt::MqttConnection &,
uint16_t,
const Aws::Crt::String &topic,
Aws::Crt::Mqtt::QOS,
int errorCode) {
(void)topic;
if (errorCode)
{
handler(nullptr, errorCode);
}
if (onSubAck)
{
onSubAck(errorCode);
}
};
auto onSubscribePublish =
[handler](
Aws::Crt::Mqtt::MqttConnection &, const Aws::Crt::String &, const Aws::Crt::ByteBuf &payload) {
Aws::Crt::String objectStr(reinterpret_cast<char *>(payload.buffer), payload.len);
Aws::Crt::JsonObject jsonObject(objectStr);
Aws::Iotsecuretunneling::SecureTunnelingNotifyResponse response(jsonObject);
handler(&response, AWS_ERROR_SUCCESS);
};
Aws::Crt::StringStream subscribeTopicSStr;
subscribeTopicSStr << "$aws"
<< "/"
<< "things"
<< "/" << *request.ThingName << "/"
<< "tunnels"
<< "/"
<< "notify";
return m_connection->Subscribe(
subscribeTopicSStr.str().c_str(),
qos,
std::move(onSubscribePublish),
std::move(onSubscribeComplete)) != 0;
}
} // namespace Iotsecuretunneling
} // namespace Aws
| 38.640449
| 115
| 0.540855
|
gregbreen
|
cbf49c5a24e61e4f2b4d97be0848f6efdc9ebb5b
| 4,236
|
hpp
|
C++
|
Manipulation.hpp
|
theoden8/rubikscube
|
94ffd4a99f03729b28db41f1b05cbb208b4eceba
|
[
"MIT"
] | 1
|
2021-03-22T22:14:49.000Z
|
2021-03-22T22:14:49.000Z
|
Manipulation.hpp
|
theoden8/rubikscube
|
94ffd4a99f03729b28db41f1b05cbb208b4eceba
|
[
"MIT"
] | null | null | null |
Manipulation.hpp
|
theoden8/rubikscube
|
94ffd4a99f03729b28db41f1b05cbb208b4eceba
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cmath>
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884L
#endif
#include <vector>
#include <queue>
#include <Logger.hpp>
#include <Debug.hpp>
#include <Face.hpp>
struct Manipulation {
const Face face;
const Rotation rot;
float progress = 0.;
/* inline Manipulation() */
/* {} */
inline Manipulation(Face f, Rotation r, float progress=0.):
face(f), rot(r), progress(progress)
{}
static Manipulation make_random() {
return Manipulation(get_random_face(), get_random_rotation());
}
inline bool is_complete() const {
/* Logger::Info("progress: %.4f, %.4f\n", progress, std::abs(1.-progress)); */
return std::abs(progress - 1.0) < 1e-5;
}
inline bool is_close() const {
return std::abs(progress - 1.0) < 1e-2;
}
inline decltype(auto) inverse() const {
return Manipulation(
face,
rot == Rotation::CLOCKWISE ?
Rotation::COUNTERCLOCKWISE
: Rotation::CLOCKWISE,
1. - progress
);
}
};
class ManipulationPerformer {
std::vector<Manipulation> timeline;
std::queue<Manipulation> performQueue;
int currentIndex = -1;
float speed = 1.;
double previous_time = 0.;
template <typename RubiksCubeT>
void rotate_face(RubiksCubeT &rb, const Manipulation &m, float deg) {
static constexpr glm::vec3
axis_z(0, 0, 1),
axis_y(0, 1, 0),
axis_x(1, 0, 0);
glm::vec3 axis;
float sign = 0.;
const Face &f = m.face;
const Rotation &r = m.rot;
if((f == Face::Z_FRONT && r == Rotation::CLOCKWISE)
|| (f == Face::Z_BACK && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_z;
sign = 1.;
} else if((f == Face::Z_BACK && r == Rotation::CLOCKWISE)
|| (f == Face::Z_FRONT && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_z;
sign = -1.;
} else if((f == Face::Y_FRONT && r == Rotation::CLOCKWISE)
|| (f == Face::Y_BACK && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_y;
sign = 1.;
} else if((f == Face::Y_BACK && r == Rotation::CLOCKWISE)
|| (f == Face::Y_FRONT && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_y;
sign = -1.;
} else if((f == Face::X_FRONT && r == Rotation::CLOCKWISE)
|| (f == Face::X_BACK && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_x;
sign = 1.;
} else if((f == Face::X_BACK && r == Rotation::CLOCKWISE)
|| (f == Face::X_FRONT && r == Rotation::COUNTERCLOCKWISE))
{
axis = axis_x;
sign = -1.;
}
rb.select_face(f, [&](Facing &f, const Face &face) mutable -> void {
f.getCubeTransform().Rotate(axis, sign * deg);
});
}
public:
ManipulationPerformer()
{}
template <typename RubiksCubeT>
void rotate_face(RubiksCubeT &rb, Manipulation &m) {
if(m.is_complete())return;
double current_time_step = fmax(glfwGetTime() - previous_time, .5);
float deg = std::sin((0.5 + m.progress * .5) * M_PI) * 90. * .03 * current_time_step * speed * std::sqrt(performQueue.size());
#if !defined(_POSIX_VERSION)
deg *= 10;
#endif
if((m.progress + deg / 90. > 1.) || m.is_close()) {
deg = (1. - m.progress) * 90.;
}
rotate_face(rb, m, deg);
m.progress = (m.progress * 90. + deg) / 90.;
previous_time = glfwGetTime();
}
void set_new(Manipulation m) {
++currentIndex;
if(currentIndex == timeline.size()) {
timeline.push_back(m);
performQueue.push(m);
} else {
while(currentIndex < timeline.size()) {
performQueue.push(timeline.back().inverse());
performQueue.pop();
}
timeline.push_back(m);
performQueue.push(m);
}
}
void take_back() {
if(currentIndex == -1)return;
Manipulation m = timeline[currentIndex--].inverse();
m.progress = 0.;
performQueue.push(m);
}
int count() const {
return currentIndex + 1;
}
template <typename RubiksCubeT>
void perform_step(RubiksCubeT &rb) {
if(performQueue.empty())return;
while(performQueue.front().is_complete()) {
rb.update_face_types(performQueue.front());
performQueue.pop();
if(performQueue.empty())return;
}
rotate_face(rb, performQueue.front());
}
};
| 24.485549
| 130
| 0.595373
|
theoden8
|
cbf69c5dd1c88758b676cdbdba78f8059d3ae2df
| 13,160
|
hpp
|
C++
|
src/util/lp/square_dense_submatrix.hpp
|
greatmazinger/z3
|
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
|
[
"MIT"
] | 18
|
2018-05-25T03:16:11.000Z
|
2022-01-25T01:41:20.000Z
|
src/util/lp/square_dense_submatrix.hpp
|
greatmazinger/z3
|
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
|
[
"MIT"
] | null | null | null |
src/util/lp/square_dense_submatrix.hpp
|
greatmazinger/z3
|
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
|
[
"MIT"
] | 9
|
2019-11-12T05:42:08.000Z
|
2022-02-18T01:09:53.000Z
|
/*++
Copyright (c) 2017 Microsoft Corporation
Module Name:
<name>
Abstract:
<abstract>
Author:
Lev Nachmanson (levnach)
Revision History:
--*/
#include "util/vector.h"
#include "util/lp/square_dense_submatrix.h"
namespace lp {
template <typename T, typename X>
square_dense_submatrix<T, X>::square_dense_submatrix (sparse_matrix<T, X> *parent_matrix, unsigned index_start) :
m_index_start(index_start),
m_dim(parent_matrix->dimension() - index_start),
m_v(m_dim * m_dim),
m_parent(parent_matrix),
m_row_permutation(m_parent->dimension()),
m_column_permutation(m_parent->dimension()) {
int row_offset = - static_cast<int>(m_index_start);
for (unsigned i = index_start; i < parent_matrix->dimension(); i++) {
unsigned row = parent_matrix->adjust_row(i);
for (auto & iv : parent_matrix->get_row_values(row)) {
unsigned j = parent_matrix->adjust_column_inverse(iv.m_index);
SASSERT(j>= m_index_start);
m_v[row_offset + j] = iv.m_value;
}
row_offset += m_dim;
}
}
template <typename T, typename X> void square_dense_submatrix<T, X>::init(sparse_matrix<T, X> *parent_matrix, unsigned index_start) {
m_index_start = index_start;
m_dim = parent_matrix->dimension() - index_start;
m_v.resize(m_dim * m_dim);
m_parent = parent_matrix;
m_column_permutation.init(m_parent->dimension());
for (unsigned i = index_start; i < parent_matrix->dimension(); i++) {
unsigned row = parent_matrix->adjust_row(i);
for (auto & iv : parent_matrix->get_row_values(row)) {
unsigned j = parent_matrix->adjust_column_inverse(iv.m_index);
(*this)[i][j] = iv.m_value;
}
}
}
template <typename T, typename X> int square_dense_submatrix<T, X>::find_pivot_column_in_row(unsigned i) const {
int j = -1;
T max = zero_of_type<T>();
SASSERT(i >= m_index_start);
unsigned row_start = (i - m_index_start) * m_dim;
for (unsigned k = i; k < m_parent->dimension(); k++) {
unsigned col = adjust_column(k); // this is where the column is in the row
unsigned offs = row_start + col - m_index_start;
T t = abs(m_v[offs]);
if (t > max) {
j = k;
max = t;
}
}
return j;
}
template <typename T, typename X> void square_dense_submatrix<T, X>::pivot(unsigned i, lp_settings & settings) {
divide_row_by_pivot(i);
for (unsigned k = i + 1; k < m_parent->dimension(); k++)
pivot_row_to_row(i, k, settings);
}
template <typename T, typename X> void square_dense_submatrix<T, X>::pivot_row_to_row(unsigned i, unsigned row, lp_settings & settings) {
SASSERT(i < row);
unsigned pj = adjust_column(i); // the pivot column
unsigned pjd = pj - m_index_start;
unsigned pivot_row_offset = (i-m_index_start)*m_dim;
T pivot = m_v[pivot_row_offset + pjd];
unsigned row_offset= (row-m_index_start)*m_dim;
T m = m_v[row_offset + pjd];
SASSERT(!is_zero(pivot));
m_v[row_offset + pjd] = -m * pivot; // creating L matrix
for (unsigned j = m_index_start; j < m_parent->dimension(); j++) {
if (j == pj) {
pivot_row_offset++;
row_offset++;
continue;
}
auto t = m_v[row_offset] - m_v[pivot_row_offset] * m;
if (settings.abs_val_is_smaller_than_drop_tolerance(t)) {
m_v[row_offset] = zero_of_type<T>();
} else {
m_v[row_offset] = t;
}
row_offset++; pivot_row_offset++;
// at the same time we pivot the L too
}
}
template <typename T, typename X> void square_dense_submatrix<T, X>::divide_row_by_pivot(unsigned i) {
unsigned pj = adjust_column(i); // the pivot column
unsigned irow_offset = (i - m_index_start) * m_dim;
T pivot = m_v[irow_offset + pj - m_index_start];
SASSERT(!is_zero(pivot));
for (unsigned k = m_index_start; k < m_parent->dimension(); k++) {
if (k == pj){
m_v[irow_offset++] = one_of_type<T>() / pivot; // creating the L matrix diagonal
continue;
}
m_v[irow_offset++] /= pivot;
}
}
template <typename T, typename X> void square_dense_submatrix<T, X>::update_parent_matrix(lp_settings & settings) {
for (unsigned i = m_index_start; i < m_parent->dimension(); i++)
update_existing_or_delete_in_parent_matrix_for_row(i, settings);
push_new_elements_to_parent_matrix(settings);
for (unsigned i = m_index_start; i < m_parent->dimension(); i++)
m_parent->set_max_in_row(m_parent->adjust_row(i));
}
template <typename T, typename X> void square_dense_submatrix<T, X>::update_existing_or_delete_in_parent_matrix_for_row(unsigned i, lp_settings & settings) {
bool diag_updated = false;
unsigned ai = m_parent->adjust_row(i);
auto & row_vals = m_parent->get_row_values(ai);
for (unsigned k = 0; k < row_vals.size(); k++) {
auto & iv = row_vals[k];
unsigned j = m_parent->adjust_column_inverse(iv.m_index);
if (j < i) {
m_parent->remove_element(row_vals, iv);
k--;
} else if (i == j) {
m_parent->m_columns[iv.m_index].m_values[iv.m_other].set_value(iv.m_value = one_of_type<T>());
diag_updated = true;
} else { // j > i
T & v = (*this)[i][j];
if (settings.abs_val_is_smaller_than_drop_tolerance(v)) {
m_parent->remove_element(row_vals, iv);
k--;
} else {
m_parent->m_columns[iv.m_index].m_values[iv.m_other].set_value(iv.m_value = v);
v = zero_of_type<T>(); // only new elements are left above the diagonal
}
}
}
if (!diag_updated) {
unsigned aj = m_parent->adjust_column(i);
m_parent->add_new_element(ai, aj, one_of_type<T>());
}
}
template <typename T, typename X> void square_dense_submatrix<T, X>::push_new_elements_to_parent_matrix(lp_settings & settings) {
for (unsigned i = m_index_start; i < m_parent->dimension() - 1; i++) {
unsigned ai = m_parent->adjust_row(i);
for (unsigned j = i + 1; j < m_parent->dimension(); j++) {
T & v = (*this)[i][j];
if (!settings.abs_val_is_smaller_than_drop_tolerance(v)) {
unsigned aj = m_parent->adjust_column(j);
m_parent->add_new_element(ai, aj, v);
}
v = zero_of_type<T>(); // leave only L elements now
}
}
}
template <typename T, typename X>
template <typename L>
L square_dense_submatrix<T, X>::row_by_vector_product(unsigned i, const vector<L> & v) {
SASSERT(i >= m_index_start);
unsigned row_in_subm = i - m_index_start;
unsigned row_offset = row_in_subm * m_dim;
L r = zero_of_type<L>();
for (unsigned j = 0; j < m_dim; j++)
r += m_v[row_offset + j] * v[adjust_column_inverse(m_index_start + j)];
return r;
}
template <typename T, typename X>
template <typename L>
L square_dense_submatrix<T, X>::column_by_vector_product(unsigned j, const vector<L> & v) {
SASSERT(j >= m_index_start);
unsigned offset = j - m_index_start;
L r = zero_of_type<L>();
for (unsigned i = 0; i < m_dim; i++, offset += m_dim)
r += m_v[offset] * v[adjust_row_inverse(m_index_start + i)];
return r;
}
template <typename T, typename X>
template <typename L>
L square_dense_submatrix<T, X>::row_by_indexed_vector_product(unsigned i, const indexed_vector<L> & v) {
SASSERT(i >= m_index_start);
unsigned row_in_subm = i - m_index_start;
unsigned row_offset = row_in_subm * m_dim;
L r = zero_of_type<L>();
for (unsigned j = 0; j < m_dim; j++)
r += m_v[row_offset + j] * v[adjust_column_inverse(m_index_start + j)];
return r;
}
template <typename T, typename X>
template <typename L>
void square_dense_submatrix<T, X>::apply_from_left_local(indexed_vector<L> & w, lp_settings & settings) {
#ifdef Z3DEBUG
// dense_matrix<T, X> deb(*this);
// vector<L> deb_w(w.m_data.size());
// for (unsigned i = 0; i < w.m_data.size(); i++)
// deb_w[i] = w[i];
// deb.apply_from_left(deb_w);
#endif // use indexed vector here
#ifndef DO_NOT_USE_INDEX
vector<L> t(m_parent->dimension(), zero_of_type<L>());
for (auto k : w.m_index) {
unsigned j = adjust_column(k); // k-th element will contribute only to column j
if (j < m_index_start || j >= this->m_index_start + this->m_dim) { // it is a unit matrix outside
t[adjust_row_inverse(j)] = w[k];
} else {
const L & v = w[k];
for (unsigned i = 0; i < m_dim; i++) {
unsigned row = adjust_row_inverse(m_index_start + i);
unsigned offs = i * m_dim + j - m_index_start;
t[row] += m_v[offs] * v;
}
}
}
w.m_index.clear();
for (unsigned i = 0; i < m_parent->dimension(); i++) {
const L & v = t[i];
if (!settings.abs_val_is_smaller_than_drop_tolerance(v)){
w.m_index.push_back(i);
w.m_data[i] = v;
} else {
w.m_data[i] = zero_of_type<L>();
}
}
#else
vector<L> t(m_parent->dimension());
for (unsigned i = 0; i < m_index_start; i++) {
t[adjust_row_inverse(i)] = w[adjust_column_inverse(i)];
}
for (unsigned i = m_index_start; i < m_parent->dimension(); i++){
t[adjust_row_inverse(i)] = row_by_indexed_vector_product(i, w);
}
for (unsigned i = 0; i < m_parent->dimension(); i++) {
w.set_value(t[i], i);
}
for (unsigned i = 0; i < m_parent->dimension(); i++) {
const L & v = t[i];
if (!is_zero(v))
w.m_index.push_back(i);
w.m_data[i] = v;
}
#endif
#ifdef Z3DEBUG
// cout << "w final" << endl;
// print_vector(w.m_data);
// SASSERT(vectors_are_equal<T>(deb_w, w.m_data));
// SASSERT(w.is_OK());
#endif
}
template <typename T, typename X>
template <typename L>
void square_dense_submatrix<T, X>::apply_from_left_to_vector(vector<L> & w) {
// lp_settings & settings) {
// dense_matrix<T, L> deb(*this);
// vector<L> deb_w(w);
// deb.apply_from_left_to_X(deb_w, settings);
// // cout << "deb" << endl;
// // print_matrix(deb);
// // cout << "w" << endl;
// // print_vector(w.m_data);
// // cout << "deb_w" << endl;
// // print_vector(deb_w);
vector<L> t(m_parent->dimension());
for (unsigned i = 0; i < m_index_start; i++) {
t[adjust_row_inverse(i)] = w[adjust_column_inverse(i)];
}
for (unsigned i = m_index_start; i < m_parent->dimension(); i++){
t[adjust_row_inverse(i)] = row_by_vector_product(i, w);
}
for (unsigned i = 0; i < m_parent->dimension(); i++) {
w[i] = t[i];
}
#ifdef Z3DEBUG
// cout << "w final" << endl;
// print_vector(w.m_data);
// SASSERT(vectors_are_equal<L>(deb_w, w));
#endif
}
template <typename T, typename X> bool square_dense_submatrix<T, X>::is_L_matrix() const {
#ifdef Z3DEBUG
SASSERT(m_row_permutation.is_identity());
for (unsigned i = 0; i < m_parent->dimension(); i++) {
if (i < m_index_start) {
SASSERT(m_column_permutation[i] == i);
continue;
}
unsigned row_offs = (i-m_index_start)*m_dim;
for (unsigned k = 0; k < m_dim; k++) {
unsigned j = m_index_start + k;
unsigned jex = adjust_column_inverse(j);
if (jex > i) {
SASSERT(is_zero(m_v[row_offs + k]));
} else if (jex == i) {
SASSERT(!is_zero(m_v[row_offs + k]));
}
}
}
#endif
return true;
}
template <typename T, typename X> void square_dense_submatrix<T, X>::apply_from_right(vector<T> & w) {
#ifdef Z3DEBUG
// dense_matrix<T, X> deb(*this);
// vector<T> deb_w(w);
// deb.apply_from_right(deb_w);
#endif
vector<T> t(w.size());
for (unsigned j = 0; j < m_index_start; j++) {
t[adjust_column_inverse(j)] = w[adjust_row_inverse(j)];
}
unsigned end = m_index_start + m_dim;
for (unsigned j = end; j < m_parent->dimension(); j++) {
t[adjust_column_inverse(j)] = w[adjust_row_inverse(j)];
}
for (unsigned j = m_index_start; j < end; j++) {
t[adjust_column_inverse(j)] = column_by_vector_product(j, w);
}
w = t;
#ifdef Z3DEBUG
// SASSERT(vector_are_equal<T>(deb_w, w));
#endif
}
#ifdef Z3DEBUG
template <typename T, typename X> T square_dense_submatrix<T, X>::get_elem (unsigned i, unsigned j) const {
i = adjust_row(i);
j = adjust_column(j);
if (i < m_index_start || j < m_index_start)
return i == j? one_of_type<T>() : zero_of_type<T>();
unsigned offs = (i - m_index_start)* m_dim + j - m_index_start;
return m_v[offs];
}
#endif
template <typename T, typename X> void square_dense_submatrix<T, X>::conjugate_by_permutation(permutation_matrix<T, X> & q) {
m_row_permutation.multiply_by_permutation_from_left(q);
m_column_permutation.multiply_by_reverse_from_right(q);
}
}
| 35.663957
| 160
| 0.607979
|
greatmazinger
|
cbf72f21062fb5d21cb485db47a0c04898cd36de
| 7,545
|
cpp
|
C++
|
src/liblvr2/io/BoctreeIO.cpp
|
uos/lvr
|
9bb03a30441b027c39db967318877e03725112d5
|
[
"BSD-3-Clause"
] | 38
|
2019-06-19T15:10:35.000Z
|
2022-02-16T03:08:24.000Z
|
src/liblvr2/io/BoctreeIO.cpp
|
uos/lvr
|
9bb03a30441b027c39db967318877e03725112d5
|
[
"BSD-3-Clause"
] | 9
|
2019-06-19T16:19:51.000Z
|
2021-09-17T08:31:25.000Z
|
src/liblvr2/io/BoctreeIO.cpp
|
uos/lvr
|
9bb03a30441b027c39db967318877e03725112d5
|
[
"BSD-3-Clause"
] | 13
|
2019-04-16T11:50:32.000Z
|
2020-11-26T07:47:44.000Z
|
/**
* Copyright (c) 2018, University Osnabrück
* 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 Osnabrück 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 University Osnabrück 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.
*/
/**
* BoctreeIO.cpp
*
* @date 23.08.2012
* @author Thomas Wiemann
*/
#include <stdio.h>
#include "lvr2/io/BoctreeIO.hpp"
#include "lvr2/io/Timestamp.hpp"
#include <slam6d/Boctree.h>
namespace lvr2
{
BoctreeIO::BoctreeIO()
{
}
BoctreeIO::~BoctreeIO()
{
}
ModelPtr BoctreeIO::read(string directory )
{
int numScans = 0;
int firstScan = -1;
int lastScan = -1;
// First, look for .oct files
boost::filesystem::directory_iterator lastFile;
for(boost::filesystem::directory_iterator it(directory); it != lastFile; it++ )
{
boost::filesystem::path p = it->path();
if(string(p.extension().string().c_str()) == ".oct")
{
// Check for naming convention "scanxxx.3d"
int num = 0;
if(sscanf(p.filename().string().c_str(), "scan%3d", &num))
{
numScans++;
if(firstScan == -1) firstScan = num;
if(lastScan == -1) lastScan = num;
if(num > lastScan) lastScan = num;
if(num < firstScan) firstScan = num;
}
}
}
list<Point> allPoints;
if(numScans)
{
for(int i = 0; i < numScans; i++)
{
char scanfile[128];
sprintf(scanfile, "%sscan%03d.oct", directory.c_str(), firstScan + i);
cout << timestamp << "Reading " << scanfile << endl;
Matrix4<Vec> tf;
vector<Point> points;
BOctTree<float>::deserialize(scanfile, points);
// Try to get transformation from .frames file
boost::filesystem::path frame_path(
boost::filesystem::path(directory) /
boost::filesystem::path( "scan" + to_string( firstScan + i, 3 ) + ".frames" ) );
string frameFileName = "/" + frame_path.relative_path().string();
ifstream frame_in(frameFileName.c_str());
if(!frame_in.good())
{
// Try to parse .pose file
boost::filesystem::path pose_path(
boost::filesystem::path(directory) /
boost::filesystem::path( "scan" + to_string( firstScan + i, 3 ) + ".pose" ) );
string poseFileName = "/" + pose_path.relative_path().string();
ifstream pose_in(poseFileName.c_str());
if(pose_in.good())
{
float euler[6];
for(int i = 0; i < 6; i++) pose_in >> euler[i];
Vec position(euler[0], euler[1], euler[2]);
Vec angle(euler[3], euler[4], euler[5]);
tf = Matrix4<Vec>(position, angle);
}
else
{
cout << timestamp << "UOS Reader: Warning: No position information found." << endl;
tf = Matrix4<Vec>();
}
}
else
{
// Use transformation from .frame files
tf = parseFrameFile(frame_in);
}
// Ugly hack to transform scan data
for(int j = 0; j < points.size(); j++)
{
Vec v(points[j].x, points[j].y, points[j].z);
v = tf * v;
if(v.length() < 10000)
{
points[j].x = v[0];
points[j].y = v[1];
points[j].z = v[2];
allPoints.push_back(points[j]);
}
}
}
}
cout << timestamp << "Read " << allPoints.size() << " points." << endl;
ModelPtr model( new Model );
if(allPoints.size())
{
floatArr points(new float[3 * allPoints.size()]);
ucharArr colors(new unsigned char[3 * allPoints.size()]);
floatArr intensities( new float[allPoints.size()]);
int i = 0;
bool found_color = false;
float min_r = 1e10;
float max_r = -1e10;
for(list<Point>::iterator it = allPoints.begin(); it != allPoints.end(); it++)
{
Point p = *it;
points[3 * i ] = p.x;
points[3 * i + 1] = p.y;
points[3 * i + 2] = p.z;
colors[3 * i ] = p.rgb[0];
colors[3 * i + 1] = p.rgb[1];
colors[3 * i + 2] = p.rgb[2];
if(p.rgb[0] != 255 && p.rgb[1] != 255 && p.rgb[2] != 255)
{
found_color = true;
}
intensities[i] = p.reflectance;
if(intensities[i] < min_r) min_r = intensities[i];
if(intensities[i] > max_r) max_r = intensities[i];
//cout << p.reflectance << " " << p.amplitude << " " << p.deviation << endl;
i++;
}
// // Map reflectances to 0..255
// float r_diff = max_r - min_r;
// if(r_diff > 0)
// {
// size_t np = allPoints.size();
// float b_size = r_diff / 255.0;
// for(int a = 0; a < np; a++)
// {
// float value = intensities[a];
// value -= min_r;
// value /= b_size;
// //cout << value << endl;
// intensities[a] = value;
// }
// }
model->m_pointCloud = PointBufferPtr( new PointBuffer );
model->m_pointCloud->setPointArray(points, allPoints.size());
model->m_pointCloud->setColorArray(colors, allPoints.size());
model->m_pointCloud->addFloatChannel(intensities, "intensities", allPoints.size(), 1);
}
return model;
}
void BoctreeIO::save( string filename )
{
}
Matrix4<Vec> BoctreeIO::parseFrameFile(ifstream& frameFile)
{
float m[16], color;
while(frameFile.good())
{
for(int i = 0; i < 16; i++ && frameFile.good()) frameFile >> m[i];
frameFile >> color;
}
return Matrix4<Vec>(m);
}
} /* namespace lvr2 */
| 31.701681
| 103
| 0.533333
|
uos
|
cbf736ce4a477ce6fe1054fb591394ad3b9fcdf8
| 2,115
|
hpp
|
C++
|
src/misc/containers.hpp
|
kmaninis/COB_public
|
e4cb02a4c6e9ffa85951bec36846581dc98e68de
|
[
"BSD-2-Clause-FreeBSD"
] | 205
|
2016-08-10T04:13:40.000Z
|
2022-01-28T08:57:37.000Z
|
src/misc/containers.hpp
|
kmaninis/COB_public
|
e4cb02a4c6e9ffa85951bec36846581dc98e68de
|
[
"BSD-2-Clause-FreeBSD"
] | 19
|
2016-09-19T13:05:59.000Z
|
2021-05-13T12:39:33.000Z
|
src/misc/containers.hpp
|
kmaninis/COB_public
|
e4cb02a4c6e9ffa85951bec36846581dc98e68de
|
[
"BSD-2-Clause-FreeBSD"
] | 70
|
2016-08-03T03:36:53.000Z
|
2022-02-03T20:44:43.000Z
|
// ------------------------------------------------------------------------
// Copyright (C)
// ETH Zurich - Switzerland
//
// Kevis-Kokitsi Maninis <kmaninis@vision.ee.ethz.ch>
// Jordi Pont-Tuset <jponttuset@vision.ee.ethz.ch>
// July 2016
// ------------------------------------------------------------------------
// This file is part of the COB package presented in:
// K.K. Maninis, J. Pont-Tuset, P. Arbelaez and L. Van Gool
// Convolutional Oriented Boundaries
// European Conference on Computer Vision (ECCV), 2016
// Please consider citing the paper if you use this code.
// ------------------------------------------------------------------------
#ifndef CONTAINERS_HPP
#define CONTAINERS_HPP
#include <vector>
#include <list>
#include <set>
#include <map>
typedef uint32_t label_type;
typedef std::set<label_type> set_type;
typedef std::map<double,std::list<set_type> > map_type;
struct merging_sequence
{
std::vector<label_type> parent_labels;
std::vector<std::list<label_type> > children_labels;
std::vector<double> start_ths;
std::size_t n_max_children;
std::size_t n_leaves;
std::size_t n_regs;
void print() const
{
for(std::size_t ii=0; ii<parent_labels.size(); ++ii)
{
for(label_type id: children_labels[ii])
printf("%d\t",id);
printf("-->\t%d\n", parent_labels[ii]);
}
}
};
struct cont_elem
{
cont_elem(size_t new_x, size_t new_y)
: x(new_x), y(new_y)
{
}
size_t x;
size_t y;
};
struct contour_container: public std::map<std::pair<label_type,label_type>, std::list<cont_elem> >
{
contour_container(): std::map<std::pair<label_type,label_type>, std::list<cont_elem> >()
{
}
void print() const
{
for(auto elem:(*this))
{
printf("[%d,%d] - ", elem.first.first, elem.first.second);
for(const cont_elem& cont: elem.second)
printf("(%d,%d), ",cont.x,cont.y);
printf("\n");
}
}
};
#endif
| 26.111111
| 98
| 0.533333
|
kmaninis
|
cbfbb58db9322b4e56c3c01538754afe49203555
| 14,499
|
cpp
|
C++
|
src/CDocScriptAmendments.cpp
|
QtWorks/CDoc
|
64b806a39b24bedd8aede6a7134326c248c0c614
|
[
"MIT"
] | 1
|
2019-04-24T02:14:34.000Z
|
2019-04-24T02:14:34.000Z
|
src/CDocScriptAmendments.cpp
|
QtWorks/CDoc
|
64b806a39b24bedd8aede6a7134326c248c0c614
|
[
"MIT"
] | null | null | null |
src/CDocScriptAmendments.cpp
|
QtWorks/CDoc
|
64b806a39b24bedd8aede6a7134326c248c0c614
|
[
"MIT"
] | null | null | null |
#include "CDocI.h"
/*----------------------------------------------------------------*/
#define DUMMY_AMENDMENT 0
#define AMENDMENT_ISSUED 1
#define AMENDMENT_ADDED 2
struct CDAmendmentData {
int type;
char *issue;
char *amend;
char *detail;
char *author;
char *date;
char *approve;
char *agree;
char *text;
};
struct CDAmendment {
CDAmendmentData data;
CDAmendment() {
data.type = DUMMY_AMENDMENT;
data.issue = NULL;
data.amend = NULL;
data.detail = NULL;
data.author = NULL;
data.date = NULL;
data.approve = NULL;
data.agree = NULL;
data.text = NULL;
}
~CDAmendment() {
delete [] data.issue ;
delete [] data.amend ;
delete [] data.detail ;
delete [] data.author ;
delete [] data.date ;
delete [] data.approve;
delete [] data.agree ;
delete [] data.text ;
}
};
/*----------------------------------------------------------------*/
typedef std::vector<CDAmendment *> CDAmendmentList;
static CDAmendmentList amendment_list;
static CDScriptTempFile *amendments_temp_file = NULL;
/*----------------------------------------------------------------*/
/* Ammendment Parameter Definition */
#define AMD_OFFSET(a) CDocOffset(CDAmendmentData*,a)
static CDParameterData
amd_parameter_data[] = {
{ "issue" , PARM_NEW_STR, NULL, AMD_OFFSET(issue ), },
{ "amend" , PARM_NEW_STR, NULL, AMD_OFFSET(amend ), },
{ "detail" , PARM_NEW_STR, NULL, AMD_OFFSET(detail ), },
{ "author" , PARM_NEW_STR, NULL, AMD_OFFSET(author ), },
{ "date" , PARM_NEW_STR, NULL, AMD_OFFSET(date ), },
{ "approve", PARM_NEW_STR, NULL, AMD_OFFSET(approve), },
{ "agree" , PARM_NEW_STR, NULL, AMD_OFFSET(agree ), },
{ NULL , 0 , NULL, 0 , },
};
/*----------------------------------------------------------------*/
static void CDocScriptAmendmentWriteLine
(CDAmendment *, int, int);
static void CDocScriptAmendmentWriteText
(char *);
static char *CDocScriptAmendmentsGetText
();
// Initialise Amendments Control Variables ready to process amendments commands.
extern void
CDocScriptInitAmendments()
{
cdoc_document.part = CDOC_AMENDMENTS_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
/* Start Outputting Text to Temporary File */
amendments_temp_file = CDocScriptStartTempFile("Amendments");
cdoc_left_margin = 0;
cdoc_right_margin = 38;
cdoc_indent = 11;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
CDocScriptWriteCommand(CDOC_INDENT_TMPL, cdoc_indent);
}
// Process a Colon Command found in the Amendments section.
extern void
CDocScriptProcessAmendmentsCommand(CDColonCommand *colon_command)
{
/* Flush Paragraph */
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
/* Get Text in Amendments Temporary File to add to previous Amendment */
char *text = CDocScriptAmendmentsGetText();
if (text != NULL) {
CDAmendment *amendment = NULL;
if (! amendment_list.empty())
amendment = amendment_list.back();
if (amendment == NULL || amendment->data.text != NULL) {
amendment = new CDAmendment;
amendment_list.push_back(amendment);
}
amendment->data.text = text;
}
/* If Issued or Amended Command then add Details to Amendments List */
if (strcmp(colon_command->getCommand().c_str(), "i") == 0 ||
strcmp(colon_command->getCommand().c_str(), "a") == 0) {
/* Create and Initialise Amendments Structure */
CDAmendment *amendment = new CDAmendment;
if (strcmp(colon_command->getCommand().c_str(), "i") == 0)
amendment->data.type = AMENDMENT_ISSUED;
else
amendment->data.type = AMENDMENT_ADDED;
amendment_list.push_back(amendment);
/* Process Parameter/Value pairs to set the Amendments Structure */
CDocExtractParameterValues(colon_command->getParameters(),
colon_command->getValues(),
amd_parameter_data,
(char *) amendment);
if (amendment->data.detail != NULL)
CStrUtil::toUpper(amendment->data.detail);
}
/* If we have and End Amendments Command (either directly or
indirectly) then Output current Amendments List */
else if (strcmp(colon_command->getCommand().c_str(), "eamends" ) == 0 ||
strcmp(colon_command->getCommand().c_str(), "body" ) == 0 ||
strcmp(colon_command->getCommand().c_str(), "appendix") == 0) {
CDocScriptTermAmendments();
/* Start new part as appropriate */
if (strcmp(colon_command->getCommand().c_str(), "body") == 0)
cdoc_document.part = CDOC_BODY_PART;
else if (strcmp(colon_command->getCommand().c_str(), "appendix") == 0)
cdoc_document.part = CDOC_APPENDIX_PART;
}
else
CDocScriptWarning("Invalid Amendments Command - %s %s",
colon_command->getCommand().c_str(), colon_command->getText().c_str());
}
// Terminate Amendments Section outputing Buffered amendments text.
extern void
CDocScriptTermAmendments()
{
/* Flush Paragraph */
if (cdoc_in_paragraph)
CDocScriptOutputParagraph();
/* Get Text in Amendments Temporary File to add to previous Amendment */
char *text = CDocScriptAmendmentsGetText();
if (text != NULL) {
CDAmendment *amendment = amendment_list.back();
if (amendment == NULL || amendment->data.text != NULL) {
amendment = new CDAmendment;
amendment_list.push_back(amendment);
}
amendment->data.text = text;
}
/*------------*/
/* End Outputting Text to Temporary File */
CDocScriptEndTempFile(amendments_temp_file);
delete amendments_temp_file;
/*------------*/
/* Write Header */
CDocScriptWriteCentreJustifiedPageHeader("List of Amendments");
CDocScriptSkipLine();
int no_amendments = amendment_list.size();
/* Output Amendments List */
/* Set up Tab Stops */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF)
CDocScriptWriteCommand(".ta 0.2i 0.5i +2i +1i +1i\n");
/* Output Column Headers */
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
CDocScriptWriteCommand(".BD \"\t\tDetails\tAuthor\tDate\tApprove\"\n");
CDocScriptSkipLine();
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) {
CDocScriptWriteText(FILL_TMPL, 9, 9, ' ');
CDocScriptWriteText("%sDetails%s", CDocStartUnderline(), CDocEndUnderline());
CDocScriptWriteText(FILL_TMPL, 40, 40, ' ');
CDocScriptWriteText("%sAuthor%s", CDocStartUnderline(), CDocEndUnderline());
CDocScriptWriteText(FILL_TMPL, 51, 51, ' ');
CDocScriptWriteText("%sDate%s", CDocStartUnderline(), CDocEndUnderline());
CDocScriptWriteText(FILL_TMPL, 62, 62, ' ');
CDocScriptWriteText("%sApprove%s", CDocStartUnderline(), CDocEndUnderline());
CDocScriptWriteText("\n");
CDocScriptSkipLine();
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC) {
CDocScriptWriteLine("%s %-30s %-10s %-10s %-20s%s", CDocStartUnderline(),
"Details", "Author", "Date", "Approve", CDocEndUnderline());
CDocScriptSkipLine();
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<p>\n");
CDocScriptWriteCommand("<table width='100%%' border>\n");
CDocScriptWriteCommand("<tr>\n");
CDocScriptWriteCommand("<th> </th>\n");
CDocScriptWriteCommand("<th>Details</th>\n");
CDocScriptWriteCommand("<th>Author</th>\n");
CDocScriptWriteCommand("<th>Date</th>\n");
CDocScriptWriteCommand("<th>Approve</th>\n");
CDocScriptWriteCommand("</tr>\n");
}
else {
CDocScriptWriteLine(" %-30s %-10s %-10s %-20s",
"Details", "Author", "Date", "Approve");
CDocScriptSkipLine();
}
/* Output each Amendment Line */
int issue_no = 0;
int amend_no = 0;
for (int i = 1; i <= no_amendments; i++) {
CDAmendment *amendment = amendment_list[i - 1];
if (amendment->data.type == DUMMY_AMENDMENT)
CDocScriptAmendmentWriteText(amendment->data.text);
else {
if (amendment->data.type == AMENDMENT_ISSUED) {
issue_no++;
amend_no = 0;
}
else
amend_no++;
if ((issue_no > 0 || amend_no > 0) && CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML)
CDocScriptSkipLine();
CDocScriptAmendmentWriteLine(amendment, issue_no, amend_no);
}
}
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("</table>\n");
CDocScriptWriteCommand("<p>\n");
}
/* Delete Amendments Structures and List */
for (int i = 1; i <= no_amendments; i++) {
CDAmendment *amendment = amendment_list[i - 1];
delete amendment;
}
amendment_list.clear();
/* End Amendments Document Part */
cdoc_document.part = CDOC_NO_PART;
cdoc_document.sub_part = CDOC_NO_SUB_PART;
}
// Write an Amendments line from the data stored in the Amendments structure.
static void
CDocScriptAmendmentWriteLine(CDAmendment *amendment, int issue_no, int amend_no)
{
char issue_string[16];
if (amend_no > 0)
sprintf(issue_string, "%d%c", issue_no, amend_no + 'A' - 1);
else
sprintf(issue_string, "%d%c", issue_no, ' ');
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
CDocScriptWriteText("\t");
if (amendment->data.issue != NULL)
CDocScriptWriteText("%s", amendment->data.issue);
else
CDocScriptWriteText("%s", issue_string);
CDocScriptWriteText("\t");
if (amendment->data.detail != NULL)
CDocScriptWriteText("%s", amendment->data.detail);
else
CDocScriptWriteText("");
CDocScriptWriteText("\t");
if (amendment->data.author != NULL)
CDocScriptWriteText("%s", amendment->data.author);
else
CDocScriptWriteText("");
CDocScriptWriteText("\t");
if (amendment->data.date != NULL)
CDocScriptWriteText("%s", amendment->data.date);
else
CDocScriptWriteText("");
CDocScriptWriteText("\t");
if (amendment->data.approve != NULL)
CDocScriptWriteText("%s", amendment->data.approve);
else
CDocScriptWriteText("");
CDocScriptWriteText("\n");
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) {
CDocScriptWriteText(FILL_TMPL, 4, 4, ' ');
CDocScriptWriteText("%-4s",
amendment->data.issue != NULL ? amendment->data.issue : issue_string);
CDocScriptWriteText(FILL_TMPL, 9, 9, ' ');
CDocScriptWriteText("%-30s",
amendment->data.detail != NULL ? amendment->data.detail : "");
CDocScriptWriteText(FILL_TMPL, 40, 40, ' ');
CDocScriptWriteText("%-10s",
amendment->data.author != NULL ? amendment->data.author : "");
CDocScriptWriteText(FILL_TMPL, 51, 51, ' ');
CDocScriptWriteText("%-10s",
amendment->data.date != NULL ? amendment->data.date : "");
CDocScriptWriteText(FILL_TMPL, 62, 62, ' ');
CDocScriptWriteText("%-20s",
amendment->data.approve != NULL ? amendment->data.approve : "");
CDocScriptWriteText("\n");
}
else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) {
CDocScriptWriteCommand("<tr>\n");
CDocScriptWriteCommand("<td>%s</td>\n",
amendment->data.issue != NULL ? amendment->data.issue : issue_string);
CDocScriptWriteCommand("<td>%s</td>\n",
amendment->data.detail != NULL ? amendment->data.detail : " " );
CDocScriptWriteCommand("<td>%s</td>\n",
amendment->data.author != NULL ? amendment->data.author : " " );
CDocScriptWriteCommand("<td>%s</td>\n",
amendment->data.date != NULL ? amendment->data.date : " " );
CDocScriptWriteCommand("<td>%s</td>\n",
amendment->data.approve != NULL ? amendment->data.approve : " " );
CDocScriptWriteCommand("</tr>\n");
}
else {
CDocScriptWriteLine(" %-4s %-30s %-10s %-10s %-20s",
amendment->data.issue != NULL ? amendment->data.issue : issue_string,
amendment->data.detail != NULL ? amendment->data.detail : "",
amendment->data.author != NULL ? amendment->data.author : "",
amendment->data.date != NULL ? amendment->data.date : "",
amendment->data.approve != NULL ? amendment->data.approve : "");
}
if (amendment->data.text != NULL && amendment->data.text[0] != '\0')
CDocScriptAmendmentWriteText(amendment->data.text);
}
// Write text associated with an amendment.
static void
CDocScriptAmendmentWriteText(char *text)
{
char *p1;
char *p = text;
while ((p1 = strchr(p, '\n')) != NULL) {
*p1 = '\0';
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
// CDocScriptWriteText("\t\t");
CDocScriptOutputTempFileLine(p);
// CDocScriptWriteText("\n");
}
else {
// CDocScriptWriteText(" ");
CDocScriptOutputTempFileLine(p);
}
p = p1 + 1;
}
if (*p != '\0') {
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) {
// CDocScriptWriteText("\t\t");
CDocScriptOutputTempFileLine(p);
// CDocScriptWriteText("\n");
}
else {
// CDocScriptWriteText(" ");
CDocScriptOutputTempFileLine(p);
}
}
//CDocScriptSkipLine();
}
// Get any text which was defined between the amendments commands.
static char *
CDocScriptAmendmentsGetText()
{
long no_read;
struct stat file_stat;
char *text = NULL;
/*-----------*/
/* End Outputting Text to Temporary File */
CDocScriptEndTempFile(amendments_temp_file);
/*-----------*/
int error = stat(amendments_temp_file->filename.c_str(), &file_stat);
if (error == -1 || file_stat.st_size == 0)
goto CDocScriptAmendmentsGetText_1;
amendments_temp_file->fp = fopen(amendments_temp_file->filename.c_str(), "r");
if (amendments_temp_file->fp == NULL)
goto CDocScriptAmendmentsGetText_1;
text = new char [file_stat.st_size + 1];
no_read = fread(text, sizeof(char), file_stat.st_size + 1, amendments_temp_file->fp);
text[no_read] = '\0';
fclose(amendments_temp_file->fp);
/*-----------*/
CDocScriptAmendmentsGetText_1:
delete amendments_temp_file;
/* Start Outputting Text to Temporary File */
amendments_temp_file = CDocScriptStartTempFile("Amendments");
cdoc_left_margin = 0;
cdoc_right_margin = 38;
cdoc_indent = 11;
if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC)
CDocScriptWriteCommand(CDOC_INDENT_TMPL, cdoc_indent);
return text;
}
| 27.564639
| 93
| 0.63294
|
QtWorks
|
cbfe304763b786b823615c143eab5a26bb544307
| 2,140
|
cpp
|
C++
|
src/WebConf.cpp
|
VisaJE/DoomsdayTetris-2
|
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
|
[
"FTL",
"MIT"
] | 1
|
2019-09-20T20:37:35.000Z
|
2019-09-20T20:37:35.000Z
|
src/WebConf.cpp
|
VisaJE/DoomsdayTetris-2
|
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
|
[
"FTL",
"MIT"
] | null | null | null |
src/WebConf.cpp
|
VisaJE/DoomsdayTetris-2
|
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
|
[
"FTL",
"MIT"
] | null | null | null |
#include "WebConf.h"
#include <iostream>
#include <vector>
#include <cstdio>
#include <sstream>
#include <fstream>
#include "Paths.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/filereadstream.h"
using namespace rapidjson;
using namespace tet;
WebConf::WebConf()
{
serverConfig = Paths::serverConfigPath().c_str();
configuration = std::vector<ConfEntry>();
serviceEnabled = false;
}
void WebConf::initiate()
{
if (!readConf()) makeConf();
}
WebConf::~WebConf()
{
}
bool WebConf::readConf()
{
FILE* conf =fopen(serverConfig.c_str(), "rb");
if (!conf) {
LOG("No config found at %s\n", serverConfig.c_str());
return false;
}
Document doc;
char readBuffer[10000];
FileReadStream in(conf, readBuffer, sizeof(readBuffer));
doc.ParseStream(in);
fclose(conf);
if (checkValidity(&doc)) setConf(&doc);
else
{
makeConf();
return false;
}
return true;
}
bool WebConf::checkValidity(Document *doc)
{
bool valid = true;
if (!doc->IsObject()) valid = false;
Value::MemberIterator enabled = doc->FindMember("enabled");
if (enabled == doc->MemberEnd()) valid = false;
if (!enabled->value.IsBool()) valid = false;
return valid;
}
void WebConf::setConf(Document *doc)
{
serviceEnabled= doc->FindMember("enabled")->value.GetBool();
for (const char* i : keys)
{
if (doc->HasMember(i))
{
auto thisValue = doc->FindMember(i);
if (thisValue->value.IsString())
{
configuration.push_back({i, thisValue->value.GetString()});
}
}
}
}
void WebConf::makeConf()
{
serviceEnabled = false;
std::stringstream defaultString;
defaultString << "\{\n\"enabled\": false";
for (auto i : keys)
{
defaultString << ",\n\"" << i << "\": \"\"";
}
defaultString << "}";
remove (serverConfig.c_str());
std::ofstream out(serverConfig.c_str());
out << defaultString.str();
out.close();
}
| 22.291667
| 74
| 0.609346
|
VisaJE
|
02021723a676015654d72928189fa57966f6e418
| 3,065
|
hpp
|
C++
|
include/ftl/map_container_const_iterator.hpp
|
ftlorg/ftl
|
75a580043ddf011477f0fbcb0ed1dc01be37814d
|
[
"BSL-1.0"
] | 47
|
2020-07-17T07:31:42.000Z
|
2022-02-18T10:31:45.000Z
|
include/ftl/map_container_const_iterator.hpp
|
ftlorg/ftl
|
75a580043ddf011477f0fbcb0ed1dc01be37814d
|
[
"BSL-1.0"
] | 40
|
2020-07-23T09:01:39.000Z
|
2020-12-19T15:19:44.000Z
|
include/ftl/map_container_const_iterator.hpp
|
ftlorg/ftl
|
75a580043ddf011477f0fbcb0ed1dc01be37814d
|
[
"BSL-1.0"
] | 1
|
2020-07-26T18:21:36.000Z
|
2020-07-26T18:21:36.000Z
|
// Copyright Grzegorz Litarowicz and Lukasz Gut 2020 - 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <ftl/iterator_interface.hpp>
#include <ftl/iterator_member_provider.hpp>
#include <ftl/iterator_traits.hpp>
#include <ftl/map.hpp>
#include <iterator>
namespace ftl {
template<typename Key, typename T, typename Item = std::pair<const Key, T>>
class map_container_const_iterator final
: public iterator_interface<map_container_const_iterator<Key, T>>
, public container_iterator_member_provider<map_container_const_iterator<Key, T>,
typename std::iterator_traits<ftl::map_container_const_iterator<Key, T>>::iterator_category> {
friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::random_access_iterator_tag>;
friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::bidirectional_iterator_tag>;
friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::forward_iterator_tag>;
friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::input_iterator_tag>;
friend container_iterator_member_provider<map_container_const_iterator<Key, T>>;
friend iterator_interface<map_container_const_iterator<Key, T>>;
public:
using difference_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::difference_type;
using value_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::value_type;
using pointer = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::pointer;
using reference = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::reference;
using const_pointer = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::const_pointer;
using const_reference = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::const_reference;
using iterator_category =
typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::iterator_category;
using size_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::size_type;
using std_map_container_const_iterator =
typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::std_map_container_const_iterator;
map_container_const_iterator(std_map_container_const_iterator begin, std_map_container_const_iterator end)
: current_{ begin }, begin_{ begin }, end_{ end } {
}
map_container_const_iterator(std_map_container_const_iterator current,
std_map_container_const_iterator begin,
std_map_container_const_iterator end)
: current_{ current }, begin_{ begin }, end_{ end } {
}
private:
mutable std_map_container_const_iterator current_;
std_map_container_const_iterator begin_;
std_map_container_const_iterator end_;
};
}// namespace ftl
| 50.245902
| 122
| 0.804568
|
ftlorg
|
02024a9538028ed67ae53f0a4acc741c4f8e4b72
| 8,617
|
cpp
|
C++
|
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 108
|
2018-10-08T17:03:32.000Z
|
2022-03-21T00:52:26.000Z
|
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 287
|
2018-09-18T14:59:12.000Z
|
2022-01-13T12:28:23.000Z
|
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
|
gianricardo/OpcUaStack
|
ccdef574175ffe8b7e82b886abc5e5403968b280
|
[
"Apache-2.0"
] | 32
|
2018-10-19T14:35:03.000Z
|
2021-11-12T09:36:46.000Z
|
#include "unittest.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaVariant.h"
using namespace OpcUaStackCore;
BOOST_AUTO_TEST_SUITE(OpcUaVariantValue_)
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_)
{
std::cout << "OpcUaVariantValue_t" << std::endl;
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_uint32_copyTo)
{
OpcUaVariantValue value1, value2;
value1.variant((OpcUaUInt32)123);
value1.copyTo(value2);
BOOST_REQUIRE(value1.variant<OpcUaUInt32>() == 123);
BOOST_REQUIRE(value2.variant<OpcUaUInt32>() == 123);
value2.variant((OpcUaUInt32)456);
BOOST_REQUIRE(value1.variant<OpcUaUInt32>() == 123);
BOOST_REQUIRE(value2.variant<OpcUaUInt32>() == 456);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_localizedText_copyTo)
{
OpcUaLocalizedText::SPtr localizedTextSPtr1 = constructSPtr<OpcUaLocalizedText>();
OpcUaLocalizedText::SPtr localizedTextSPtr2;
localizedTextSPtr1->locale("de");
localizedTextSPtr1->text("text1");
OpcUaVariantValue value1, value2;
value1.variant(localizedTextSPtr1);
value1.copyTo(value2);
localizedTextSPtr1 = value1.variantSPtr<OpcUaLocalizedText>();
localizedTextSPtr2 = value2.variantSPtr<OpcUaLocalizedText>();
BOOST_REQUIRE(localizedTextSPtr1->locale().value() == "de");
BOOST_REQUIRE(localizedTextSPtr1->text().value() == "text1");
BOOST_REQUIRE(localizedTextSPtr2->locale().value() == "de");
BOOST_REQUIRE(localizedTextSPtr2->text().value() == "text1");
localizedTextSPtr1->text("text2");
BOOST_REQUIRE(localizedTextSPtr1->locale().value() == "de");
BOOST_REQUIRE(localizedTextSPtr1->text().value() == "text2");
BOOST_REQUIRE(localizedTextSPtr2->locale().value() == "de");
BOOST_REQUIRE(localizedTextSPtr2->text().value() == "text1");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Boolean)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Boolean:true") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaBoolean);
OpcUaBoolean value = variantValue.variant<OpcUaBoolean>();
BOOST_REQUIRE(value == true);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_SByte)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("SByte:-12") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaSByte);
OpcUaSByte value = variantValue.variant<OpcUaSByte>();
BOOST_REQUIRE(value == -12);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Byte)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Byte:12") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaByte);
OpcUaByte value = variantValue.variant<OpcUaByte>();
BOOST_REQUIRE(value == 12);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int16)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Int16:-1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt16);
OpcUaInt16 value = variantValue.variant<OpcUaInt16>();
BOOST_REQUIRE(value == -1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt16)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("UInt16:1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt16);
OpcUaUInt16 value = variantValue.variant<OpcUaUInt16>();
BOOST_REQUIRE(value == 1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int32)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Int32:-1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt32);
OpcUaInt32 value = variantValue.variant<OpcUaInt32>();
BOOST_REQUIRE(value == -1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt32)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("UInt32:1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt32);
OpcUaUInt32 value = variantValue.variant<OpcUaUInt32>();
BOOST_REQUIRE(value == 1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int64)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Int64:-1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt64);
OpcUaInt64 value = variantValue.variant<OpcUaInt64>();
BOOST_REQUIRE(value == -1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt64)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("UInt64:1234") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt64);
OpcUaUInt64 value = variantValue.variant<OpcUaUInt64>();
BOOST_REQUIRE(value == 1234);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Double)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Double:1.1") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaDouble);
OpcUaDouble value = variantValue.variant<OpcUaDouble>();
BOOST_REQUIRE(value > 1.09 && value < 1.11);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Float)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Float:1.1") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaFloat);
OpcUaFloat value = variantValue.variant<OpcUaFloat>();
BOOST_REQUIRE(value > 1.09 && value < 1.11);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_DateTime)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("DateTime:20120101T101101") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaDateTime);
OpcUaDateTime value = variantValue.variant<OpcUaDateTime>();
BOOST_REQUIRE(value.toISOString() == "20120101T101101");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_StatusCode)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("StatusCode:Success") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaStatusCode);
OpcUaStatusCode value = variantValue.variant<OpcUaStatusCode>();
BOOST_REQUIRE(value == Success);
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Guid)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("Guid:12345678-9ABC-DEF0-1234-56789ABCDEF0") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaGuid);
OpcUaGuid::SPtr value = variantValue.variantSPtr<OpcUaGuid>();
std::string guidString = *value;
BOOST_REQUIRE(guidString == "12345678-9ABC-DEF0-1234-56789ABCDEF0");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_ByteString)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("ByteString:0102030405060708090A0B0C0E0F") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaByteString);
OpcUaByteString::SPtr value = variantValue.variantSPtr<OpcUaByteString>();
BOOST_REQUIRE(value->toHexString() == "0102030405060708090A0B0C0E0F");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_String)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("String:0102030405060708090A0B0C0E0F") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaString);
OpcUaString::SPtr value = variantValue.variantSPtr<OpcUaString>();
BOOST_REQUIRE(value->value() == "0102030405060708090A0B0C0E0F");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_NodeId)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("NodeId:ns=3;s=nodename") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaNodeId);
OpcUaNodeId::SPtr value = variantValue.variantSPtr<OpcUaNodeId>();
BOOST_REQUIRE(value->namespaceIndex() == 3);
BOOST_REQUIRE(value->nodeId<OpcUaString::SPtr>()->value() == "nodename");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_QualifiedName)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("QualifiedName:1:string") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaQualifiedName);
OpcUaQualifiedName::SPtr value = variantValue.variantSPtr<OpcUaQualifiedName>();
BOOST_REQUIRE(value->namespaceIndex() == 1);
BOOST_REQUIRE(value->name().value() == "string");
}
BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_LocalizedText)
{
OpcUaVariantValue variantValue;
BOOST_REQUIRE(variantValue.fromString("LocalizedText:de,string") == true);
BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaLocalizedText);
OpcUaLocalizedText::SPtr value = variantValue.variantSPtr<OpcUaLocalizedText>();
BOOST_REQUIRE(value->locale().value() == "de");
BOOST_REQUIRE(value->text().value() == "string");
}
BOOST_AUTO_TEST_SUITE_END()
| 31.797048
| 93
| 0.799698
|
gianricardo
|
020488f372a97cea57732f61db4c270581acce67
| 1,204
|
cpp
|
C++
|
src/scenes/hannahWhitney/hannahWhitney.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 12
|
2019-10-28T19:07:59.000Z
|
2021-08-21T22:00:52.000Z
|
src/scenes/hannahWhitney/hannahWhitney.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 1
|
2019-10-28T19:20:05.000Z
|
2019-10-28T20:14:24.000Z
|
src/scenes/hannahWhitney/hannahWhitney.cpp
|
yxcde/RTP_MIT_RECODED
|
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
|
[
"MIT"
] | 8
|
2019-10-28T19:11:30.000Z
|
2020-01-12T05:18:31.000Z
|
#include "hannahWhitney.h"
void hannahWhitney::setup(){
// setup pramaters
// if your original code use an ofxPanel instance dont use it here, instead
// add your parameters to the "parameters" instance as follows.
// param was declared in mitScene1.h
//parameters.add(param.set("param", 5, 0, 100));
parameters.add(speed.set("speed", 1, 0, 5));
parameters.add(noise.set("noise", 10, 0, 100));
setAuthor("Hannah Lienhard");
setOriginalArtist("John Whitney");
loadCode("scenes/hannahWhitney/exampleCode.cpp");
}
void hannahWhitney::update(){
}
void hannahWhitney::draw(){
ofBackground(0);
ofSetColor(255);
float time = speed*ofGetElapsedTimef()*50;
ofSeedRandom(noise);
for (int z = 0; z < 10; z++){
float radius = fmod(time + ofMap(z, 0, 10, 0, 300), 300);
ofPoint center(300,300);
for (int i = 0; i < 100; i++){
float angle = ofMap(i, 0, 100, 0, TWO_PI);
float offset = ofNoise(ofRandom(0.01, 0.06))*100;
ofDrawCircle(center.x + offset+ radius * cos(angle),
center.y + +offset+ radius * sin(angle),
3);
}
}
}
| 28
| 75
| 0.585548
|
yxcde
|
0208cfad27722f229571d73aba766e592097b786
| 5,636
|
cpp
|
C++
|
src/journal_manager/replay/replay_stripe.cpp
|
hsungyang/poseidonos
|
0f523b36ccf0d70726364395ea96ac6ae3b845c3
|
[
"BSD-3-Clause"
] | 38
|
2021-04-06T03:20:55.000Z
|
2022-03-02T09:33:28.000Z
|
src/journal_manager/replay/replay_stripe.cpp
|
gye-ul/poseidonos
|
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
|
[
"BSD-3-Clause"
] | 19
|
2021-04-08T02:27:44.000Z
|
2022-03-23T00:59:04.000Z
|
src/journal_manager/replay/replay_stripe.cpp
|
gye-ul/poseidonos
|
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
|
[
"BSD-3-Clause"
] | 28
|
2021-04-08T04:39:18.000Z
|
2022-03-24T05:56:00.000Z
|
/*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* 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 Samsung Electronics Corporation nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "src/journal_manager/replay/replay_stripe.h"
#include "src/include/pos_event_id.h"
#include "src/journal_manager/replay/replay_event_factory.h"
#include "src/logger/logger.h"
namespace pos
{
// Constructor for product code
ReplayStripe::ReplayStripe(StripeId vsid, IVSAMap* inputVsaMap, IStripeMap* inputStripeMap,
IContextReplayer* ctxReplayer,
IBlockAllocator* blockAllocator, IArrayInfo* arrayInfo,
ActiveWBStripeReplayer* wbReplayer, ActiveUserStripeReplayer* userReplayer)
: ReplayStripe(inputVsaMap, inputStripeMap, wbReplayer, userReplayer, nullptr, nullptr, nullptr)
{
status = new StripeReplayStatus(vsid);
replayEventFactory = new ReplayEventFactory(status, inputVsaMap, inputStripeMap, ctxReplayer, blockAllocator, arrayInfo, wbReplayer);
}
// Constructor for unit test
ReplayStripe::ReplayStripe(IVSAMap* inputVsaMap, IStripeMap* inputStripeMap,
ActiveWBStripeReplayer* wbReplayer,
ActiveUserStripeReplayer* userReplayer,
StripeReplayStatus* inputStatus, ReplayEventFactory* factory, ReplayEventList* inputReplayEventList)
: status(inputStatus),
replayEventFactory(factory),
wbStripeReplayer(wbReplayer),
userStripeReplayer(userReplayer),
vsaMap(inputVsaMap),
stripeMap(inputStripeMap),
replaySegmentInfo(true)
{
if (inputReplayEventList != nullptr)
{
replayEvents = *inputReplayEventList;
}
}
ReplayStripe::~ReplayStripe(void)
{
for (auto replayEvent : replayEvents)
{
delete replayEvent;
}
replayEvents.clear();
delete status;
delete replayEventFactory;
}
void
ReplayStripe::AddLog(ReplayLog replayLog)
{
if (replayLog.segInfoFlushed == true)
{
replaySegmentInfo = false;
}
status->RecordLogFoundTime(replayLog.time);
}
int
ReplayStripe::Replay(void)
{
int result = 0;
if ((result = _ReplayEvents()) != 0)
{
return result;
}
status->Print();
return result;
}
void
ReplayStripe::_CreateSegmentAllocationEvent(void)
{
ReplayEvent* segmentAllocation =
replayEventFactory->CreateSegmentAllocationReplayEvent(status->GetUserLsid());
replayEvents.push_front(segmentAllocation);
}
void
ReplayStripe::_CreateStripeAllocationEvent(void)
{
ReplayEvent* stripeAllocation =
replayEventFactory->CreateStripeAllocationReplayEvent(status->GetVsid(), status->GetWbLsid());
replayEvents.push_front(stripeAllocation);
}
void
ReplayStripe::_CreateStripeFlushReplayEvent(void)
{
StripeAddr dest = {
.stripeLoc = IN_USER_AREA,
.stripeId = status->GetUserLsid()};
ReplayEvent* stripeMapUpdate =
replayEventFactory->CreateStripeMapUpdateReplayEvent(status->GetVsid(), dest);
replayEvents.push_back(stripeMapUpdate);
if (replaySegmentInfo == true)
{
ReplayEvent* flushEvent =
replayEventFactory->CreateStripeFlushReplayEvent(status->GetVsid(),
status->GetWbLsid(), status->GetUserLsid());
replayEvents.push_back(flushEvent);
}
}
int
ReplayStripe::_ReplayEvents(void)
{
int result = 0;
for (auto replayEvent : replayEvents)
{
result = replayEvent->Replay();
if (result != 0)
{
return result;
}
}
return result;
}
void
ReplayStripe::DeleteBlockMapReplayEvents(void)
{
int numErasedLogs = 0;
for (auto it = replayEvents.begin(); it != replayEvents.end();)
{
ReplayEvent* replayEvent = *it;
if (replayEvent->GetType() == ReplayEventType::BLOCK_MAP_UPDATE)
{
it = replayEvents.erase(it);
delete replayEvent;
numErasedLogs++;
}
else
{
it++;
}
}
int eventId = static_cast<int>(POS_EVENT_ID::JOURNAL_REPLAY_VOLUME_EVENT);
POS_TRACE_DEBUG(eventId, "[Replay] {} block log of volume {} is skipped",
numErasedLogs, status->GetVolumeId());
}
} // namespace pos
| 30.301075
| 137
| 0.709368
|
hsungyang
|
0209710921734a953f6fe988de49529a58cfd8ba
| 58,870
|
cc
|
C++
|
third/blackwidow/src/blackwidow.cc
|
kxtry/pika
|
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
|
[
"MIT"
] | null | null | null |
third/blackwidow/src/blackwidow.cc
|
kxtry/pika
|
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
|
[
"MIT"
] | 2
|
2020-02-26T11:54:45.000Z
|
2021-05-20T11:26:21.000Z
|
third/blackwidow/src/blackwidow.cc
|
kxtry/pika
|
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017-present The blackwidow Authors. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "blackwidow/blackwidow.h"
#include "blackwidow/util.h"
#include "src/mutex_impl.h"
#include "src/redis_strings.h"
#include "src/redis_hashes.h"
#include "src/redis_sets.h"
#include "src/redis_lists.h"
#include "src/redis_zsets.h"
#include "src/redis_hyperloglog.h"
#include "src/lru_cache.h"
namespace blackwidow {
BlackWidow::BlackWidow() :
strings_db_(nullptr),
hashes_db_(nullptr),
sets_db_(nullptr),
zsets_db_(nullptr),
lists_db_(nullptr),
is_opened_(false),
bg_tasks_cond_var_(&bg_tasks_mutex_),
current_task_type_(kNone),
bg_tasks_should_exit_(false),
scan_keynum_exit_(false) {
cursors_store_ = new LRUCache<std::string, std::string>();
cursors_store_->SetCapacity(5000);
Status s = StartBGThread();
if (!s.ok()) {
fprintf(stderr,
"[FATAL] start bg thread failed, %s\n", s.ToString().c_str());
exit(-1);
}
}
BlackWidow::~BlackWidow() {
bg_tasks_should_exit_ = true;
bg_tasks_cond_var_.Signal();
if (is_opened_) {
rocksdb::CancelAllBackgroundWork(strings_db_->GetDB(), true);
rocksdb::CancelAllBackgroundWork(hashes_db_->GetDB(), true);
rocksdb::CancelAllBackgroundWork(sets_db_->GetDB(), true);
rocksdb::CancelAllBackgroundWork(lists_db_->GetDB(), true);
rocksdb::CancelAllBackgroundWork(zsets_db_->GetDB(), true);
}
int ret = 0;
if ((ret = pthread_join(bg_tasks_thread_id_, NULL)) != 0) {
fprintf(stderr, "pthread_join failed with bgtask thread error %d\n", ret);
}
delete strings_db_;
delete hashes_db_;
delete sets_db_;
delete lists_db_;
delete zsets_db_;
delete cursors_store_;
}
static std::string AppendSubDirectory(const std::string& db_path,
const std::string& sub_db) {
if (db_path.back() == '/') {
return db_path + sub_db;
} else {
return db_path + "/" + sub_db;
}
}
Status BlackWidow::Open(const BlackwidowOptions& bw_options,
const std::string& db_path) {
mkpath(db_path.c_str(), 0755);
strings_db_ = new RedisStrings(this, kStrings);
Status s = strings_db_->Open(
bw_options, AppendSubDirectory(db_path, "strings"));
if (!s.ok()) {
fprintf(stderr,
"[FATAL] open kv db failed, %s\n", s.ToString().c_str());
exit(-1);
}
hashes_db_ = new RedisHashes(this, kHashes);
s = hashes_db_->Open(bw_options, AppendSubDirectory(db_path, "hashes"));
if (!s.ok()) {
fprintf(stderr,
"[FATAL] open hashes db failed, %s\n", s.ToString().c_str());
exit(-1);
}
sets_db_ = new RedisSets(this, kSets);
s = sets_db_->Open(bw_options, AppendSubDirectory(db_path, "sets"));
if (!s.ok()) {
fprintf(stderr,
"[FATAL] open set db failed, %s\n", s.ToString().c_str());
exit(-1);
}
lists_db_ = new RedisLists(this, kLists);
s = lists_db_->Open(bw_options, AppendSubDirectory(db_path, "lists"));
if (!s.ok()) {
fprintf(stderr,
"[FATAL] open list db failed, %s\n", s.ToString().c_str());
exit(-1);
}
zsets_db_ = new RedisZSets(this, kZSets);
s = zsets_db_->Open(bw_options, AppendSubDirectory(db_path, "zsets"));
if (!s.ok()) {
fprintf(stderr,
"[FATAL] open zset db failed, %s\n", s.ToString().c_str());
exit(-1);
}
is_opened_.store(true);
return Status::OK();
}
Status BlackWidow::GetStartKey(const DataType& dtype, int64_t cursor, std::string* start_key) {
std::string index_key = DataTypeTag[dtype] + std::to_string(cursor);
return cursors_store_->Lookup(index_key, start_key);
}
Status BlackWidow::StoreCursorStartKey(const DataType& dtype, int64_t cursor,
const std::string& next_key) {
std::string index_key = DataTypeTag[dtype] + std::to_string(cursor);
return cursors_store_->Insert(index_key, next_key);
}
// Strings Commands
Status BlackWidow::Set(const Slice& key,
const Slice& value) {
return strings_db_->Set(key, value);
}
Status BlackWidow::SetOnce(const Slice& key,
const Slice& value) {
return strings_db_->SetOnce(key, value);
}
Status BlackWidow::Setxx(const Slice& key,
const Slice& value,
int32_t* ret,
const int32_t ttl) {
return strings_db_->Setxx(key, value, ret, ttl);
}
Status BlackWidow::Get(const Slice& key, std::string* value) {
return strings_db_->Get(key, value);
}
Status BlackWidow::GetSet(const Slice& key, const Slice& value,
std::string* old_value) {
return strings_db_->GetSet(key, value, old_value);
}
Status BlackWidow::SetBit(const Slice& key, int64_t offset,
int32_t value, int32_t* ret) {
return strings_db_->SetBit(key, offset, value, ret);
}
Status BlackWidow::GetBit(const Slice& key, int64_t offset, int32_t* ret) {
return strings_db_->GetBit(key, offset, ret);
}
Status BlackWidow::MSet(const std::vector<KeyValue>& kvs) {
return strings_db_->MSet(kvs);
}
Status BlackWidow::MGet(const std::vector<std::string>& keys,
std::vector<ValueStatus>* vss) {
return strings_db_->MGet(keys, vss);
}
Status BlackWidow::Setnx(const Slice& key, const Slice& value,
int32_t* ret, const int32_t ttl) {
return strings_db_->Setnx(key, value, ret, ttl);
}
Status BlackWidow::MSetnx(const std::vector<KeyValue>& kvs,
int32_t* ret) {
return strings_db_->MSetnx(kvs, ret);
}
Status BlackWidow::Setvx(const Slice& key, const Slice& value,
const Slice& new_value, int32_t* ret,
const int32_t ttl) {
return strings_db_->Setvx(key, value, new_value, ret, ttl);
}
Status BlackWidow::Delvx(const Slice& key, const Slice& value, int32_t* ret) {
return strings_db_->Delvx(key, value, ret);
}
Status BlackWidow::Setrange(const Slice& key, int64_t start_offset,
const Slice& value, int32_t* ret) {
return strings_db_->Setrange(key, start_offset, value, ret);
}
Status BlackWidow::Getrange(const Slice& key, int64_t start_offset,
int64_t end_offset, std::string* ret) {
return strings_db_->Getrange(key, start_offset, end_offset, ret);
}
Status BlackWidow::Append(const Slice& key, const Slice& value, int32_t* ret) {
return strings_db_->Append(key, value, ret);
}
Status BlackWidow::BitCount(const Slice& key, int64_t start_offset,
int64_t end_offset, int32_t *ret, bool have_range) {
return strings_db_->BitCount(key, start_offset, end_offset, ret, have_range);
}
Status BlackWidow::BitOp(BitOpType op, const std::string& dest_key,
const std::vector<std::string>& src_keys,
int64_t* ret) {
return strings_db_->BitOp(op, dest_key, src_keys, ret);
}
Status BlackWidow::BitPos(const Slice& key, int32_t bit,
int64_t* ret) {
return strings_db_->BitPos(key, bit, ret);
}
Status BlackWidow::BitPos(const Slice& key, int32_t bit,
int64_t start_offset, int64_t* ret) {
return strings_db_->BitPos(key, bit, start_offset, ret);
}
Status BlackWidow::BitPos(const Slice& key, int32_t bit,
int64_t start_offset, int64_t end_offset,
int64_t* ret) {
return strings_db_->BitPos(key, bit, start_offset, end_offset, ret);
}
Status BlackWidow::Decrby(const Slice& key, int64_t value, int64_t* ret) {
return strings_db_->Decrby(key, value, ret);
}
Status BlackWidow::Incrby(const Slice& key, int64_t value, int64_t* ret) {
return strings_db_->Incrby(key, value, ret);
}
Status BlackWidow::Incrbyrange(const Slice& key, int64_t value, int64_t* ret, int64_t min_, int64_t max_) {
return strings_db_->Incrbyrange(key, value, ret, min_, max_);
}
Status BlackWidow::Incrbyfloat(const Slice& key, const Slice& value,
std::string* ret) {
return strings_db_->Incrbyfloat(key, value, ret);
}
Status BlackWidow::Setex(const Slice& key, const Slice& value, int32_t ttl) {
return strings_db_->Setex(key, value, ttl);
}
Status BlackWidow::Strlen(const Slice& key, int32_t* len) {
return strings_db_->Strlen(key, len);
}
Status BlackWidow::PKSetexAt(const Slice& key,
const Slice& value,
int32_t timestamp) {
return strings_db_->PKSetexAt(key, value, timestamp);
}
// Hashes Commands
Status BlackWidow::HSet(const Slice& key, const Slice& field,
const Slice& value, int32_t* res) {
return hashes_db_->HSet(key, field, value, res);
}
Status BlackWidow::HSetOnce(const Slice& key, const Slice& field,
const Slice& value, int32_t* res) {
return hashes_db_->HSetOnce(key, field, value, res);
}
Status BlackWidow::HGet(const Slice& key, const Slice& field,
std::string* value) {
return hashes_db_->HGet(key, field, value);
}
Status BlackWidow::HMSet(const Slice& key,
const std::vector<FieldValue>& fvs) {
return hashes_db_->HMSet(key, fvs);
}
Status BlackWidow::HMGet(const Slice& key,
const std::vector<std::string>& fields,
std::vector<ValueStatus>* vss) {
return hashes_db_->HMGet(key, fields, vss);
}
Status BlackWidow::HGetall(const Slice& key,
std::vector<FieldValue>* fvs) {
return hashes_db_->HGetall(key, fvs);
}
Status BlackWidow::HKeys(const Slice& key,
std::vector<std::string>* fields) {
return hashes_db_->HKeys(key, fields);
}
Status BlackWidow::HVals(const Slice& key,
std::vector<std::string>* values) {
return hashes_db_->HVals(key, values);
}
Status BlackWidow::HSetnx(const Slice& key, const Slice& field,
const Slice& value, int32_t* ret) {
return hashes_db_->HSetnx(key, field, value, ret);
}
Status BlackWidow::HLen(const Slice& key, int32_t* ret) {
return hashes_db_->HLen(key, ret);
}
Status BlackWidow::HStrlen(const Slice& key, const Slice& field, int32_t* len) {
return hashes_db_->HStrlen(key, field, len);
}
Status BlackWidow::HExists(const Slice& key, const Slice& field) {
return hashes_db_->HExists(key, field);
}
Status BlackWidow::HIncrby(const Slice& key, const Slice& field, int64_t value,
int64_t* ret) {
return hashes_db_->HIncrby(key, field, value, ret);
}
Status BlackWidow::HIncrbyrange(const Slice& key, const Slice& field, int64_t value,
int64_t* ret, int64_t min_, int64_t max_) {
return hashes_db_->HIncrbyrange(key, field, value, ret, min_, max_);
}
Status BlackWidow::HIncrbyfloat(const Slice& key, const Slice& field,
const Slice& by, std::string* new_value) {
return hashes_db_->HIncrbyfloat(key, field, by, new_value);
}
Status BlackWidow::HDel(const Slice& key,
const std::vector<std::string>& fields,
int32_t* ret) {
return hashes_db_->HDel(key, fields, ret);
}
Status BlackWidow::HScan(const Slice& key, int64_t cursor,
const std::string& pattern, int64_t count,
std::vector<FieldValue>* field_values,
int64_t* next_cursor) {
return hashes_db_->HScan(key, cursor,
pattern, count, field_values, next_cursor);
}
Status BlackWidow::HScanx(const Slice& key, const std::string start_field,
const std::string& pattern, int64_t count,
std::vector<FieldValue>* field_values,
std::string* next_field) {
return hashes_db_->HScanx(key, start_field,
pattern, count, field_values, next_field);
}
Status BlackWidow::PKHScanRange(const Slice& key, const Slice& field_start,
const std::string& field_end,
const Slice& pattern, int32_t limit,
std::vector<FieldValue>* field_values,
std::string* next_field) {
return hashes_db_->PKHScanRange(key, field_start,
field_end, pattern, limit, field_values, next_field);
}
Status BlackWidow::PKHRScanRange(const Slice& key, const Slice& field_start,
const std::string& field_end,
const Slice& pattern, int32_t limit,
std::vector<FieldValue>* field_values,
std::string* next_field) {
return hashes_db_->PKHRScanRange(key, field_start,
field_end, pattern, limit, field_values, next_field);
}
// Sets Commands
Status BlackWidow::SAdd(const Slice& key,
const std::vector<std::string>& members,
int32_t* ret) {
return sets_db_->SAdd(key, members, ret);
}
Status BlackWidow::SCard(const Slice& key,
int32_t* ret) {
return sets_db_->SCard(key, ret);
}
Status BlackWidow::SDiff(const std::vector<std::string>& keys,
std::vector<std::string>* members) {
return sets_db_->SDiff(keys, members);
}
Status BlackWidow::SDiffstore(const Slice& destination,
const std::vector<std::string>& keys,
int32_t* ret) {
return sets_db_->SDiffstore(destination, keys, ret);
}
Status BlackWidow::SInter(const std::vector<std::string>& keys,
std::vector<std::string>* members) {
return sets_db_->SInter(keys, members);
}
Status BlackWidow::SInterstore(const Slice& destination,
const std::vector<std::string>& keys,
int32_t* ret) {
return sets_db_->SInterstore(destination, keys, ret);
}
Status BlackWidow::SIsmember(const Slice& key, const Slice& member,
int32_t* ret) {
return sets_db_->SIsmember(key, member, ret);
}
Status BlackWidow::SMembers(const Slice& key,
std::vector<std::string>* members) {
return sets_db_->SMembers(key, members);
}
Status BlackWidow::SMove(const Slice& source, const Slice& destination,
const Slice& member, int32_t* ret) {
return sets_db_->SMove(source, destination, member, ret);
}
Status BlackWidow::SPop(const Slice& key, std::string* member) {
bool need_compact = false;
Status status = sets_db_->SPop(key, member, &need_compact);
if (need_compact) {
AddBGTask({kSets, kCompactKey, key.ToString()});
}
return status;
}
Status BlackWidow::SRandmember(const Slice& key, int32_t count,
std::vector<std::string>* members) {
return sets_db_->SRandmember(key, count, members);
}
Status BlackWidow::SRem(const Slice& key,
const std::vector<std::string>& members,
int32_t* ret) {
return sets_db_->SRem(key, members, ret);
}
Status BlackWidow::SUnion(const std::vector<std::string>& keys,
std::vector<std::string>* members) {
return sets_db_->SUnion(keys, members);
}
Status BlackWidow::SUnionstore(const Slice& destination,
const std::vector<std::string>& keys,
int32_t* ret) {
return sets_db_->SUnionstore(destination, keys, ret);
}
Status BlackWidow::SScan(const Slice& key, int64_t cursor,
const std::string& pattern, int64_t count,
std::vector<std::string>* members,
int64_t* next_cursor) {
return sets_db_->SScan(key, cursor, pattern, count, members, next_cursor);
}
Status BlackWidow::LPush(const Slice& key,
const std::vector<std::string>& values,
uint64_t* ret) {
return lists_db_->LPush(key, values, ret);
}
Status BlackWidow::RPush(const Slice& key,
const std::vector<std::string>& values,
uint64_t* ret) {
return lists_db_->RPush(key, values, ret);
}
Status BlackWidow::LRange(const Slice& key, int64_t start, int64_t stop,
std::vector<std::string>* ret) {
return lists_db_->LRange(key, start, stop, ret);
}
Status BlackWidow::LTrim(const Slice& key, int64_t start, int64_t stop) {
return lists_db_->LTrim(key, start, stop);
}
Status BlackWidow::LLen(const Slice& key, uint64_t* len) {
return lists_db_->LLen(key, len);
}
Status BlackWidow::LPop(const Slice& key, std::string* element) {
return lists_db_->LPop(key, element);
}
Status BlackWidow::RPop(const Slice& key, std::string* element) {
return lists_db_->RPop(key, element);
}
Status BlackWidow::LIndex(const Slice& key,
int64_t index,
std::string* element) {
return lists_db_->LIndex(key, index, element);
}
Status BlackWidow::LInsert(const Slice& key,
const BeforeOrAfter& before_or_after,
const std::string& pivot,
const std::string& value,
int64_t* ret) {
return lists_db_->LInsert(key, before_or_after, pivot, value, ret);
}
Status BlackWidow::LPushx(const Slice& key, const Slice& value, uint64_t* len) {
return lists_db_->LPushx(key, value, len);
}
Status BlackWidow::RPushx(const Slice& key, const Slice& value, uint64_t* len) {
return lists_db_->RPushx(key, value, len);
}
Status BlackWidow::LRem(const Slice& key, int64_t count,
const Slice& value, uint64_t* ret) {
return lists_db_->LRem(key, count, value, ret);
}
Status BlackWidow::LSet(const Slice& key, int64_t index, const Slice& value) {
return lists_db_->LSet(key, index, value);
}
Status BlackWidow::RPoplpush(const Slice& source,
const Slice& destination,
std::string* element) {
return lists_db_->RPoplpush(source, destination, element);
}
Status BlackWidow::ZPopMax(const Slice& key,
const int64_t count,
std::vector<ScoreMember>* score_members){
return zsets_db_->ZPopMax(key, count, score_members);
}
Status BlackWidow::ZPopMin(const Slice& key,
const int64_t count,
std::vector<ScoreMember>* score_members){
return zsets_db_->ZPopMin(key, count, score_members);
}
Status BlackWidow::ZAdd(const Slice& key,
const std::vector<ScoreMember>& score_members,
int32_t* ret) {
return zsets_db_->ZAdd(key, score_members, ret);
}
Status BlackWidow::ZCard(const Slice& key,
int32_t* ret) {
return zsets_db_->ZCard(key, ret);
}
Status BlackWidow::ZCount(const Slice& key,
double min,
double max,
bool left_close,
bool right_close,
int32_t* ret) {
return zsets_db_->ZCount(key, min, max, left_close, right_close, ret);
}
Status BlackWidow::ZIncrby(const Slice& key,
const Slice& member,
double increment,
double* ret) {
return zsets_db_->ZIncrby(key, member, increment, ret);
}
Status BlackWidow::ZRange(const Slice& key,
int32_t start,
int32_t stop,
std::vector<ScoreMember>* score_members) {
return zsets_db_->ZRange(key, start, stop, score_members);
}
Status BlackWidow::ZRangebyscore(const Slice& key,
double min,
double max,
bool left_close,
bool right_close,
std::vector<ScoreMember>* score_members) {
return zsets_db_->ZRangebyscore(key, min, max,
left_close, right_close, score_members);
}
Status BlackWidow::ZRank(const Slice& key,
const Slice& member,
int32_t* rank) {
return zsets_db_->ZRank(key, member, rank);
}
Status BlackWidow::ZRem(const Slice& key,
std::vector<std::string> members,
int32_t* ret) {
return zsets_db_->ZRem(key, members, ret);
}
Status BlackWidow::ZRemrangebyrank(const Slice& key,
int32_t start,
int32_t stop,
int32_t* ret) {
return zsets_db_->ZRemrangebyrank(key, start, stop, ret);
}
Status BlackWidow::ZRemrangebyscore(const Slice& key,
double min,
double max,
bool left_close,
bool right_close,
int32_t* ret) {
return zsets_db_->ZRemrangebyscore(key, min, max,
left_close, right_close, ret);
}
Status BlackWidow::ZRevrange(const Slice& key,
int32_t start,
int32_t stop,
std::vector<ScoreMember>* score_members) {
return zsets_db_->ZRevrange(key, start, stop, score_members);
}
Status BlackWidow::ZRevrangebyscore(const Slice& key,
double min,
double max,
bool left_close,
bool right_close,
std::vector<ScoreMember>* score_members) {
return zsets_db_->ZRevrangebyscore(key, min, max,
left_close, right_close, score_members);
}
Status BlackWidow::ZRevrank(const Slice& key,
const Slice& member,
int32_t* rank) {
return zsets_db_->ZRevrank(key, member, rank);
}
Status BlackWidow::ZScore(const Slice& key,
const Slice& member,
double* ret) {
return zsets_db_->ZScore(key, member, ret);
}
Status BlackWidow::ZUnionstore(const Slice& destination,
const std::vector<std::string>& keys,
const std::vector<double>& weights,
const AGGREGATE agg,
int32_t* ret) {
return zsets_db_->ZUnionstore(destination, keys, weights, agg, ret);
}
Status BlackWidow::ZInterstore(const Slice& destination,
const std::vector<std::string>& keys,
const std::vector<double>& weights,
const AGGREGATE agg,
int32_t* ret) {
return zsets_db_->ZInterstore(destination, keys, weights, agg, ret);
}
Status BlackWidow::ZRangebylex(const Slice& key,
const Slice& min,
const Slice& max,
bool left_close,
bool right_close,
std::vector<std::string>* members) {
return zsets_db_->ZRangebylex(key, min, max,
left_close, right_close, members);
}
Status BlackWidow::ZLexcount(const Slice& key,
const Slice& min,
const Slice& max,
bool left_close,
bool right_close,
int32_t* ret) {
return zsets_db_->ZLexcount(key, min, max, left_close, right_close, ret);
}
Status BlackWidow::ZRemrangebylex(const Slice& key,
const Slice& min,
const Slice& max,
bool left_close,
bool right_close,
int32_t* ret) {
return zsets_db_->ZRemrangebylex(key, min, max, left_close, right_close, ret);
}
Status BlackWidow::ZScan(const Slice& key, int64_t cursor,
const std::string& pattern, int64_t count,
std::vector<ScoreMember>* score_members,
int64_t* next_cursor) {
return zsets_db_->ZScan(key, cursor,
pattern, count, score_members, next_cursor);
}
// Keys Commands
int32_t BlackWidow::Expire(const Slice& key, int32_t ttl,
std::map<DataType, Status>* type_status) {
int32_t ret = 0;
bool is_corruption = false;
// Strings
Status s = strings_db_->Expire(key, ttl);
if (s.ok()) {
ret++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kStrings] = s;
}
// Hash
s = hashes_db_->Expire(key, ttl);
if (s.ok()) {
ret++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kHashes] = s;
}
// Sets
s = sets_db_->Expire(key, ttl);
if (s.ok()) {
ret++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kSets] = s;
}
// Lists
s = lists_db_->Expire(key, ttl);
if (s.ok()) {
ret++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
// Zsets
s = zsets_db_->Expire(key, ttl);
if (s.ok()) {
ret++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kZSets] = s;
}
if (is_corruption) {
return -1;
} else {
return ret;
}
}
int64_t BlackWidow::Del(const std::vector<std::string>& keys,
std::map<DataType, Status>* type_status) {
Status s;
int64_t count = 0;
bool is_corruption = false;
for (const auto& key : keys) {
// Strings
Status s = strings_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kStrings] = s;
}
// Hashes
s = hashes_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kHashes] = s;
}
// Sets
s = sets_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kSets] = s;
}
// Lists
s = lists_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
// ZSets
s = zsets_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kZSets] = s;
}
}
if (is_corruption) {
return -1;
} else {
return count;
}
}
int64_t BlackWidow::DelByType(const std::vector<std::string>& keys,
const DataType& type) {
Status s;
int64_t count = 0;
bool is_corruption = false;
for (const auto& key : keys) {
switch (type) {
// Strings
case DataType::kStrings:
{
s = strings_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
}
break;
}
// Hashes
case DataType::kHashes:
{
s = hashes_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
}
break;
}
// Sets
case DataType::kSets:
{
s = sets_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
}
break;
}
// Lists
case DataType::kLists:
{
s = lists_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
}
break;
}
// ZSets
case DataType::kZSets:
{
s = zsets_db_->Del(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
}
break;
}
case DataType::kAll:
{
return -1;
}
}
}
if (is_corruption) {
return -1;
} else {
return count;
}
}
int64_t BlackWidow::Exists(const std::vector<std::string>& keys,
std::map<DataType, Status>* type_status) {
int64_t count = 0;
int32_t ret;
uint64_t llen;
std::string value;
Status s;
bool is_corruption = false;
for (const auto& key : keys) {
s = strings_db_->Get(key, &value);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kStrings] = s;
}
s = hashes_db_->HLen(key, &ret);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kHashes] = s;
}
s = sets_db_->SCard(key, &ret);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kSets] = s;
}
s = lists_db_->LLen(key, &llen);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
s = zsets_db_->ZCard(key, &ret);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kZSets] = s;
}
}
if (is_corruption) {
return -1;
} else {
return count;
}
}
int64_t BlackWidow::Scan(const DataType& dtype, int64_t cursor,
const std::string& pattern, int64_t count,
std::vector<std::string>* keys) {
keys->clear();
bool is_finish;
int64_t leftover_visits = count;
int64_t step_length = count, cursor_ret = 0;
std::string start_key, next_key, prefix;
prefix = isTailWildcard(pattern) ?
pattern.substr(0, pattern.size() - 1) : "";
if (cursor < 0) {
return cursor_ret;
} else {
Status s = GetStartKey(dtype, cursor, &start_key);
if (s.IsNotFound()) {
// If want to scan all the databases, we start with the strings database
start_key = (dtype == DataType::kAll
? DataTypeTag[kStrings] : DataTypeTag[dtype]) + prefix;
cursor = 0;
}
}
char key_type = start_key.at(0);
start_key.erase(start_key.begin());
switch (key_type) {
case 'k':
is_finish = strings_db_->Scan(start_key, pattern,
keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key);
break;
} else if (is_finish) {
if (DataType::kStrings == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("h") + prefix);
break;
}
}
start_key = prefix;
case 'h':
is_finish = hashes_db_->Scan(start_key, pattern,
keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key);
break;
} else if (is_finish) {
if (DataType::kHashes == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("s") + prefix);
break;
}
}
start_key = prefix;
case 's':
is_finish = sets_db_->Scan(start_key, pattern,
keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key);
break;
} else if (is_finish) {
if (DataType::kSets == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("l") + prefix);
break;
}
}
start_key = prefix;
case 'l':
is_finish = lists_db_->Scan(start_key, pattern,
keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key);
break;
} else if (is_finish) {
if (DataType::kLists == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("z") + prefix);
break;
}
}
start_key = prefix;
case 'z':
is_finish = zsets_db_->Scan(start_key, pattern,
keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key);
break;
} else if (is_finish) {
cursor_ret = 0;
break;
}
}
return cursor_ret;
}
int64_t BlackWidow::PKExpireScan(const DataType& dtype, int64_t cursor,
int32_t min_ttl, int32_t max_ttl,
int64_t count, std::vector<std::string>* keys) {
keys->clear();
bool is_finish;
int64_t leftover_visits = count;
int64_t step_length = count, cursor_ret = 0;
std::string start_key, next_key;
int64_t curtime;
rocksdb::Env::Default()->GetCurrentTime(&curtime);
if (cursor < 0) {
return cursor_ret;
} else {
Status s = GetStartKey(dtype, cursor, &start_key);
if (s.IsNotFound()) {
// If want to scan all the databases, we start with the strings database
start_key = std::string(1, dtype == DataType::kAll
? DataTypeTag[kStrings] : DataTypeTag[dtype]);
cursor = 0;
}
}
char key_type = start_key.at(0);
start_key.erase(start_key.begin());
switch (key_type) {
case 'k':
is_finish = strings_db_->PKExpireScan(start_key, curtime + min_ttl,
curtime + max_ttl, keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key);
break;
} else if (is_finish) {
if (DataType::kStrings == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("h"));
break;
}
}
start_key = "";
case 'h':
is_finish = hashes_db_->PKExpireScan(start_key, curtime + min_ttl,
curtime + max_ttl, keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key);
break;
} else if (is_finish) {
if (DataType::kHashes == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("s"));
break;
}
}
start_key = "";
case 's':
is_finish = sets_db_->PKExpireScan(start_key, curtime + min_ttl,
curtime + max_ttl, keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key);
break;
} else if (is_finish) {
if (DataType::kSets == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("l"));
break;
}
}
start_key = "";
case 'l':
is_finish = lists_db_->PKExpireScan(start_key, curtime + min_ttl,
curtime + max_ttl, keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key);
break;
} else if (is_finish) {
if (DataType::kLists == dtype) {
cursor_ret = 0;
break;
} else if (!leftover_visits) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("z"));
break;
}
}
start_key = "";
case 'z':
is_finish = zsets_db_->PKExpireScan(start_key, curtime + min_ttl,
curtime + max_ttl, keys, &leftover_visits, &next_key);
if (!leftover_visits && !is_finish) {
cursor_ret = cursor + step_length;
StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key);
break;
} else if (is_finish) {
cursor_ret = 0;
break;
}
}
return cursor_ret;
}
Status BlackWidow::PKScanRange(const DataType& data_type,
const Slice& key_start, const Slice& key_end,
const Slice& pattern, int32_t limit,
std::vector<std::string>* keys,
std::vector<KeyValue>* kvs,
std::string* next_key) {
Status s;
keys->clear();
next_key->clear();
switch (data_type) {
case DataType::kStrings:
s = strings_db_->PKScanRange(key_start, key_end,
pattern, limit, kvs, next_key);
break;
case DataType::kHashes:
s = hashes_db_->PKScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kLists:
s = lists_db_->PKScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kZSets:
s = zsets_db_->PKScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kSets:
s = sets_db_->PKScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
default:
s = Status::Corruption("Unsupported data types");
break;
}
return s;
}
Status BlackWidow::PKRScanRange(const DataType& data_type,
const Slice& key_start, const Slice& key_end,
const Slice& pattern, int32_t limit,
std::vector<std::string>* keys,
std::vector<KeyValue>* kvs,
std::string* next_key) {
Status s;
keys->clear();
next_key->clear();
switch (data_type) {
case DataType::kStrings:
s = strings_db_->PKRScanRange(key_start, key_end,
pattern, limit, kvs, next_key);
break;
case DataType::kHashes:
s = hashes_db_->PKRScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kLists:
s = lists_db_->PKRScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kZSets:
s = zsets_db_->PKRScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
case DataType::kSets:
s = sets_db_->PKRScanRange(key_start, key_end,
pattern, limit, keys, next_key);
break;
default:
s = Status::Corruption("Unsupported data types");
break;
}
return s;
}
Status BlackWidow::PKPatternMatchDel(const DataType& data_type,
const std::string& pattern,
int32_t* ret) {
Status s;
switch (data_type) {
case DataType::kStrings:
s = strings_db_->PKPatternMatchDel(pattern, ret);
break;
case DataType::kHashes:
s = hashes_db_->PKPatternMatchDel(pattern, ret);
break;
case DataType::kLists:
s = lists_db_->PKPatternMatchDel(pattern, ret);
break;
case DataType::kZSets:
s = zsets_db_->PKPatternMatchDel(pattern, ret);
break;
case DataType::kSets:
s = sets_db_->PKPatternMatchDel(pattern, ret);
break;
default:
s = Status::Corruption("Unsupported data type");
break;
}
return s;
}
Status BlackWidow::Scanx(const DataType& data_type,
const std::string& start_key,
const std::string& pattern,
int64_t count,
std::vector<std::string>* keys,
std::string* next_key) {
Status s;
keys->clear();
next_key->clear();
switch (data_type) {
case DataType::kStrings:
strings_db_->Scan(start_key, pattern, keys, &count, next_key);
break;
case DataType::kHashes:
hashes_db_->Scan(start_key, pattern, keys, &count, next_key);
break;
case DataType::kLists:
lists_db_->Scan(start_key, pattern, keys, &count, next_key);
break;
case DataType::kZSets:
zsets_db_->Scan(start_key, pattern, keys, &count, next_key);
break;
case DataType::kSets:
sets_db_->Scan(start_key, pattern, keys, &count, next_key);
break;
default:
Status::Corruption("Unsupported data types");
break;
}
return s;
}
int32_t BlackWidow::Expireat(const Slice& key, int32_t timestamp,
std::map<DataType, Status>* type_status) {
Status s;
int32_t count = 0;
bool is_corruption = false;
s = strings_db_->Expireat(key, timestamp);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kStrings] = s;
}
s = hashes_db_->Expireat(key, timestamp);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kHashes] = s;
}
s = sets_db_->Expireat(key, timestamp);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kSets] = s;
}
s = lists_db_->Expireat(key, timestamp);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
s = zsets_db_->Expireat(key, timestamp);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
if (is_corruption) {
return -1;
} else {
return count;
}
}
int32_t BlackWidow::Persist(const Slice& key,
std::map<DataType, Status>* type_status) {
Status s;
int32_t count = 0;
bool is_corruption = false;
s = strings_db_->Persist(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kStrings] = s;
}
s = hashes_db_->Persist(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kHashes] = s;
}
s = sets_db_->Persist(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kSets] = s;
}
s = lists_db_->Persist(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
s = zsets_db_->Persist(key);
if (s.ok()) {
count++;
} else if (!s.IsNotFound()) {
is_corruption = true;
(*type_status)[DataType::kLists] = s;
}
if (is_corruption) {
return -1;
} else {
return count;
}
}
std::map<DataType, int64_t> BlackWidow::TTL(const Slice& key,
std::map<DataType, Status>* type_status) {
Status s;
std::map<DataType, int64_t> ret;
int64_t timestamp = 0;
s = strings_db_->TTL(key, ×tamp);
if (s.ok() || s.IsNotFound()) {
ret[DataType::kStrings] = timestamp;
} else if (!s.IsNotFound()) {
ret[DataType::kStrings] = -3;
(*type_status)[DataType::kStrings] = s;
}
s = hashes_db_->TTL(key, ×tamp);
if (s.ok() || s.IsNotFound()) {
ret[DataType::kHashes] = timestamp;
} else if (!s.IsNotFound()) {
ret[DataType::kHashes] = -3;
(*type_status)[DataType::kHashes] = s;
}
s = lists_db_->TTL(key, ×tamp);
if (s.ok() || s.IsNotFound()) {
ret[DataType::kLists] = timestamp;
} else if (!s.IsNotFound()) {
ret[DataType::kLists] = -3;
(*type_status)[DataType::kLists] = s;
}
s = sets_db_->TTL(key, ×tamp);
if (s.ok() || s.IsNotFound()) {
ret[DataType::kSets] = timestamp;
} else if (!s.IsNotFound()) {
ret[DataType::kSets] = -3;
(*type_status)[DataType::kSets] = s;
}
s = zsets_db_->TTL(key, ×tamp);
if (s.ok() || s.IsNotFound()) {
ret[DataType::kZSets] = timestamp;
} else if (!s.IsNotFound()) {
ret[DataType::kZSets] = -3;
(*type_status)[DataType::kZSets] = s;
}
return ret;
}
// the sequence is kv, hash, list, zset, set
Status BlackWidow::Type(const std::string &key, std::string* type) {
type->clear();
Status s;
std::string value;
s = strings_db_->Get(key, &value);
if (s.ok()) {
*type = "string";
return s;
} else if (!s.IsNotFound()) {
return s;
}
int32_t hashes_len = 0;
s = hashes_db_->HLen(key, &hashes_len);
if (s.ok() && hashes_len != 0) {
*type = "hash";
return s;
} else if (!s.IsNotFound()) {
return s;
}
uint64_t lists_len = 0;
s = lists_db_->LLen(key, &lists_len);
if (s.ok() && lists_len != 0) {
*type = "list";
return s;
} else if (!s.IsNotFound()) {
return s;
}
int32_t zsets_size = 0;
s = zsets_db_->ZCard(key, &zsets_size);
if (s.ok() && zsets_size != 0) {
*type = "zset";
return s;
} else if (!s.IsNotFound()) {
return s;
}
int32_t sets_size = 0;
s = sets_db_->SCard(key, &sets_size);
if (s.ok() && sets_size != 0) {
*type = "set";
return s;
} else if (!s.IsNotFound()) {
return s;
}
*type = "none";
return Status::OK();
}
Status BlackWidow::Keys(const DataType& data_type,
const std::string& pattern,
std::vector<std::string>* keys) {
Status s;
if (data_type == DataType::kStrings) {
s = strings_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
} else if (data_type == DataType::kHashes) {
s = hashes_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
} else if (data_type == DataType::kZSets) {
s = zsets_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
} else if (data_type == DataType::kSets) {
s = sets_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
} else if (data_type == DataType::kLists) {
s = lists_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
} else {
s = strings_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
s = hashes_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
s = zsets_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
s = sets_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
s = lists_db_->ScanKeys(pattern, keys);
if (!s.ok()) return s;
}
return s;
}
void BlackWidow::ScanDatabase(const DataType& type) {
switch (type) {
case kStrings:
strings_db_->ScanDatabase();
break;
case kHashes:
hashes_db_->ScanDatabase();
break;
case kSets:
sets_db_->ScanDatabase();
break;
case kZSets:
zsets_db_->ScanDatabase();
break;
case kLists:
lists_db_->ScanDatabase();
break;
case kAll:
strings_db_->ScanDatabase();
hashes_db_->ScanDatabase();
sets_db_->ScanDatabase();
zsets_db_->ScanDatabase();
lists_db_->ScanDatabase();
break;
}
}
// HyperLogLog
Status BlackWidow::PfAdd(const Slice& key,
const std::vector<std::string>& values,
bool* update) {
*update = false;
if (values.size() >= kMaxKeys) {
return Status::InvalidArgument("Invalid the number of key");
}
std::string value, registers, result = "";
Status s = strings_db_->Get(key, &value);
if (s.ok()) {
registers = value;
} else if (s.IsNotFound()) {
registers = "";
} else {
return s;
}
HyperLogLog log(kPrecision, registers);
int32_t previous = static_cast<int32_t>(log.Estimate());
for (size_t i = 0; i < values.size(); ++i) {
result = log.Add(values[i].data(), values[i].size());
}
HyperLogLog update_log(kPrecision, result);
int32_t now = static_cast<int32_t>(update_log.Estimate());
if (previous != now || (s.IsNotFound() && values.size() == 0)) {
*update = true;
}
s = strings_db_->Set(key, result);
return s;
}
Status BlackWidow::PfCount(const std::vector<std::string>& keys,
int64_t* result) {
if (keys.size() >= kMaxKeys || keys.size() <= 0) {
return Status::InvalidArgument("Invalid the number of key");
}
std::string value, first_registers;
Status s = strings_db_->Get(keys[0], &value);
if (s.ok()) {
first_registers = std::string(value.data(), value.size());
} else if (s.IsNotFound()) {
first_registers = "";
}
HyperLogLog first_log(kPrecision, first_registers);
for (size_t i = 1; i < keys.size(); ++i) {
std::string value, registers;
s = strings_db_->Get(keys[i], &value);
if (s.ok()) {
registers = value;
} else if (s.IsNotFound()) {
continue;
} else {
return s;
}
HyperLogLog log(kPrecision, registers);
first_log.Merge(log);
}
*result = static_cast<int32_t>(first_log.Estimate());
return Status::OK();
}
Status BlackWidow::PfMerge(const std::vector<std::string>& keys) {
if (keys.size() >= kMaxKeys || keys.size() <= 0) {
return Status::InvalidArgument("Invalid the number of key");
}
Status s;
std::string value, first_registers, result;
s = strings_db_->Get(keys[0], &value);
if (s.ok()) {
first_registers = std::string(value.data(), value.size());
} else if (s.IsNotFound()) {
first_registers = "";
}
result = first_registers;
HyperLogLog first_log(kPrecision, first_registers);
for (size_t i = 1; i < keys.size(); ++i) {
std::string value, registers;
s = strings_db_->Get(keys[i], &value);
if (s.ok()) {
registers = std::string(value.data(), value.size());
} else if (s.IsNotFound()) {
continue;
} else {
return s;
}
HyperLogLog log(kPrecision, registers);
result = first_log.Merge(log);
}
s = strings_db_->Set(keys[0], result);
return s;
}
static void* StartBGThreadWrapper(void* arg) {
BlackWidow* bw = reinterpret_cast<BlackWidow*>(arg);
bw->RunBGTask();
return NULL;
}
Status BlackWidow::StartBGThread() {
int result = pthread_create(&bg_tasks_thread_id_,
NULL, StartBGThreadWrapper, this);
if (result != 0) {
char msg[128];
snprintf(msg, sizeof(msg), "pthread create: %s", strerror(result));
return Status::Corruption(msg);
}
return Status::OK();
}
Status BlackWidow::AddBGTask(const BGTask& bg_task) {
bg_tasks_mutex_.Lock();
if (bg_task.type == kAll) {
// if current task it is global compact,
// clear the bg_tasks_queue_;
std::queue<BGTask> empty_queue;
bg_tasks_queue_.swap(empty_queue);
}
bg_tasks_queue_.push(bg_task);
bg_tasks_cond_var_.Signal();
bg_tasks_mutex_.Unlock();
return Status::OK();
}
Status BlackWidow::RunBGTask() {
BGTask task;
while (!bg_tasks_should_exit_) {
bg_tasks_mutex_.Lock();
while (bg_tasks_queue_.empty() && !bg_tasks_should_exit_) {
bg_tasks_cond_var_.Wait();
}
if (!bg_tasks_queue_.empty()) {
task = bg_tasks_queue_.front();
bg_tasks_queue_.pop();
}
bg_tasks_mutex_.Unlock();
if (bg_tasks_should_exit_) {
return Status::Incomplete("bgtask return with bg_tasks_should_exit true");
}
if (task.operation == kCleanAll) {
DoCompact(task.type);
} else if (task.operation == kCompactKey) {
CompactKey(task.type, task.argv);
}
}
return Status::OK();
}
Status BlackWidow::Compact(const DataType& type, bool sync) {
if (sync) {
return DoCompact(type);
} else {
AddBGTask({type, kCleanAll});
}
return Status::OK();
}
Status BlackWidow::DoCompact(const DataType& type) {
if (type != kAll
&& type != kStrings
&& type != kHashes
&& type != kSets
&& type != kZSets
&& type != kLists) {
return Status::InvalidArgument("");
}
Status s;
if (type == kStrings) {
current_task_type_ = Operation::kCleanStrings;
s = strings_db_->CompactRange(NULL, NULL);
} else if (type == kHashes) {
current_task_type_ = Operation::kCleanHashes;
s = hashes_db_->CompactRange(NULL, NULL);
} else if (type == kSets) {
current_task_type_ = Operation::kCleanSets;
s = sets_db_->CompactRange(NULL, NULL);
} else if (type == kZSets) {
current_task_type_ = Operation::kCleanZSets;
s = zsets_db_->CompactRange(NULL, NULL);
} else if (type == kLists) {
current_task_type_ = Operation::kCleanLists;
s = lists_db_->CompactRange(NULL, NULL);
} else {
current_task_type_ = Operation::kCleanAll;
s = strings_db_->CompactRange(NULL, NULL);
s = hashes_db_->CompactRange(NULL, NULL);
s = sets_db_->CompactRange(NULL, NULL);
s = zsets_db_->CompactRange(NULL, NULL);
s = lists_db_->CompactRange(NULL, NULL);
}
current_task_type_ = Operation::kNone;
return s;
}
Status BlackWidow::CompactKey(const DataType& type, const std::string& key) {
std::string meta_start_key, meta_end_key;
std::string data_start_key, data_end_key;
CalculateMetaStartAndEndKey(key, &meta_start_key, &meta_end_key);
CalculateDataStartAndEndKey(key, &data_start_key, &data_end_key);
Slice slice_meta_begin(meta_start_key);
Slice slice_meta_end(meta_end_key);
Slice slice_data_begin(data_start_key);
Slice slice_data_end(data_end_key);
if (type == kSets) {
sets_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta);
sets_db_->CompactRange(&slice_data_begin, &slice_data_end, kData);
} else if (type == kZSets) {
zsets_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta);
zsets_db_->CompactRange(&slice_data_begin, &slice_data_end, kData);
} else if (type == kHashes) {
hashes_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta);
hashes_db_->CompactRange(&slice_data_begin, &slice_data_end, kData);
} else if (type == kLists) {
lists_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta);
lists_db_->CompactRange(&slice_data_begin, &slice_data_end, kData);
}
return Status::OK();
}
Status BlackWidow::SetMaxCacheStatisticKeys(uint32_t max_cache_statistic_keys) {
std::vector<Redis*> dbs = {sets_db_, zsets_db_, hashes_db_, lists_db_};
for (const auto& db : dbs) {
db->SetMaxCacheStatisticKeys(max_cache_statistic_keys);
}
return Status::OK();
}
Status BlackWidow::SetSmallCompactionThreshold(uint32_t small_compaction_threshold) {
std::vector<Redis*> dbs = {sets_db_, zsets_db_, hashes_db_, lists_db_};
for (const auto& db : dbs) {
db->SetSmallCompactionThreshold(small_compaction_threshold);
}
return Status::OK();
}
std::string BlackWidow::GetCurrentTaskType() {
int type = current_task_type_;
switch (type) {
case kCleanAll:
return "All";
case kCleanStrings:
return "String";
case kCleanHashes:
return "Hash";
case kCleanZSets:
return "ZSet";
case kCleanSets:
return "Set";
case kCleanLists:
return "List";
case kNone:
default:
return "No";
}
}
Status BlackWidow::GetUsage(const std::string& property, uint64_t* const result) {
*result = GetProperty(ALL_DB, property);
return Status::OK();
}
Status BlackWidow::GetUsage(const std::string& property,
std::map<std::string, uint64_t>* const type_result) {
type_result->clear();
(*type_result)[STRINGS_DB] = GetProperty(STRINGS_DB, property);
(*type_result)[HASHES_DB] = GetProperty(HASHES_DB, property);
(*type_result)[LISTS_DB] = GetProperty(LISTS_DB, property);
(*type_result)[ZSETS_DB] = GetProperty(ZSETS_DB, property);
(*type_result)[SETS_DB] = GetProperty(SETS_DB, property);
return Status::OK();
}
uint64_t BlackWidow::GetProperty(const std::string& db_type,
const std::string& property) {
uint64_t out = 0, result = 0;
if (db_type == ALL_DB || db_type == STRINGS_DB) {
strings_db_->GetProperty(property, &out);
result += out;
}
if (db_type == ALL_DB || db_type == HASHES_DB) {
hashes_db_->GetProperty(property, &out);
result += out;
}
if (db_type == ALL_DB || db_type == LISTS_DB) {
lists_db_->GetProperty(property, &out);
result += out;
}
if (db_type == ALL_DB || db_type == ZSETS_DB) {
zsets_db_->GetProperty(property, &out);
result += out;
}
if (db_type == ALL_DB || db_type == SETS_DB) {
sets_db_->GetProperty(property, &out);
result += out;
}
return result;
}
Status BlackWidow::GetKeyNum(std::vector<KeyInfo>* key_infos) {
KeyInfo key_info;
// NOTE: keep the db order with string, hash, list, zset, set
std::vector<Redis*> dbs = {strings_db_, hashes_db_,
lists_db_, zsets_db_, sets_db_};
for (const auto& db : dbs) {
// check the scanner was stopped or not, before scanning the next db
if (scan_keynum_exit_) {
break;
}
db->ScanKeyNum(&key_info);
key_infos->push_back(key_info);
}
if (scan_keynum_exit_) {
scan_keynum_exit_ = false;
return Status::Corruption("exit");
}
return Status::OK();
}
Status BlackWidow::StopScanKeyNum() {
scan_keynum_exit_ = true;
return Status::OK();
}
rocksdb::DB* BlackWidow::GetDBByType(const std::string& type) {
if (type == STRINGS_DB) {
return strings_db_->GetDB();
} else if (type == HASHES_DB) {
return hashes_db_->GetDB();
} else if (type == LISTS_DB) {
return lists_db_->GetDB();
} else if (type == SETS_DB) {
return sets_db_->GetDB();
} else if (type == ZSETS_DB) {
return zsets_db_->GetDB();
} else {
return NULL;
}
}
} // namespace blackwidow
| 30.282922
| 107
| 0.588109
|
kxtry
|
021d1f0c93284d9dd8db0d3cef62784aec55eebb
| 5,827
|
cpp
|
C++
|
lang/steve/Syntax.cpp
|
flowgrammable/steve-legacy
|
5e7cbc16280c199732d26a2cb0703422695abe16
|
[
"Apache-2.0"
] | 1
|
2017-07-30T04:18:56.000Z
|
2017-07-30T04:18:56.000Z
|
lang/steve/Syntax.cpp
|
flowgrammable/steve-legacy
|
5e7cbc16280c199732d26a2cb0703422695abe16
|
[
"Apache-2.0"
] | null | null | null |
lang/steve/Syntax.cpp
|
flowgrammable/steve-legacy
|
5e7cbc16280c199732d26a2cb0703422695abe16
|
[
"Apache-2.0"
] | null | null | null |
#include <steve/Syntax.hpp>
#include <steve/Print.hpp>
#include <steve/Debug.hpp>
namespace steve {
void
init_trees() {
// Terms
init_node(id_tree, "id-tree");
init_node(lit_tree, "lit-tree");
init_node(brace_tree, "brace-tree");
init_node(call_tree, "call-tree");
init_node(index_tree, "index-tree");
init_node(dot_tree, "dot-tree");
init_node(range_tree, "range-tree");
init_node(app_tree, "app-tree");
init_node(unary_tree, "unary-tree");
init_node(binary_tree, "binary-tree");
init_node(if_tree, "if-tree");
// Types
init_node(record_tree, "record-tree");
init_node(variant_tree, "variant-tree");
init_node(enum_tree, "enum-tree");
// Statements
init_node(block_tree, "block-tree");
init_node(return_tree, "return-tree");
init_node(break_tree, "break-tree");
init_node(cont_tree, "cont-tree");
init_node(while_tree, "while-tree");
init_node(switch_tree, "switch-tree");
init_node(load_tree, "load-tree");
// Declarations
init_node(value_tree, "value-tree");
init_node(parm_tree, "parm-tree");
init_node(fn_tree, "fn-tree");
init_node(def_tree, "def-tree");
init_node(field_tree, "field-tree");
init_node(alt_tree, "alt-tree");
init_node(import_tree, "import-tree");
init_node(using_tree, "using-tree");
// Misc
init_node(top_tree, "top-tree");
}
// FIXME: A whole lot of this stuff is common in both Ast.cpp and
// here. In fact, it's practically verbatim. It would not be amiss
// to move much of this out to Node.cpp.
namespace {
struct sexpr {
sexpr(Printer& p, const char* n)
: printer(p)
{
print(printer, '(');
print(printer, n);
print_space(printer);
}
sexpr(Printer& p, String s)
: sexpr(p, s.data()) { }
template<typename T>
sexpr(Printer& p, T* n)
: sexpr(p, node_name(n)) { }
~sexpr() { print(printer, ')'); }
Printer& printer;
};
void debug_print(Printer&, Tree*);
void
debug_print(Printer& p, const Token* k) {
print(p, k->text);
}
struct debug_printer {
template<typename T>
void operator()(Printer& p, T t) const { debug_print(p, t); }
};
// Top-level match printing sequences-of-T.
template<typename T>
void
debug_print(Printer& p, Seq<T>* s) {
print(p, '(');
print_separated(p, s, debug_printer(), space_separator());
print(p, ')');
}
// Note that t->first is a token.
template<typename T>
inline void
debug_terminal(Printer& p, T* t) {
sexpr s(p, t);
debug_print(p, t->first);
}
template<typename T>
inline void
debug_nullary(Printer& p, T* t) { sexpr s(p, t); }
template<typename T>
inline void
debug_unary(Printer& p, T* t) {
sexpr s(p, t);
debug_print(p, t->first);
}
template<typename T>
void
debug_binary(Printer& p, T* t) {
sexpr s(p, t);
debug_print(p, t->first);
print_space(p);
debug_print(p, t->second);
}
template<typename T>
inline void
debug_ternary(Printer& p, T* t) {
sexpr s(p, t);
debug_print(p, t->first);
print_space(p);
debug_print(p, t->second);
print_space(p);
debug_print(p, t->third);
}
void
debug_unary(Printer& p, Unary_tree* t) {
sexpr s(p, t->op()->text);
debug_print(p, t->arg());
}
void
debug_binary(Printer& p, Binary_tree* t) {
sexpr s(p, t->op()->text);
debug_print(p, t->left());
print_space(p);
debug_print(p, t->right());
}
void
debug_top(Printer& p, Top_tree* t) {
sexpr s(p, t);
indent(p);
print_newline(p);
for (Tree* s : *t->first) {
print_indent(p);
debug_print(p, s);
print_newline(p);
}
undent(p);
print_indent(p);
}
void
debug_print(Printer& p, Tree* t) {
if (not t) {
print(p, "()");
return;
}
switch (t->kind) {
// Terms
case id_tree: return debug_terminal(p, as<Id_tree>(t));
case lit_tree: return debug_terminal(p, as<Lit_tree>(t));
case brace_tree: return debug_unary(p, as<Brace_tree>(t));
case call_tree: return debug_binary(p, as<Call_tree>(t));
case index_tree: return debug_binary(p, as<Index_tree>(t));
case app_tree: return debug_binary(p, as<App_tree>(t));
case dot_tree: return debug_binary(p, as<Dot_tree>(t));
case range_tree: return debug_binary(p, as<Range_tree>(t));
case unary_tree: return debug_unary(p, as<Unary_tree>(t));
case binary_tree: return debug_binary(p, as<Binary_tree>(t));
case if_tree: return debug_ternary(p, as<If_tree>(t));
// Types
case record_tree: return debug_unary(p, as<Record_tree>(t));
case variant_tree: return debug_binary(p, as<Variant_tree>(t));
case enum_tree: return debug_binary(p, as<Enum_tree>(t));
// Statements
case return_tree: return debug_unary(p, as<Return_tree>(t));
case break_tree: return debug_nullary(p, as<Break_tree>(t));
case cont_tree: return debug_nullary(p, as<Cont_tree>(t));
case while_tree: return debug_binary(p, as<While_tree>(t));
case switch_tree: return debug_binary(p, as<Switch_tree>(t));
case case_tree: return debug_binary(p, as<Case_tree>(t));
case load_tree: return debug_unary(p, as<Load_tree>(t));
// Declarations
case value_tree: return debug_binary(p, as<Value_tree>(t));
case parm_tree: return debug_ternary(p, as<Parm_tree>(t));
case fn_tree: return debug_ternary(p, as<Fn_tree>(t));
case def_tree: return debug_binary(p, as<Def_tree>(t));
case field_tree: return debug_ternary(p, as<Field_tree>(t));
case alt_tree: return debug_binary(p, as<Alt_tree>(t));
case import_tree: return debug_unary(p, as<Import_tree>(t));
case using_tree: return debug_unary(p, as<Using_tree>(t));
// Misc
case top_tree: return debug_top(p, as<Top_tree>(t));
// Unhandled
default:
steve_unreachable("unhandled parse tree");
}
}
} // namespace
std::ostream&
operator<<(std::ostream& os, debug_tree d) {
Printer p(os);
debug_print(p, d.e);
return os;
}
} // namespace steve
| 26.130045
| 66
| 0.665866
|
flowgrammable
|
0223e335169af73587acf33e192b13720d7cf256
| 4,795
|
hpp
|
C++
|
libs/iostreams/test/write_bidir_filter_test.hpp
|
zyiacas/boost-doc-zh
|
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
|
[
"BSL-1.0"
] | 198
|
2015-01-13T05:47:18.000Z
|
2022-03-09T04:46:46.000Z
|
libs/iostreams/test/write_bidir_filter_test.hpp
|
sdfict/boost-doc-zh
|
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
|
[
"BSL-1.0"
] | 9
|
2015-01-28T16:33:19.000Z
|
2020-04-12T23:03:28.000Z
|
libs/iostreams/test/write_bidir_filter_test.hpp
|
sdfict/boost-doc-zh
|
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
|
[
"BSL-1.0"
] | 139
|
2015-01-15T20:09:31.000Z
|
2022-01-31T15:21:16.000Z
|
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_TEST_WRITE_INOUT_FILTER_HPP_INCLUDED
#define BOOST_IOSTREAMS_TEST_WRITE_INOUT_FILTER_HPP_INCLUDED
#include <fstream>
#include <boost/iostreams/combine.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/test/test_tools.hpp>
#include "detail/filters.hpp"
#include "detail/sequence.hpp"
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"
void write_bidirectional_filter_test()
{
using namespace std;
using namespace boost;
using namespace boost::iostreams;
using namespace boost::iostreams::test;
lowercase_file lower;
BOOST_IOS::openmode mode = out_mode | BOOST_IOS::trunc;
{
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
dest.open(lower2.name().c_str(), mode);
out.push(combine(toupper_filter(), tolower_filter()));
out.push(dest);
write_data_in_chars(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chars with an "
"output filter"
);
}
{
// OutputFilter.
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
out.push(combine(toupper_filter(), tolower_filter()));
dest.open(lower2.name().c_str(), mode);
out.push(dest);
write_data_in_chunks(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chunks with an "
"output filter"
);
}
{
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
out.push(combine(toupper_filter(), tolower_multichar_filter()), 0);
dest.open(lower2.name().c_str(), mode);
out.push(dest);
write_data_in_chars(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chars "
"with a multichar output filter with no buffer"
);
}
{
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
out.push(combine(toupper_filter(), tolower_multichar_filter()), 0);
dest.open(lower2.name().c_str(), mode);
out.push(dest);
write_data_in_chunks(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chunks "
"with a multichar output filter with no buffer"
);
}
{
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
out.push(combine(toupper_filter(), tolower_multichar_filter()));
dest.open(lower2.name().c_str(), mode);
out.push(dest);
write_data_in_chars(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chars "
"with a multichar output filter"
);
}
{
temp_file lower2;
filebuf dest;
filtering_stream<bidirectional> out;
out.push(combine(toupper_filter(), tolower_multichar_filter()));
dest.open(lower2.name().c_str(), mode);
out.push(dest);
write_data_in_chunks(out);
out.reset();
dest.close();
BOOST_CHECK_MESSAGE(
compare_files(lower2.name(), lower.name()),
"failed writing to a filtering_stream<bidirectional> in chunks "
"with a buffered output filter"
);
}
}
#endif // #ifndef BOOST_IOSTREAMS_TEST_WRITE_BIDIRECTIONAL_FILTER_HPP_INCLUDED
| 35.518519
| 85
| 0.572471
|
zyiacas
|
0227bf12c90e0a56a4e0729185a2f700f4eab792
| 21,446
|
cpp
|
C++
|
test/queuemanager.cpp
|
bogdasar1985/newsboat
|
3ccc76b45ea86116d25a3dd7602a95350f878c77
|
[
"MIT"
] | null | null | null |
test/queuemanager.cpp
|
bogdasar1985/newsboat
|
3ccc76b45ea86116d25a3dd7602a95350f878c77
|
[
"MIT"
] | null | null | null |
test/queuemanager.cpp
|
bogdasar1985/newsboat
|
3ccc76b45ea86116d25a3dd7602a95350f878c77
|
[
"MIT"
] | null | null | null |
#include "queuemanager.h"
#include "3rd-party/catch.hpp"
#include "test_helpers/chmod.h"
#include "test_helpers/envvar.h"
#include "test_helpers/misc.h"
#include "test_helpers/tempfile.h"
#include "cache.h"
#include "configcontainer.h"
#include "rssfeed.h"
#include "rssitem.h"
#include "utils.h"
using namespace newsboat;
SCENARIO("Smoke test for QueueManager", "[QueueManager]")
{
GIVEN("A fresh instance of QueueManager") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto item = std::make_shared<RssItem>(&cache);
const std::string enclosure_url("https://example.com/podcast.mp3");
item->set_enclosure_url(enclosure_url);
item->set_enclosure_type("audio/mpeg");
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
THEN("the queue file is not automatically created") {
REQUIRE_FALSE(test_helpers::file_exists(queue_file.get_path()));
}
WHEN("enqueue_url() is called") {
const auto result = manager.enqueue_url(item, feed);
THEN("the return value indicates success") {
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
}
THEN("the queue file contains an entry") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(test_helpers::starts_with(enclosure_url, lines[0]));
REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0]));
REQUIRE(lines[1] == "");
}
THEN("the item is marked as enqueued") {
REQUIRE(item->enqueued());
}
}
WHEN("enqueue_url() is called on the same item twice in a row") {
manager.enqueue_url(item, feed);
const auto result = manager.enqueue_url(item, feed);
THEN("the second call indicates that the enclosure is already in the queue") {
REQUIRE(result.status == EnqueueStatus::URL_QUEUED_ALREADY);
REQUIRE(result.extra_info == enclosure_url);
}
THEN("the queue file contains a single entry") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(test_helpers::starts_with(enclosure_url, lines[0]));
REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0]));
REQUIRE(lines[1] == "");
}
THEN("the item is marked as enqueued") {
REQUIRE(item->enqueued());
}
}
WHEN("enqueue_url() is called for multiple different items") {
const auto result = manager.enqueue_url(item, feed);
auto item2 = std::make_shared<RssItem>(&cache);
item2->set_enclosure_url("https://www.example.com/another.mp3");
item2->set_enclosure_type("audio/mpeg");
const auto result2 = manager.enqueue_url(item2, feed);
auto item3 = std::make_shared<RssItem>(&cache);
item3->set_enclosure_url("https://joe.example.com/vacation.jpg");
item3->set_enclosure_type("image/jpeg");
const auto result3 = manager.enqueue_url(item3, feed);
THEN("return values indicate success") {
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
REQUIRE(result2.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result2.extra_info == "");
REQUIRE(result3.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result3.extra_info == "");
}
THEN("the queue file contains three entries") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 4);
REQUIRE(lines[0] != "");
REQUIRE(lines[1] != "");
REQUIRE(lines[2] != "");
REQUIRE(lines[3] == "");
}
THEN("items are marked as enqueued") {
REQUIRE(item->enqueued());
REQUIRE(item2->enqueued());
REQUIRE(item3->enqueued());
}
}
}
}
SCENARIO("enqueue_url() errors if the filename is already used", "[QueueManager]")
{
GIVEN("Pristine QueueManager and two RssItems") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto item1 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url1("https://example.com/podcast.mp3");
item1->set_enclosure_url(enclosure_url1);
item1->set_enclosure_type("audio/mpeg");
auto item2 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url2("https://example.com/~joe/podcast.mp3");
item2->set_enclosure_url(enclosure_url2);
item2->set_enclosure_type("audio/mpeg");
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
WHEN("first item is enqueued") {
const auto result = manager.enqueue_url(item1, feed);
THEN("the return value indicates success") {
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
}
THEN("the queue file contains a corresponding entry") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0]));
REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0]));
REQUIRE(lines[1] == "");
}
THEN("the item is marked as enqueued") {
REQUIRE(item1->enqueued());
}
AND_WHEN("second item is enqueued") {
const auto result = manager.enqueue_url(item2, feed);
THEN("the return value indicates that the filename is already used") {
REQUIRE(result.status == EnqueueStatus::OUTPUT_FILENAME_USED_ALREADY);
// That field contains a path to the temporary directory,
// so we simply check that it's not empty.
REQUIRE(result.extra_info != "");
}
THEN("the queue file still contains a single entry") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0]));
REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0]));
REQUIRE(lines[1] == "");
}
THEN("the item is NOT marked as enqueued") {
REQUIRE_FALSE(item2->enqueued());
}
}
}
}
}
SCENARIO("enqueue_url() errors if the queue file can't be opened for writing",
"[QueueManager]")
{
GIVEN("Pristine QueueManager, an RssItem, and an uneditable queue file") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto item = std::make_shared<RssItem>(&cache);
item->set_enclosure_url("https://example.com/podcast.mp3");
item->set_enclosure_type("audio/mpeg");
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
test_helpers::copy_file("data/empty-file", queue_file.get_path());
// The file is read-only
test_helpers::Chmod uneditable_queue_file(queue_file.get_path(), 0444);
WHEN("enqueue_url() is called") {
const auto result = manager.enqueue_url(item, feed);
THEN("the return value indicates the file couldn't be written to") {
REQUIRE(result.status == EnqueueStatus::QUEUE_FILE_OPEN_ERROR);
REQUIRE(result.extra_info == queue_file.get_path());
}
THEN("the item is NOT marked as enqueued") {
REQUIRE_FALSE(item->enqueued());
}
}
}
}
TEST_CASE("QueueManager puts files into a location configured by `download-path`",
"[QueueManager]")
{
ConfigContainer cfg;
SECTION("path with a slash at the end") {
cfg.set_configvalue("download-path", "/tmp/nonexistent-newsboat/");
}
SECTION("path without a slash at the end") {
cfg.set_configvalue("download-path", "/tmp/nonexistent-newsboat");
}
Cache cache(":memory:", &cfg);
auto item1 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url1("https://example.com/podcast.mp3");
item1->set_enclosure_url(enclosure_url1);
item1->set_enclosure_type("audio/mpeg");
auto item2 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url2("https://example.com/~joe/podcast.ogg");
item2->set_enclosure_url(enclosure_url2);
item2->set_enclosure_type("audio/vorbis");
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom");
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
const auto result1 = manager.enqueue_url(item1, feed);
REQUIRE(result1.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result1.extra_info == "");
REQUIRE(item1->enqueued());
const auto result2 = manager.enqueue_url(item2, feed);
REQUIRE(result2.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result2.extra_info == "");
REQUIRE(item2->enqueued());
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 3);
REQUIRE(lines[0] ==
R"(https://example.com/podcast.mp3 "/tmp/nonexistent-newsboat/podcast.mp3")");
REQUIRE(lines[1] ==
R"(https://example.com/~joe/podcast.ogg "/tmp/nonexistent-newsboat/podcast.ogg")");
REQUIRE(lines[2] == "");
}
TEST_CASE("QueueManager names files according to the `download-filename-format` setting",
"[QueueManager]")
{
ConfigContainer cfg;
// We set the download-path to a fixed value to ensure that we know
// *exactly* how the result should look.
cfg.set_configvalue("download-path", "/example/");
Cache cache(":memory:", &cfg);
auto item = std::make_shared<RssItem>(&cache);
item->set_enclosure_url("https://example.com/~adam/podcast.mp3");
item->set_enclosure_type("audio/mpeg");
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom");
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
SECTION("%n for current feed title, with slashes replaced by underscores") {
cfg.set_configvalue("download-filename-format", "%n");
feed->set_title("Feed title/theme");
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/Feed title_theme")");
REQUIRE(lines[1] == "");
}
SECTION("%h for the enclosure URL's hostname") {
cfg.set_configvalue("download-filename-format", "%h");
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/example.com")");
REQUIRE(lines[1] == "");
}
SECTION("%u for the enclosure URL's basename") {
cfg.set_configvalue("download-filename-format", "%u");
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/podcast.mp3")");
REQUIRE(lines[1] == "");
}
SECTION("%F, %m, %b, %d, %H, %M, %S, %y, and %Y to render items's publication date with strftime") {
// %H is sensitive to the timezone, so reset it to UTC for a time being
test_helpers::TzEnvVar tzEnv;
tzEnv.set("UTC");
cfg.set_configvalue("download-filename-format", "%F, %m, %b, %d, %H, %M, %S, %y, and %Y");
// Tue, 06 Apr 2021 15:38:19 +0000
item->set_pubDate(1617723499);
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/2021-04-06, 04, Apr, 06, 15, 38, 19, 21, and 2021")");
REQUIRE(lines[1] == "");
}
SECTION("%t for item title, with slashes replaced by underscores") {
cfg.set_configvalue("download-filename-format", "%t");
item->set_title("Rain/snow/sun in a single day");
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/Rain_snow_sun in a single day")");
REQUIRE(lines[1] == "");
}
SECTION("%e for enclosure's filename extension") {
cfg.set_configvalue("download-filename-format", "%e");
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/mp3")");
REQUIRE(lines[1] == "");
}
SECTION("%N for the feed's title (even if `feed` passed into a function is different)") {
cfg.set_configvalue("download-filename-format", "%N");
SECTION("`feed` argument is irrelevant") {
feed->set_title("Relevant feed");
item->set_feedptr(feed);
auto irrelevant_feed = std::make_shared<RssFeed>(&cache,
"https://example.com/podcasts.atom");
irrelevant_feed->set_title("Irrelevant");
manager.enqueue_url(item, irrelevant_feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/Relevant feed")");
REQUIRE(lines[1] == "");
}
SECTION("`feed` argument is relevant") {
feed->set_title("Relevant feed");
item->set_feedptr(feed);
manager.enqueue_url(item, feed);
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(lines[0] ==
R"(https://example.com/~adam/podcast.mp3 "/example/Relevant feed")");
REQUIRE(lines[1] == "");
}
}
}
TEST_CASE("autoenqueue() adds all enclosures of all items to the queue", "[QueueManager]")
{
GIVEN("Pristine QueueManager and a feed of three items") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom");
auto item1 = std::make_shared<RssItem>(&cache);
item1->set_enclosure_url("https://example.com/~adam/podcast.mp3");
item1->set_enclosure_type("audio/mpeg");
feed->add_item(item1);
auto item2 = std::make_shared<RssItem>(&cache);
item2->set_enclosure_url("https://example.com/episode.ogg");
item2->set_enclosure_type("audio/vorbis");
feed->add_item(item2);
auto item3 = std::make_shared<RssItem>(&cache);
item3->set_enclosure_url("https://example.com/~fae/painting.jpg");
item3->set_enclosure_type("image/jpeg");
feed->add_item(item3);
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
WHEN("autoenqueue() is called") {
const auto result = manager.autoenqueue(feed);
THEN("the return value indicates success") {
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
}
THEN("the queue file contains three entries") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 4);
REQUIRE(lines[0] != "");
REQUIRE(lines[1] != "");
REQUIRE(lines[2] != "");
REQUIRE(lines[3] == "");
}
THEN("items are marked as enqueued") {
REQUIRE(item1->enqueued());
REQUIRE(item2->enqueued());
REQUIRE(item3->enqueued());
}
}
}
}
SCENARIO("autoenqueue() errors if the filename is already used", "[QueueManager]")
{
GIVEN("Pristine QueueManager and a feed of two items") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
auto item1 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url1("https://example.com/podcast.mp3");
item1->set_enclosure_url(enclosure_url1);
item1->set_enclosure_type("audio/mpeg");
feed->add_item(item1);
auto item2 = std::make_shared<RssItem>(&cache);
const std::string enclosure_url2("https://example.com/~joe/podcast.mp3");
item2->set_enclosure_url(enclosure_url2);
item2->set_enclosure_type("audio/mpeg");
feed->add_item(item2);
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
WHEN("autoenqueue() is called") {
const auto result = manager.autoenqueue(feed);
THEN("the return value indicates that the filename is already used") {
REQUIRE(result.status == EnqueueStatus::OUTPUT_FILENAME_USED_ALREADY);
// That field contains a path to the temporary directory,
// so we simply check that it's not empty.
REQUIRE(result.extra_info != "");
}
THEN("the queue file still contains a single entry") {
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 2);
REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0]));
REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0]));
REQUIRE(lines[1] == "");
}
THEN("the first item is enqueued, the second one isn't") {
REQUIRE(item1->enqueued());
REQUIRE_FALSE(item2->enqueued());
}
}
}
}
SCENARIO("autoenqueue() errors if the queue file can't be opened for writing",
"[QueueManager]")
{
GIVEN("Pristine QueueManager, a single-item feed, and an uneditable queue file") {
ConfigContainer cfg;
Cache cache(":memory:", &cfg);
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
auto item = std::make_shared<RssItem>(&cache);
item->set_enclosure_url("https://example.com/podcast.mp3");
item->set_enclosure_type("audio/mpeg");
feed->add_item(item);
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
test_helpers::copy_file("data/empty-file", queue_file.get_path());
// The file is read-only
test_helpers::Chmod uneditable_queue_file(queue_file.get_path(), 0444);
WHEN("autoenqueue() is called") {
const auto result = manager.autoenqueue(feed);
THEN("the return value indicates the file couldn't be written to") {
REQUIRE(result.status == EnqueueStatus::QUEUE_FILE_OPEN_ERROR);
REQUIRE(result.extra_info == queue_file.get_path());
}
THEN("the item is NOT marked as enqueued") {
REQUIRE_FALSE(item->enqueued());
}
}
}
}
TEST_CASE("autoenqueue() skips already-enqueued items", "[QueueManager]")
{
ConfigContainer cfg;
// We set the download-path to a fixed value to ensure that we know
// *exactly* how the result should look.
cfg.set_configvalue("download-path", "/example/");
Cache cache(":memory:", &cfg);
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
auto item1 = std::make_shared<RssItem>(&cache);
item1->set_enclosure_url("https://example.com/podcast.mp3");
item1->set_enclosure_type("audio/mpeg");
feed->add_item(item1);
auto item2 = std::make_shared<RssItem>(&cache);
item2->set_enclosure_url("https://example.com/podcast2.mp3");
item2->set_enclosure_type("audio/mpeg");
item2->set_enqueued(true);
feed->add_item(item2);
auto item3 = std::make_shared<RssItem>(&cache);
item3->set_enclosure_url("https://example.com/podcast3.mp3");
item3->set_enclosure_type("audio/mpeg");
feed->add_item(item3);
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
const auto result = manager.autoenqueue(feed);
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 3);
REQUIRE(lines[0] == R"(https://example.com/podcast.mp3 "/example/podcast.mp3")");
REQUIRE(lines[1] == R"(https://example.com/podcast3.mp3 "/example/podcast3.mp3")");
REQUIRE(lines[2] == "");
}
TEST_CASE("autoenqueue() only enqueues HTTP and HTTPS URLs", "[QueueManager]")
{
ConfigContainer cfg;
// We set the download-path to a fixed value to ensure that we know
// *exactly* how the result should look.
cfg.set_configvalue("download-path", "/example/");
Cache cache(":memory:", &cfg);
auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom");
auto item1 = std::make_shared<RssItem>(&cache);
item1->set_enclosure_url("https://example.com/podcast.mp3");
item1->set_enclosure_type("audio/mpeg");
feed->add_item(item1);
auto item2 = std::make_shared<RssItem>(&cache);
item2->set_enclosure_url("http://example.com/podcast2.mp3");
item2->set_enclosure_type("audio/mpeg");
feed->add_item(item2);
auto item3 = std::make_shared<RssItem>(&cache);
item3->set_enclosure_url("ftp://user@example.com/podcast3.mp3");
item3->set_enclosure_type("audio/mpeg");
feed->add_item(item3);
test_helpers::TempFile queue_file;
QueueManager manager(&cfg, queue_file.get_path());
const auto result = manager.autoenqueue(feed);
REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY);
REQUIRE(result.extra_info == "");
REQUIRE(test_helpers::file_exists(queue_file.get_path()));
const auto lines = test_helpers::file_contents(queue_file.get_path());
REQUIRE(lines.size() == 3);
REQUIRE(lines[0] == R"(https://example.com/podcast.mp3 "/example/podcast.mp3")");
REQUIRE(lines[1] == R"(http://example.com/podcast2.mp3 "/example/podcast2.mp3")");
REQUIRE(lines[2] == "");
}
| 32.741985
| 108
| 0.698126
|
bogdasar1985
|
022e8cdc7fd979350a932c73f852b0e1b194b98d
| 5,516
|
cpp
|
C++
|
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
|
gurylev-nikita/devtools-course-practice
|
bab6ba4e39f04940e27c9ac148505eb152c05d17
|
[
"CC-BY-4.0"
] | null | null | null |
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
|
gurylev-nikita/devtools-course-practice
|
bab6ba4e39f04940e27c9ac148505eb152c05d17
|
[
"CC-BY-4.0"
] | 3
|
2021-04-22T17:12:19.000Z
|
2021-05-14T12:16:25.000Z
|
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
|
taktaev-artyom/devtools-course-practice
|
7cf19defe061c07cfb3ebb71579456e807430a5d
|
[
"CC-BY-4.0"
] | null | null | null |
// Copyright 2021 Yurin Stanislav
#include <gtest/gtest.h>
#include <tuple>
#include "include/fraction.h"
typedef testing::TestWithParam<int>
Can_create_one_parametres_constructor;
TEST_P(Can_create_one_parametres_constructor, can_create_constructor) {
int n = GetParam();
Fraction f(n);
ASSERT_EQ(n, f.getNumerator());
}
INSTANTIATE_TEST_CASE_P(, Can_create_one_parametres_constructor,
testing::Values(3, 29)
);
typedef testing::TestWithParam<std::tuple<int, int>>
Can_create_two_parametres_constructor;
TEST_P(Can_create_two_parametres_constructor, can_create_constructor) {
int n = std::get<0>(GetParam());
int d = std::get<1>(GetParam());
Fraction f(n, d);
ASSERT_EQ(d, f.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, Can_create_two_parametres_constructor,
testing::Values(std::make_tuple(2, 3), std::make_tuple(43, 99))
);
TEST(Fraction, throws_on_zero_denominator) {
ASSERT_ANY_THROW(Fraction f(29, 0));
}
TEST(Fraction, default_fraction_creating) {
Fraction f;
ASSERT_EQ(0, f.getNumerator());
ASSERT_EQ(1, f.getDenominator());
}
TEST(Fraction, fraction_with_negative_parametres_becomes_positive) {
Fraction f(-1, -2);
ASSERT_EQ(1, f.getNumerator());
ASSERT_EQ(2, f.getDenominator());
}
TEST(Fraction, moves_minus_to_numerator) {
Fraction f(1, -2);
ASSERT_EQ(-1, f.getNumerator());
ASSERT_EQ(2, f.getDenominator());
}
typedef testing::TestWithParam<std::tuple<int, int, int, int>>
Reduction_par;
TEST_P(Reduction_par, reduction) {
int n = std::get<0>(GetParam());
int d = std::get<1>(GetParam());
Fraction f(n, d);
ASSERT_EQ(std::get<2>(GetParam()), f.getNumerator());
ASSERT_EQ(std::get<3>(GetParam()), f.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, Reduction_par,
testing::Values(std::make_tuple(3, 6, 1, 2),
std::make_tuple(8, -32, -1, 4))
);
typedef testing::TestWithParam<std::tuple<int, int, int>>
gcd_par;
TEST_P(gcd_par, ) {
Fraction f;
ASSERT_EQ(std::get<0>(GetParam()),
f.gcd(std::get<1>(GetParam()),
std::get<2>(GetParam())));
}
INSTANTIATE_TEST_CASE_P(, gcd_par,
testing::Values(std::make_tuple(3, 3, 6),
std::make_tuple(6, 18, 30))
);
TEST(Fraction, gcd_negative_parameter) {
Fraction f;
ASSERT_ANY_THROW(f.gcd(-18, 30));
}
typedef testing::TestWithParam<std::tuple<int, int, int>>
lcm_par;
TEST_P(lcm_par, ) {
Fraction f;
ASSERT_EQ(std::get<0>(GetParam()),
f.lcm(std::get<1>(GetParam()),
std::get<2>(GetParam())));
}
INSTANTIATE_TEST_CASE_P(, lcm_par,
testing::Values(std::make_tuple(36, 12, 18),
std::make_tuple(15, 15, 3))
);
TEST(Fraction, lcm_negative_parameter) {
Fraction f;
ASSERT_ANY_THROW(f.lcm(-12, 18));
}
TEST(Fraction, can_self_appropriation) {
Fraction f(2, 3);
f = f;
ASSERT_EQ(2, f.getNumerator());
ASSERT_EQ(3, f.getDenominator());
}
TEST(Fraction, comparison_operator_overloading) {
Fraction f1(2, 3);
Fraction f2;
f2 = f1;
ASSERT_EQ(2, f2.getNumerator());
ASSERT_EQ(3, f2.getDenominator());
}
typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>>
plus_par;
TEST_P(plus_par, ) {
Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam()));
Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam()));
Fraction f3;
f3 = f1 + f2;
ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator());
ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, plus_par,
testing::Values(std::make_tuple(2, 3, 3, 4, 17, 12),
std::make_tuple(-3, 5, 4, 7, -1, 35))
);
typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>>
minus_par;
TEST_P(minus_par, ) {
Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam()));
Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam()));
Fraction f3;
f3 = f1 - f2;
ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator());
ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, minus_par,
testing::Values(std::make_tuple(2, 5, 4, 3, -14, 15),
std::make_tuple(3, 8, 11, -5, 103, 40))
);
typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>>
multi_par;
TEST_P(multi_par, ) {
Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam()));
Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam()));
Fraction f3;
f3 = f1 * f2;
ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator());
ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, multi_par,
testing::Values(std::make_tuple(3, 2, 8, 11, 12, 11),
std::make_tuple(7, -4, -9, 3, 21, 4))
);
typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>>
dev_par;
TEST_P(dev_par, ) {
Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam()));
Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam()));
Fraction f3;
f3 = f1 / f2;
ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator());
ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator());
}
INSTANTIATE_TEST_CASE_P(, dev_par,
testing::Values(std::make_tuple(13, 11, 4, 5, 65, 44),
std::make_tuple(14, -6, -15, -2, -14, 45))
);
| 24.959276
| 72
| 0.624184
|
gurylev-nikita
|
023db6b22b9a28d346cbb2f1953bc3307b8e2a74
| 624
|
hpp
|
C++
|
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
|
simRepoRelease/raisimLib
|
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
|
[
"Apache-2.0"
] | 142
|
2020-10-21T18:18:13.000Z
|
2022-03-29T11:49:25.000Z
|
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
|
simRepoRelease/raisimLib
|
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
|
[
"Apache-2.0"
] | 192
|
2020-10-21T15:51:15.000Z
|
2022-03-28T12:56:01.000Z
|
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
|
simRepoRelease/raisimLib
|
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
|
[
"Apache-2.0"
] | 51
|
2020-10-26T08:29:54.000Z
|
2022-03-23T12:00:23.000Z
|
//----------------------------//
// This file is part of RaiSim//
// Copyright 2020, RaiSim Tech//
//----------------------------//
#ifndef RAISIM_STIFFWIRE_HPP
#define RAISIM_STIFFWIRE_HPP
#include "LengthConstraint.hpp"
namespace raisim {
class StiffLengthConstraint : public LengthConstraint {
public:
StiffLengthConstraint(Object* obj1, size_t localIdx1, Vec<3> pos1_b, Object* obj2, size_t localIdx2, Vec<3> pos2_b, double length);
virtual ~StiffLengthConstraint() = default;
protected:
void applyTension(contact::ContactProblems& contact_problems) final;
private:
};
}
#endif //RAISIM_STIFFWIRE_HPP
| 21.517241
| 133
| 0.689103
|
simRepoRelease
|
023f04b5d143edd11c52d56b5ab6e1297a7fe7ba
| 6,666
|
cpp
|
C++
|
src/transaction/transactors/SetREL.cpp
|
hawx1993/truechain-testnet-core
|
a75edfe83562b3764fb3140144bc41943ebb995a
|
[
"MIT"
] | null | null | null |
src/transaction/transactors/SetREL.cpp
|
hawx1993/truechain-testnet-core
|
a75edfe83562b3764fb3140144bc41943ebb995a
|
[
"MIT"
] | null | null | null |
src/transaction/transactors/SetREL.cpp
|
hawx1993/truechain-testnet-core
|
a75edfe83562b3764fb3140144bc41943ebb995a
|
[
"MIT"
] | null | null | null |
//------------------------------------------------------------------------------
/*
Copyright (c) 2012, 2013 Skywell Labs Inc.
Copyright (c) 2017-2018 TrueChain Foundation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <transaction/book/Quality.h>
#include <transaction/transactors/Transactor.h>
#include <common/base/Log.h>
#include <protocol/Indexes.h>
#include <protocol/TxFlags.h>
namespace truechain {
class SetREL
: public Transactor
{
public:
SetREL (
STTx const& txn,
TransactionEngineParams params,
TransactionEngine* engine)
: Transactor (
txn,
params,
engine,
deprecatedLogs().journal("SetREL"))
{
}
TER preCheck () override
{
std::uint32_t const uTxFlags = mTxn.getFlags ();
if (uTxFlags & tfRelationSetMask)
{
m_journal.trace <<
"Malformed transaction: Invalid flags set.";
return temINVALID_FLAG;
}
STAmount const saLimitAmount (mTxn.getFieldAmount (sfLimitAmount));
if (!isLegalNet (saLimitAmount))
return temBAD_AMOUNT;
if (saLimitAmount.isNative ())
{
if (m_journal.trace) m_journal.trace <<
"Malformed transaction: specifies native limit " <<
saLimitAmount.getFullText ();
return temBAD_LIMIT;
}
if (badCurrency() == saLimitAmount.getCurrency ())
{
if (m_journal.trace) m_journal.trace <<
"Malformed transaction: specifies SWT as IOU";
return temBAD_CURRENCY;
}
if (saLimitAmount < zero)
{
if (m_journal.trace) m_journal.trace <<
"Malformed transaction: Negative credit limit.";
return temBAD_LIMIT;
}
// Check if destination makes sense.
auto const& issuer = saLimitAmount.getIssuer ();
if (!issuer || issuer == noAccount())
{
if (m_journal.trace) m_journal.trace <<
"Malformed transaction: no destination account.";
return temDST_NEEDED;
}
return Transactor::preCheck ();
}
TER doApply () override
{
TER terResult = tesSUCCESS;
std::uint32_t const uRelationType = mTxn.getFieldU32 (sfRelationType);
STAmount const saLimitAmount (mTxn.getFieldAmount (sfLimitAmount));
bool const bQualityIn (mTxn.isFieldPresent (sfQualityIn));
bool const bQualityOut (mTxn.isFieldPresent (sfQualityOut));
Currency const currency (saLimitAmount.getCurrency ());
Account uIssuerID (saLimitAmount.getIssuer ());
Account uDstAccountID (mTxn.getFieldAccount160 (sfTarget));
// true, iff current is high account.
bool const bHigh = mTxnAccountID > uDstAccountID;
std::uint32_t uQualityIn (bQualityIn ? mTxn.getFieldU32 (sfQualityIn) : 0);
std::uint32_t uQualityOut (bQualityOut ? mTxn.getFieldU32 (sfQualityOut) : 0);
if (bQualityOut && QUALITY_ONE == uQualityOut)
uQualityOut = 0;
SLE::pointer sleDst (mEngine->view().entryCache (
ltACCOUNT_ROOT, getAccountRootIndex (uDstAccountID)));
if (!sleDst)
{
m_journal.trace <<
"Delay transaction: Destination account does not exist.";
return tecNO_DST;
}
STAmount saLimitAllow = saLimitAmount;
saLimitAllow.setIssuer (mTxnAccountID);
SLE::pointer sleSkywellState (mEngine->view().entryCache (ltTrust_STATE,
getTrustStateIndex (mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency)));
if (mTxn.getTxnType () == ttREL_DEL && sleSkywellState)
{
return mEngine->view ().trustDelete (
sleSkywellState, mTxnAccountID, uDstAccountID);
}
if (!sleSkywellState && mTxn.getTxnType () == ttREL_SET)
{
// Zero balance in currency.
// STAmount saBalance ({currency, noAccount()});
STAmount saBalance ({currency, uIssuerID});
uint256 index (getTrustStateIndex (
mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency));
m_journal.trace <<
"doRelationSet: Creating rep line: " <<
to_string (index);
// Create a new skywell line.
terResult = mEngine->view ().relationCreate (
bHigh,
mTxnAccountID,
uDstAccountID,
index,
mTxnAccount,
saBalance,
saLimitAllow, // Limit for who is being charged.
uQualityIn,
uQualityOut);
if(terResult == tesSUCCESS)
{
SLE::pointer sleSkywellState (mEngine->view().entryCache (ltTrust_STATE,
getTrustStateIndex (mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency)));
sleSkywellState->setFieldU32 (sfRelationType, uRelationType);
mEngine->view().entryModify (sleSkywellState);
}
}
else if(sleSkywellState && mTxn.getTxnType () == ttREL_SET)
{
//
// Limits
//
sleSkywellState->setFieldAmount (!bHigh ? sfLowLimit : sfHighLimit, saLimitAllow);
mEngine->view().entryModify (sleSkywellState);
m_journal.trace << "Modify trust line";
}
return terResult;
}
};
TER
transact_SetREL (
STTx const& txn,
TransactionEngineParams params,
TransactionEngine* engine)
{
return SetREL (txn, params, engine).apply ();
}
}
| 33.33
| 100
| 0.581458
|
hawx1993
|
02453a9c5f55e1e5df7a191a9c251533ef2e9fb6
| 6,259
|
cpp
|
C++
|
KRender/Internal/KConstantDefinition.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | 13
|
2019-10-19T17:41:19.000Z
|
2021-11-04T18:50:03.000Z
|
KRender/Internal/KConstantDefinition.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | 3
|
2019-12-09T06:22:43.000Z
|
2020-05-28T09:33:44.000Z
|
KRender/Internal/KConstantDefinition.cpp
|
King19931229/KApp
|
f7f855b209348f835de9e5f57844d4fb6491b0a1
|
[
"MIT"
] | null | null | null |
#include "KConstantDefinition.h"
namespace KConstantDefinition
{
static ConstantBufferDetail CAMERA_DETAILS;
static ConstantBufferDetail SHADOW_DETAILS;
static ConstantBufferDetail CASCADED_SHADOW_DETAILS;
static ConstantBufferDetail GLOBAL_DETAILS;
static ConstantBufferDetail VOXEL_DETAILS;
static ConstantBufferDetail EMPYT_DETAILS;
void SafeInit()
{
static bool CONSTANT_DETAIL_INIT = false;
if(!CONSTANT_DETAIL_INIT)
{
// CAMERA
{
// VIEW
{
ConstantSemanticDetail DETAIL = { CS_VIEW, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW), MEMBER_OFFSET(CAMERA, VIEW) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// PROJ
{
ConstantSemanticDetail DETAIL = { CS_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PROJ), MEMBER_OFFSET(CAMERA, PROJ) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// VIEW_INV
{
ConstantSemanticDetail DETAIL = { CS_VIEW_INV, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW_INV), MEMBER_OFFSET(CAMERA, VIEW_INV) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// PROJ_INV
{
ConstantSemanticDetail DETAIL = { CS_PROJ_INV, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PROJ_INV), MEMBER_OFFSET(CAMERA, PROJ_INV) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// VIEW_PROJ
{
ConstantSemanticDetail DETAIL = { CS_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW_PROJ), MEMBER_OFFSET(CAMERA, VIEW_PROJ) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// PREV_VIEW_PROJ
{
ConstantSemanticDetail DETAIL = { CS_PREV_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PREV_VIEW_PROJ), MEMBER_OFFSET(CAMERA, PREV_VIEW_PROJ) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
// PARAMETERS
{
ConstantSemanticDetail DETAIL = { CS_CAMERA_PARAMETERS, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(CAMERA, PARAMETERS), MEMBER_OFFSET(CAMERA, PARAMETERS) };
CAMERA_DETAILS.semanticDetails.push_back(DETAIL);
}
CAMERA_DETAILS.bufferSize = sizeof(CAMERA);
}
// SHADOW
{
// LIGHT_VIEW
{
ConstantSemanticDetail DETAIL = { CS_SHADOW_VIEW, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(SHADOW, LIGHT_VIEW), MEMBER_OFFSET(SHADOW, LIGHT_VIEW) };
SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// LIGHT_PROJ
{
ConstantSemanticDetail DETAIL = { CS_SHADOW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(SHADOW, LIGHT_PROJ), MEMBER_OFFSET(SHADOW, LIGHT_PROJ) };
SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// CAM_NEAR_FAR
{
ConstantSemanticDetail DETAIL = { CS_SHADOW_CAMERA_PARAMETERS, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(SHADOW, PARAMETERS), MEMBER_OFFSET(SHADOW, PARAMETERS) };
SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
SHADOW_DETAILS.bufferSize = sizeof(SHADOW);
}
// CASCADED_SHADOW_DETAILS
{
// LIGHT_VIEW
{
ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_VIEW, EF_R32G32B32A32_FLOAT, 4 * 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_VIEW), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_VIEW) };
CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// LIGHT_VIEW_PROJ
{
ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4 * 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_VIEW_PROJ), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_VIEW_PROJ) };
CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// LIGHT_INFO
{
ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_LIGHT_INFO, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_INFO), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_INFO) };
CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// FRUSTUM
{
ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_FRUSTUM, EF_R32_FLOAT, 4, MEMBER_SIZE(CASCADED_SHADOW, FRUSTUM), MEMBER_OFFSET(CASCADED_SHADOW, FRUSTUM) };
CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
// NUM_CASCADED
{
ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_NUM_CASCADED, EF_R32_UINT, 1, MEMBER_SIZE(CASCADED_SHADOW, NUM_CASCADED), MEMBER_OFFSET(CASCADED_SHADOW, NUM_CASCADED) };
CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL);
}
CASCADED_SHADOW_DETAILS.bufferSize = sizeof(CASCADED_SHADOW);
}
// VOXEL_DETAILS
{
// VIEW_PROJ
{
ConstantSemanticDetail DETAIL = { CS_VOXEL_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4 * 3, MEMBER_SIZE(VOXEL, VIEW_PROJ), MEMBER_OFFSET(VOXEL, VIEW_PROJ) };
VOXEL_DETAILS.semanticDetails.push_back(DETAIL);
}
// VIEW_PROJ_INV
{
ConstantSemanticDetail DETAIL = { CS_VOXEL_VIEW_PROJ_INV, EF_R32G32B32A32_FLOAT, 4 * 3, MEMBER_SIZE(VOXEL, VIEW_PROJ_INV), MEMBER_OFFSET(VOXEL, VIEW_PROJ_INV) };
VOXEL_DETAILS.semanticDetails.push_back(DETAIL);
}
// MIDPOINT_SCALE
{
ConstantSemanticDetail DETAIL = { CS_VOXEL_MIDPOINT_SCALE, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(VOXEL, MIDPOINT_SCALE), MEMBER_OFFSET(VOXEL, MIDPOINT_SCALE) };
VOXEL_DETAILS.semanticDetails.push_back(DETAIL);
}
// MISCS
{
ConstantSemanticDetail DETAIL = { CS_VOXEL_MISCS, EF_R32_UINT, 4, MEMBER_SIZE(VOXEL, MISCS), MEMBER_OFFSET(VOXEL, MISCS) };
VOXEL_DETAILS.semanticDetails.push_back(DETAIL);
}
VOXEL_DETAILS.bufferSize = sizeof(VOXEL);
}
// GLOBAL
{
// SUN_LIGHT_DIR
{
ConstantSemanticDetail DETAIL = { CS_SUN_LIGHT_DIRECTION, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(GLOBAL, SUN_LIGHT_DIR), MEMBER_OFFSET(GLOBAL, SUN_LIGHT_DIR) };
GLOBAL_DETAILS.semanticDetails.push_back(DETAIL);
}
GLOBAL_DETAILS.bufferSize = sizeof(GLOBAL);
}
CONSTANT_DETAIL_INIT = true;
}
}
const ConstantBufferDetail& GetConstantBufferDetail(ConstantBufferType bufferType)
{
SafeInit();
switch (bufferType)
{
case CBT_CAMERA:
return CAMERA_DETAILS;
case CBT_SHADOW:
return SHADOW_DETAILS;
case CBT_CASCADED_SHADOW:
return CASCADED_SHADOW_DETAILS;
case CBT_VOXEL:
return VOXEL_DETAILS;
case CBT_GLOBAL:
return GLOBAL_DETAILS;
default:
assert(false && "Unknown ConstantBufferType");
return EMPYT_DETAILS;
}
}
}
| 37.479042
| 196
| 0.743569
|
King19931229
|
02496a9d11e2f2c402f399026afa68502c18c5b9
| 598
|
hpp
|
C++
|
irohad/model/query_response.hpp
|
artyom-yurin/iroha-archive
|
1ad3a149d21d30e99c650a9a4bad88b2792d751d
|
[
"Apache-2.0"
] | 31
|
2019-04-17T19:32:05.000Z
|
2022-02-05T01:35:02.000Z
|
irohad/model/query_response.hpp
|
artyom-yurin/iroha-archive
|
1ad3a149d21d30e99c650a9a4bad88b2792d751d
|
[
"Apache-2.0"
] | 11
|
2016-10-13T10:09:55.000Z
|
2019-06-13T08:49:11.000Z
|
irohad/model/query_response.hpp
|
artyom-yurin/iroha-archive
|
1ad3a149d21d30e99c650a9a4bad88b2792d751d
|
[
"Apache-2.0"
] | 12
|
2019-06-03T10:31:31.000Z
|
2021-12-13T12:17:15.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_QUERY_RESPONSE_HPP
#define IROHA_QUERY_RESPONSE_HPP
#include <memory>
#include "crypto/hash_types.hpp"
#include "model/client.hpp"
#include "model/query.hpp"
namespace iroha {
namespace model {
/**
* Interface of query response for user
*/
struct QueryResponse {
/**
* Client query
*/
hash256_t query_hash{};
virtual ~QueryResponse() {}
};
} // namespace model
} // namespace iroha
#endif // IROHA_QUERY_RESPONSE_HPP
| 19.290323
| 53
| 0.658863
|
artyom-yurin
|
024a4d8d95c5a6b2a0db4e4836429606715b30b5
| 3,576
|
hpp
|
C++
|
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | null | null | null |
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | null | null | null |
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | null | null | null |
//
// FILE NAME: TestCIDMData_AttrData.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/07/2018
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// The header for the attribute data tests.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// CLASS: TTest_AttrDataBasic
// PREFIX: tfwt
// ---------------------------------------------------------------------------
class TTest_AttrDataBasic : public TTestFWTest
{
public :
// -------------------------------------------------------------------
// Constructor and Destructor
// -------------------------------------------------------------------
TTest_AttrDataBasic();
~TTest_AttrDataBasic();
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tTestFWLib::ETestRes eRunTest
(
TTextStringOutStream& strmOutput
, tCIDLib::TBoolean& bWarning
) final;
private :
// -------------------------------------------------------------------
// Private, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bTestState
(
TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const TString& strFmtValue
);
tCIDLib::TBoolean bTestState2
(
TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue
);
tCIDLib::TBoolean bTestState3
(
TTextOutStream& strmOut
, const TString& strTestName
, const tCIDLib::TCard4 c4Line
, const TAttrData& adatTest
, const TString& strAttrId
, const TString& strSpecType
, const TString& strLimits
, const tCIDMData::EAttrTypes eType
, const tCIDMData::EAttrEdTypes eEditType
, const TString& strFmtValue
, const tCIDLib::TCard8 c8UserData
, const TString& strUserData
);
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TTest_AttrDataBasic, TTestFWTest)
};
| 34.384615
| 78
| 0.39877
|
MarkStega
|
024e57bdb0089575ac829640706113b6c2366713
| 970
|
cpp
|
C++
|
source/RegistRTTR.cpp
|
xzrunner/visiongraph
|
476ea49bbf56d6a2caa062d05677e768575d7ea1
|
[
"MIT"
] | null | null | null |
source/RegistRTTR.cpp
|
xzrunner/visiongraph
|
476ea49bbf56d6a2caa062d05677e768575d7ea1
|
[
"MIT"
] | null | null | null |
source/RegistRTTR.cpp
|
xzrunner/visiongraph
|
476ea49bbf56d6a2caa062d05677e768575d7ea1
|
[
"MIT"
] | null | null | null |
#define EXE_FILEPATH "visiongraph/comp_include_gen.h"
#include "visiongraph/comp_regist_cfg.h"
#undef EXE_FILEPATH
#include <rttr/registration>
#define REGIST_COMP_TYPE(type, name) \
rttr::registration::class_<visiongraph::comp::type>("vg::"#name) \
.constructor<>() \
;
#define REGIST_ENUM_ITEM(type, name, label) \
rttr::value(name, type), \
rttr::metadata(type, label) \
RTTR_REGISTRATION
{
rttr::registration::class_<dag::Node<vg::CompVarType>::Port>("vg::Node::Port")
.property("var", &dag::Node<vg::CompVarType>::Port::var)
;
rttr::registration::class_<vg::Component>("vg::Comp")
.method("GetImports", &vg::Component::GetImports)
.method("GetExports", &vg::Component::GetExports)
;
#define EXE_FILEPATH "visiongraph/comp_rttr_gen.h"
#include "visiongraph/comp_regist_cfg.h"
#undef EXE_FILEPATH
}
namespace vg
{
void regist_rttr()
{
}
}
| 23.658537
| 78
| 0.64433
|
xzrunner
|
0250d212edfdbdd165811d908620272c8b6add10
| 2,149
|
hpp
|
C++
|
src/utility/Timer.hpp
|
jabra98/chip8EMU
|
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
|
[
"MIT"
] | 6
|
2020-06-02T12:03:48.000Z
|
2021-07-05T20:52:03.000Z
|
src/utility/Timer.hpp
|
jabra98/chip8EMU
|
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
|
[
"MIT"
] | null | null | null |
src/utility/Timer.hpp
|
jabra98/chip8EMU
|
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
|
[
"MIT"
] | 1
|
2020-04-10T15:31:01.000Z
|
2020-04-10T15:31:01.000Z
|
#ifndef TIMER_HPP
#define TIMER_HPP
#include <chrono>
#include <stdexcept>
class Timer
{
public:
enum class Type
{
cpu,
framerate,
seconds,
milliseconds
};
bool is_ready(Type t, long long required_rate)
{
if (required_rate == 0)
return false;
if (t == Type::cpu)
{
if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() -
cpu_interval).count() > (1'000'000 / required_rate))
{
cpu_interval = timer.now();
return true;
}
else
return false;
}
else if (t==Type::framerate)
{
if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() -
frame_interval).count() > (1'000'000 / required_rate))
{
frame_interval = timer.now();
return true;
}
else
return false;
}
else if (t==Type::seconds)
{
if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() -
seconds).count() > (1'000'000 / required_rate))
{
seconds = timer.now();
return true;
}
else
return false;
}
else if (t==Type::milliseconds)
{
if (std::chrono::duration_cast<std::chrono::milliseconds>(timer.now() -
milliseconds).count() > (required_rate))
{
milliseconds = timer.now();
return true;
}
else
return false;
}
throw std::runtime_error{"unsupported timertype"};
}
private:
std::chrono::time_point<std::chrono::steady_clock> milliseconds{};
std::chrono::time_point<std::chrono::steady_clock> seconds{};
std::chrono::time_point<std::chrono::steady_clock> frame_interval{};
std::chrono::time_point<std::chrono::steady_clock> cpu_interval{};
std::chrono::steady_clock timer;
};
#endif // TIMER_HPP
| 27.202532
| 84
| 0.500233
|
jabra98
|
0256646db1940ee49d099786ccb4fa7b8ec9d819
| 3,652
|
cpp
|
C++
|
src/smt/smt_lookahead.cpp
|
vmishenev/misynth
|
5bd977cb32144a6d61670c874efad49982f75932
|
[
"MIT"
] | 55
|
2015-08-15T22:37:02.000Z
|
2022-03-27T03:08:02.000Z
|
src/smt/smt_lookahead.cpp
|
ekpyron/z3
|
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
|
[
"MIT"
] | 16
|
2016-04-13T23:48:33.000Z
|
2020-02-02T12:38:52.000Z
|
src/smt/smt_lookahead.cpp
|
ekpyron/z3
|
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
|
[
"MIT"
] | 18
|
2015-08-11T08:37:41.000Z
|
2021-09-16T14:24:04.000Z
|
/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smt_lookahead.cpp
Abstract:
Lookahead cuber for SMT
Author:
nbjorner 2019-05-27.
Revision History:
--*/
#include <cmath>
#include "ast/ast_smt2_pp.h"
#include "smt/smt_lookahead.h"
#include "smt/smt_context.h"
namespace smt {
lookahead::lookahead(context& ctx):
ctx(ctx), m(ctx.get_manager()) {}
double lookahead::get_score() {
double score = 0;
for (clause* cp : ctx.m_aux_clauses) {
unsigned nf = 0, nu = 0;
bool is_taut = false;
for (literal lit : *cp) {
switch (ctx.get_assignment(lit)) {
case l_false:
if (ctx.get_assign_level(lit) > 0) {
++nf;
}
break;
case l_true:
is_taut = true;
break;
default:
++nu;
break;
}
}
if (!is_taut && nf > 0) {
score += pow(0.5, nu);
}
}
return score;
}
struct lookahead::compare {
context& ctx;
compare(context& ctx): ctx(ctx) {}
bool operator()(bool_var v1, bool_var v2) const {
return ctx.get_activity(v1) > ctx.get_activity(v2);
}
};
expr_ref lookahead::choose() {
ctx.pop_to_base_lvl();
unsigned sz = ctx.m_bool_var2expr.size();
bool_var best_v = null_bool_var;
double best_score = -1;
svector<bool_var> vars;
for (bool_var v = 0; v < static_cast<bool_var>(sz); ++v) {
expr* b = ctx.bool_var2expr(v);
if (b && ctx.get_assignment(v) == l_undef) {
vars.push_back(v);
}
}
compare comp(ctx);
std::sort(vars.begin(), vars.end(), comp);
unsigned nf = 0, nc = 0, ns = 0, bound = 2000;
for (bool_var v : vars) {
if (!ctx.bool_var2expr(v)) continue;
literal lit(v, false);
ctx.push_scope();
ctx.assign(lit, b_justification::mk_axiom(), true);
ctx.propagate();
bool inconsistent = ctx.inconsistent();
double score1 = get_score();
ctx.pop_scope(1);
if (inconsistent) {
ctx.assign(~lit, b_justification::mk_axiom(), false);
ctx.propagate();
++nf;
continue;
}
ctx.push_scope();
ctx.assign(~lit, b_justification::mk_axiom(), true);
ctx.propagate();
inconsistent = ctx.inconsistent();
double score2 = get_score();
ctx.pop_scope(1);
if (inconsistent) {
ctx.assign(lit, b_justification::mk_axiom(), false);
ctx.propagate();
++nf;
continue;
}
double score = score1 + score2 + 1024*score1*score2;
if (score > best_score) {
best_score = score;
best_v = v;
bound += ns;
ns = 0;
}
++nc;
++ns;
if (ns > bound) {
break;
}
}
expr_ref result(m);
if (ctx.inconsistent()) {
result = m.mk_false();
}
else if (best_v != null_bool_var) {
result = ctx.bool_var2expr(best_v);
}
else {
result = m.mk_true();
}
return result;
}
}
| 26.852941
| 69
| 0.452903
|
vmishenev
|
026b4f500cd2619f0f7fc036d74b2cb3c8f5edbc
| 6,372
|
cpp
|
C++
|
Engine/Threading/QueuedTask.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | 16
|
2018-12-22T02:09:05.000Z
|
2022-03-09T20:38:59.000Z
|
Engine/Threading/QueuedTask.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | 46
|
2018-04-02T11:06:01.000Z
|
2019-12-14T11:16:04.000Z
|
Engine/Threading/QueuedTask.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | 14
|
2018-04-09T02:26:15.000Z
|
2021-09-11T03:12:15.000Z
|
// ------------------------------------ //
#include "QueuedTask.h"
using namespace Leviathan;
// ------------------------------------ //
DLLEXPORT Leviathan::QueuedTask::QueuedTask(std::function<void ()> functorun) :
FunctionToRun(functorun)
{
}
DLLEXPORT Leviathan::QueuedTask::~QueuedTask(){
}
// ------------------------------------ //
DLLEXPORT void Leviathan::QueuedTask::RunTask(){
// Run the function //
_PreFunctionRun();
FunctionToRun();
_PostFunctionRun();
}
// ------------------------------------ //
void Leviathan::QueuedTask::_PreFunctionRun(){
}
void Leviathan::QueuedTask::_PostFunctionRun(){
}
// ------------------------------------ //
DLLEXPORT bool Leviathan::QueuedTask::CanBeRan(const QueuedTaskCheckValues* const checkvalues){
return true;
}
DLLEXPORT bool Leviathan::QueuedTask::MustBeRanBefore(int eventtypeidentifier){
return eventtypeidentifier == TASK_MUSTBERAN_BEFORE_EXIT;
}
DLLEXPORT bool Leviathan::QueuedTask::IsRepeating(){
return false;
}
// ------------------ QueuedTaskCheckValues ------------------ //
Leviathan::QueuedTaskCheckValues::QueuedTaskCheckValues() :
CurrentTime(Time::GetThreadSafeSteadyTimePoint())
{
}
// ------------------ ConditionalTask ------------------ //
DLLEXPORT Leviathan::ConditionalTask::ConditionalTask(
std::function<void ()> functorun, std::function<bool ()> canberuncheck) :
QueuedTask(functorun), TaskCheckingFunc(canberuncheck)
{
}
DLLEXPORT Leviathan::ConditionalTask::~ConditionalTask(){
}
DLLEXPORT bool Leviathan::ConditionalTask::CanBeRan(
const QueuedTaskCheckValues* const checkvalues)
{
return TaskCheckingFunc();
}
// ------------------ ConditionalDelayedTask ------------------ //
DLLEXPORT Leviathan::ConditionalDelayedTask::ConditionalDelayedTask(
std::function<void ()> functorun, std::function<bool ()> canberuncheck,
const MicrosecondDuration &delaytime) :
QueuedTask(functorun), TaskCheckingFunc(canberuncheck),
CheckingTime(Time::GetThreadSafeSteadyTimePoint()+delaytime), DelayBetweenChecks(delaytime)
{
}
DLLEXPORT Leviathan::ConditionalDelayedTask::~ConditionalDelayedTask(){
}
DLLEXPORT bool Leviathan::ConditionalDelayedTask::CanBeRan(
const QueuedTaskCheckValues* const checkvalues)
{
// Check is it too early //
if(checkvalues->CurrentTime < CheckingTime)
return false;
// Adjust the next check time //
CheckingTime = Time::GetThreadSafeSteadyTimePoint()+DelayBetweenChecks;
// Run the checking function //
return TaskCheckingFunc();
}
// ------------------ DelayedTask ------------------ //
DLLEXPORT Leviathan::DelayedTask::DelayedTask(std::function<void ()> functorun,
const MicrosecondDuration &delaytime) : QueuedTask(functorun),
ExecutionTime(Time::GetThreadSafeSteadyTimePoint()+delaytime)
{
}
DLLEXPORT Leviathan::DelayedTask::DelayedTask(std::function<void ()> functorun,
const WantedClockType::time_point &executetime) :
QueuedTask(functorun), ExecutionTime(executetime)
{
}
DLLEXPORT Leviathan::DelayedTask::~DelayedTask(){
}
DLLEXPORT bool Leviathan::DelayedTask::CanBeRan(
const QueuedTaskCheckValues* const checkvalues)
{
// Check is the current time past our timestamp //
return checkvalues->CurrentTime >= ExecutionTime;
}
// ------------------ RepeatingDelayedTask ------------------ //
DLLEXPORT Leviathan::RepeatingDelayedTask::RepeatingDelayedTask(
std::function<void ()> functorun, const MicrosecondDuration &bothdelays) :
DelayedTask(functorun, bothdelays), TimeBetweenExecutions(bothdelays), ShouldRunAgain(true)
{
}
DLLEXPORT Leviathan::RepeatingDelayedTask::RepeatingDelayedTask(
std::function<void ()> functorun, const MicrosecondDuration &initialdelay,
const MicrosecondDuration &followingduration) :
DelayedTask(functorun, initialdelay), TimeBetweenExecutions(followingduration),
ShouldRunAgain(true)
{
}
DLLEXPORT Leviathan::RepeatingDelayedTask::~RepeatingDelayedTask(){
}
DLLEXPORT bool Leviathan::RepeatingDelayedTask::IsRepeating(){
return ShouldRunAgain;
}
DLLEXPORT void Leviathan::RepeatingDelayedTask::SetRepeatStatus(bool newvalue){
ShouldRunAgain = newvalue;
}
void Leviathan::RepeatingDelayedTask::_PostFunctionRun(){
// Set new execution point in time //
ExecutionTime = Time::GetThreadSafeSteadyTimePoint()+TimeBetweenExecutions;
}
// ------------------ RepeatCountedTask ------------------ //
DLLEXPORT Leviathan::RepeatCountedTask::RepeatCountedTask(std::function<void ()> functorun,
size_t repeatcount) :
QueuedTask(functorun), MaxRepeats(repeatcount), RepeatedCount(0)
{
}
DLLEXPORT Leviathan::RepeatCountedTask::~RepeatCountedTask(){
}
DLLEXPORT bool Leviathan::RepeatCountedTask::IsRepeating(){
// Increment count and see if there are still repeats left //
return ++RepeatedCount < MaxRepeats;
}
DLLEXPORT void Leviathan::RepeatCountedTask::StopRepeating(){
// This should do the trick //
MaxRepeats = 0;
}
DLLEXPORT size_t Leviathan::RepeatCountedTask::GetRepeatCount() const
{
return RepeatedCount;
}
DLLEXPORT bool Leviathan::RepeatCountedTask::IsThisLastRepeat() const{
return RepeatedCount + 1 >= MaxRepeats;
}
// ------------------ RepeatCountedDelayedTask ------------------ //
DLLEXPORT Leviathan::RepeatCountedDelayedTask::RepeatCountedDelayedTask(
std::function<void ()> functorun,
const MicrosecondDuration &bothdelays, int repeatcount) :
RepeatCountedTask(functorun, repeatcount), TimeBetweenExecutions(bothdelays),
ExecutionTime(Time::GetThreadSafeSteadyTimePoint() + bothdelays)
{
}
DLLEXPORT Leviathan::RepeatCountedDelayedTask::RepeatCountedDelayedTask(
std::function<void ()> functorun,
const MicrosecondDuration &initialdelay,
const MicrosecondDuration &followingduration, int repeatcount) :
RepeatCountedTask(functorun, repeatcount), TimeBetweenExecutions(followingduration),
ExecutionTime(Time::GetThreadSafeSteadyTimePoint()+initialdelay)
{
}
DLLEXPORT Leviathan::RepeatCountedDelayedTask::~RepeatCountedDelayedTask(){
}
DLLEXPORT bool Leviathan::RepeatCountedDelayedTask::CanBeRan(
const QueuedTaskCheckValues* const checkvalues)
{
// Check is the current time past our timestamp //
return checkvalues->CurrentTime >= ExecutionTime;
}
void Leviathan::RepeatCountedDelayedTask::_PostFunctionRun(){
// Set new execution point in time //
ExecutionTime = Time::GetThreadSafeSteadyTimePoint()+TimeBetweenExecutions;
}
| 28.963636
| 95
| 0.724105
|
Higami69
|
0275f4fa5198d87b64f0fe69c9de5e91eb58b7ea
| 323
|
cpp
|
C++
|
src/main/cpp/pistis/logging/Log.cpp
|
tomault/pistis-logging
|
26f1411d161dc08c5684f0df4a95d929e3bbef35
|
[
"Apache-2.0"
] | null | null | null |
src/main/cpp/pistis/logging/Log.cpp
|
tomault/pistis-logging
|
26f1411d161dc08c5684f0df4a95d929e3bbef35
|
[
"Apache-2.0"
] | null | null | null |
src/main/cpp/pistis/logging/Log.cpp
|
tomault/pistis-logging
|
26f1411d161dc08c5684f0df4a95d929e3bbef35
|
[
"Apache-2.0"
] | null | null | null |
#include "Log.hpp"
using namespace pistis::logging;
Log::Log(LogMessageFactory* msgFactory, LogMessageReceiver* msgReceiver,
const std::string& destination, LogLevel logLevel):
msgFactory_(msgFactory), msgReceiver_(msgReceiver),
destination_(destination), logLevel_(logLevel) {
// Intentionally left blank
}
| 26.916667
| 72
| 0.770898
|
tomault
|
027659d075d26f6856fc5298629383779d8ee66f
| 1,268
|
cpp
|
C++
|
src/chat/test/ElizaTest.cpp
|
OznOg/xania
|
4effa29e1c88c7290400a8cf8a67e03ad71c851a
|
[
"BSD-2-Clause"
] | null | null | null |
src/chat/test/ElizaTest.cpp
|
OznOg/xania
|
4effa29e1c88c7290400a8cf8a67e03ad71c851a
|
[
"BSD-2-Clause"
] | null | null | null |
src/chat/test/ElizaTest.cpp
|
OznOg/xania
|
4effa29e1c88c7290400a8cf8a67e03ad71c851a
|
[
"BSD-2-Clause"
] | null | null | null |
/*************************************************************************/
/* Xania (M)ulti(U)ser(D)ungeon server source code */
/* (C) 1995-2020 Xania Development Team */
/* See the header to file: merc.h for original code copyrights */
/* Chat bot originally written by Chris Busch in 1993-5, this file is a */
/* reimplementation of that work. */
/*************************************************************************/
#include "chat/Eliza.hpp"
#include "chat/Database.hpp"
#include "chat/KeywordResponses.hpp"
#include <unistd.h>
#include <catch2/catch.hpp>
using namespace chat;
TEST_CASE("production database sanity") {
std::string chatdata_file = TEST_RESOURCE_DIR "/chat.data";
Eliza eliza;
SECTION("validate production chat database loads and responds to a basic lookup") {
CHECK(eliza.load_databases(chatdata_file) == true);
CHECK(eliza.handle_player_message("player", "what is your name?", "Heimdall") == "My name is \"Heimdall\"");
CHECK(eliza.handle_player_message("player", "you remind me of a big yellow submarine", "Heimdall")
== "In what way am I like a big yellow submarine?");
}
}
| 45.285714
| 116
| 0.554416
|
OznOg
|
027a6ebc2ac3a25e7bc902f573cb157e364f0d05
| 1,188
|
hpp
|
C++
|
Value/ValueVisitorPrinter.hpp
|
Sevenrip/value-container
|
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
|
[
"MIT"
] | null | null | null |
Value/ValueVisitorPrinter.hpp
|
Sevenrip/value-container
|
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
|
[
"MIT"
] | null | null | null |
Value/ValueVisitorPrinter.hpp
|
Sevenrip/value-container
|
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
|
[
"MIT"
] | null | null | null |
#pragma once
#include <ostream>
#include <memory>
#include <type_traits>
#include <unordered_map>
#include <string>
#include <sstream>
#include "../Utils/Utils.hpp"
class ValueVisitorPrinter
{
public:
explicit ValueVisitorPrinter(std::stringstream & stream)
: _stream(stream) {}
ValueVisitorPrinter& operator=(ValueVisitorPrinter const&) = delete;
template <typename T>
void operator()(const T & t ) const
{
_stream << t;
}
void operator()(const std::shared_ptr<const std::string> & s ) const
{
_stream << *s;
}
template <typename T>
void operator()(const std::shared_ptr<std::vector<T>> & t) const
{
_stream << "[ " ;
for(const auto & el : *t) {
this->operator()(el);
}
_stream << " ]" ;
}
template <typename T>
void operator()(const std::shared_ptr<StringMap<T>> & map)
{
_stream << "{ " ;
for(const auto & pair : *map) {
_stream << "{" ;
this->operator()(pair.first);
this->operator()(pair.second);
_stream << "}" ;
}
_stream << " }" ;
}
private:
int _depth;
std::stringstream & _stream;
};
| 19.47541
| 73
| 0.564815
|
Sevenrip
|
027dbd873a120220b9c64c2d82a5a7f0e8a07408
| 7,996
|
cpp
|
C++
|
code/wxWidgets/utils/configtool/src/configitemselector.cpp
|
Bloodknight/NeuTorsion
|
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
|
[
"MIT"
] | 38
|
2016-02-20T02:46:28.000Z
|
2021-11-17T11:39:57.000Z
|
code/wxWidgets/utils/configtool/src/configitemselector.cpp
|
Bloodknight/NeuTorsion
|
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
|
[
"MIT"
] | 17
|
2016-02-20T02:19:55.000Z
|
2021-02-08T15:15:17.000Z
|
code/wxWidgets/utils/configtool/src/configitemselector.cpp
|
Bloodknight/NeuTorsion
|
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
|
[
"MIT"
] | 46
|
2016-02-20T02:47:33.000Z
|
2021-01-31T15:46:05.000Z
|
/////////////////////////////////////////////////////////////////////////////
// Name: configitemselector.cpp
// Purpose: Selector for one or more config items
// Author: Julian Smart
// Modified by:
// Created: 2003-06-04
// RCS-ID: $Id: configitemselector.cpp,v 1.11 2005/02/01 20:44:05 ABX Exp $
// Copyright: (c) Julian Smart
// Licence:
/////////////////////////////////////////////////////////////////////////////
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "configitemselector.h"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/statline.h"
#include "wx/splitter.h"
#include "wx/scrolwin.h"
#include "wx/spinctrl.h"
#include "wx/spinbutt.h"
#endif
#include "wx/cshelp.h"
#include "wx/notebook.h"
#include "wx/valgen.h"
#include "configitemselector.h"
#include "configtooldoc.h"
#include "configtoolview.h"
#include "configitem.h"
#include "mainframe.h"
#include "wxconfigtool.h"
////@begin XPM images
////@end XPM images
/*!
* ctConfigItemsSelector type definition
*/
IMPLEMENT_CLASS( ctConfigItemsSelector, wxDialog )
/*!
* ctConfigItemsSelector event table definition
*/
BEGIN_EVENT_TABLE( ctConfigItemsSelector, wxDialog )
////@begin ctConfigItemsSelector event table entries
EVT_BUTTON( ID_CONFIG_ADD, ctConfigItemsSelector::OnConfigAdd )
EVT_UPDATE_UI( ID_CONFIG_ADD, ctConfigItemsSelector::OnUpdateConfigAdd )
EVT_BUTTON( ID_CONFIG_REMOVE, ctConfigItemsSelector::OnConfigRemove )
EVT_UPDATE_UI( ID_CONFIG_REMOVE, ctConfigItemsSelector::OnUpdateConfigRemove )
EVT_BUTTON( wxID_OK, ctConfigItemsSelector::OnOk )
////@end ctConfigItemsSelector event table entries
END_EVENT_TABLE()
/*!
* ctConfigItemsSelector constructor
*/
ctConfigItemsSelector::ctConfigItemsSelector( wxWindow* parent, wxWindowID id, const wxString& caption)
{
wxDialog::Create( parent, id, caption);
CreateControls();
InitSourceConfigList();
}
/*!
* Control creation for ctConfigItemsSelector
*/
void ctConfigItemsSelector::CreateControls()
{
////@begin ctConfigItemsSelector content construction
ctConfigItemsSelector* item1 = this;
wxBoxSizer* item2 = new wxBoxSizer(wxVERTICAL);
item1->SetSizer(item2);
wxBoxSizer* item3 = new wxBoxSizer(wxVERTICAL);
item2->Add(item3, 1, wxGROW|wxALL, 5);
wxStaticText* item4 = new wxStaticText(item1, wxID_STATIC, _("Please edit the list of configuration items by selecting from the\nlist below."), wxDefaultPosition, wxDefaultSize, 0);
item3->Add(item4, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5);
wxStaticText* item5 = new wxStaticText(item1, wxID_STATIC, _("&Available items:"), wxDefaultPosition, wxDefaultSize, 0);
item3->Add(item5, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5);
wxString* item6Strings = NULL;
wxListBox* item6 = new wxListBox(item1, ID_AVAILABLE_CONFIG_ITEMS, wxDefaultPosition, wxSize(wxDefaultCoord, 150), 0, item6Strings, wxLB_SINGLE|wxLB_SORT);
item3->Add(item6, 1, wxGROW|wxALL, 5);
wxStaticText* item7 = new wxStaticText(item1, wxID_STATIC, _("&List of configuration items:"), wxDefaultPosition, wxDefaultSize, 0);
item3->Add(item7, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5);
wxBoxSizer* item8 = new wxBoxSizer(wxHORIZONTAL);
item3->Add(item8, 0, wxGROW, 5);
wxString* item9Strings = NULL;
wxListBox* item9 = new wxListBox(item1, ID_CONFIG_ITEMS, wxDefaultPosition, wxSize(wxDefaultCoord, 100), 0, item9Strings, wxLB_SINGLE);
item8->Add(item9, 1, wxGROW|wxALL, 5);
wxBoxSizer* item10 = new wxBoxSizer(wxVERTICAL);
item8->Add(item10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* item11 = new wxButton(item1, ID_CONFIG_ADD, _("A&dd"), wxDefaultPosition, wxDefaultSize, 0);
item10->Add(item11, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxButton* item12 = new wxButton(item1, ID_CONFIG_REMOVE, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0);
item10->Add(item12, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
wxBoxSizer* item13 = new wxBoxSizer(wxHORIZONTAL);
item3->Add(item13, 0, wxGROW, 5);
item13->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* item15 = new wxButton(item1, wxID_OK);
item15->SetDefault();
item13->Add(item15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
wxButton* item16 = new wxButton(item1, wxID_CANCEL);
item13->Add(item16, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
Centre();
////@end ctConfigItemsSelector content construction
}
/*!
* Event handler for ID_CONFIG_ADD
*/
void ctConfigItemsSelector::OnConfigAdd( wxCommandEvent& WXUNUSED(event) )
{
wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox);
wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox);
if (masterList)
{
if (masterList->GetSelection() > -1)
{
wxString str = masterList->GetStringSelection();
if (m_configItems.Index(str) == wxNOT_FOUND)
{
listBox->Append(str);
m_configItems.Add(str);
}
}
}
}
/*!
* Event handler for ID_CONFIG_REMOVE
*/
void ctConfigItemsSelector::OnConfigRemove( wxCommandEvent& WXUNUSED(event) )
{
wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox);
if (listBox)
{
if (listBox->GetSelection() > -1)
{
wxString str = listBox->GetStringSelection();
listBox->Delete(listBox->GetSelection());
m_configItems.Remove(str);
}
}
}
/*!
* Event handler for wxID_OK
*/
void ctConfigItemsSelector::OnOk( wxCommandEvent& event )
{
// Replace with custom code
event.Skip();
}
/*!
* Should we show tooltips?
*/
bool ctConfigItemsSelector::ShowToolTips()
{
return true;
}
/*!
* Update event handler for ID_CONFIG_ADD
*/
void ctConfigItemsSelector::OnUpdateConfigAdd( wxUpdateUIEvent& event )
{
wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox);
event.Enable(masterList && masterList->GetSelection() != -1);
}
/*!
* Update event handler for ID_CONFIG_REMOVE
*/
void ctConfigItemsSelector::OnUpdateConfigRemove( wxUpdateUIEvent& event )
{
wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox);
event.Enable(listBox && listBox->GetSelection() != -1);
}
/// Initialise the master list
void ctConfigItemsSelector::InitSourceConfigList(ctConfigItem* item)
{
wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox);
if (!item)
item = wxGetApp().GetMainFrame()->GetDocument()->GetTopItem();
if (!item)
return;
bool addIt = false;
if (item->GetType() == ctTypeGroup)
addIt = false;
else if (item->GetType() == ctTypeCheckGroup)
addIt = true;
else if (item->GetType() == ctTypeRadioGroup)
addIt = true;
else if (item->GetType() == ctTypeString)
addIt = true;
else if (item->GetType() == ctTypeBoolCheck)
addIt = true;
else if (item->GetType() == ctTypeBoolRadio)
addIt = true;
else if (item->GetType() == ctTypeInteger)
addIt = true;
if (addIt)
{
masterList->Append(item->GetName());
}
wxObjectList::compatibility_iterator node = item->GetChildren().GetFirst();
while (node)
{
ctConfigItem* child = (ctConfigItem*) node->GetData();
InitSourceConfigList(child);
node = node->GetNext();
}
}
/// Set the initial list
void ctConfigItemsSelector::SetConfigList(const wxArrayString& items)
{
m_configItems = items;
wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox);
listBox->Clear();
size_t i;
for (i = 0; i < items.GetCount(); i++)
listBox->Append(items[i]);
}
| 28.866426
| 185
| 0.681591
|
Bloodknight
|
028104b7714953839a12c04612e6e6e671966089
| 11,207
|
cpp
|
C++
|
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
|
Enderderder/SonyEngine
|
ee8b3726d293c667d2e2a849808b993e954b84c7
|
[
"MIT"
] | 2
|
2020-02-22T01:27:28.000Z
|
2021-12-20T08:41:43.000Z
|
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
|
Enderderder/SonyEngine
|
ee8b3726d293c667d2e2a849808b993e954b84c7
|
[
"MIT"
] | null | null | null |
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
|
Enderderder/SonyEngine
|
ee8b3726d293c667d2e2a849808b993e954b84c7
|
[
"MIT"
] | 2
|
2019-09-17T19:54:00.000Z
|
2020-03-06T15:08:52.000Z
|
/* SIE CONFIDENTIAL
PlayStation(R)4 Programmer Tool Runtime Library Release 05.008.001
* Copyright (C) 2016 Sony Interactive Entertainment Inc.
* All Rights Reserved.
*/
// Simplet #7
// This simplet shows how to setup es, gs shaders to create geometry
#include "../toolkit/simplet-common.h"
#include "std_cbuffer.h"
using namespace sce;
bool screenshot = false;
// {
// "title" : "simplet-gs-stream-out",
// "overview" : "This sample demonstrates simple stream out with geometry shading.",
// "explanation" : ["This sample sets up required compile switches, stream out buffers and registers and performs simple geometry shading with them.",
// "There are three necessary steps to use streamout:",
// "1. Use the geometry shader compiled with the -gsstream switches.",
// "2. Set streamout buffers.",
// "3. Set streamout config registers.",
// "Streamout config registers need to be set before each streamout draw because the GPU maintains persistent streamout state and the next draw call may continue writing where the last call ended causing possible memory corruption."]
// }
static const unsigned s_shader_g[] = {
#include "shader_g.h"
};
static const unsigned s_shader_p[] = {
#include "shader_p.h"
};
static const unsigned s_shader_ve[] = {
#include "shader_ve.h"
};
static void Test()
{
//
// Define window size and set up a window to render to it
//
uint32_t targetWidth = 1920;
uint32_t targetHeight = 1080;
SimpletUtil::getResolution(targetWidth, targetHeight);
//
// Setup the render target:
//
Gnm::DataFormat format = Gnm::kDataFormatB8G8R8A8UnormSrgb;
Gnm::RenderTarget fbTarget;
Gnm::TileMode tileMode;
GpuAddress::computeSurfaceTileMode(Gnm::getGpuMode(), &tileMode, GpuAddress::kSurfaceTypeColorTargetDisplayable, format, 1);
Gnm::SizeAlign fbSize = Gnmx::Toolkit::init(&fbTarget, targetWidth, targetHeight, 1, format, tileMode, Gnm::kNumSamples1, Gnm::kNumFragments1, NULL, NULL);
void *fbCpuBaseAddr = SimpletUtil::allocateGarlicMemory(fbSize);
uint8_t *fbBaseAddr = static_cast<uint8_t*>(fbCpuBaseAddr);
memset(fbCpuBaseAddr, 0x0, fbSize.m_size);
fbTarget.setAddresses(fbBaseAddr, 0, 0);
//
// Load all shader binaries to video memory
//
Gnmx::EsShader *exportShader = SimpletUtil::LoadEsShaderFromMemory(s_shader_ve);
Gnmx::GsShader *geometryShader = SimpletUtil::LoadGsShaderFromMemory(s_shader_g);
Gnmx::PsShader *pixelShader = SimpletUtil::LoadPsShaderFromMemory(s_shader_p);
//
// Allocate esgs and gsvs rings
//
const uint32_t esgsRingSize = Gnm::kGsRingSizeSetup4Mb, gsvsRingSize = Gnm::kGsRingSizeSetup4Mb;
void *esgsRing = SimpletUtil::allocateGarlicMemory(esgsRingSize, Gnm::kAlignmentOfBufferInBytes);
void *gsvsRing = SimpletUtil::allocateGarlicMemory(gsvsRingSize, Gnm::kAlignmentOfBufferInBytes);
//
// Create a synchronization point:
//
volatile uint64_t *label = (uint64_t*)SimpletUtil::allocateOnionMemory(sizeof(uint64_t), sizeof(uint64_t));
//
// Setup the Command and constant buffers:
//
Gnmx::GfxContext gfxc;
const uint32_t kNumRingEntries = 64;
const uint32_t cueHeapSize = Gnmx::ConstantUpdateEngine::computeHeapSize(kNumRingEntries);
gfxc.init(SimpletUtil::allocateGarlicMemory(cueHeapSize, Gnm::kAlignmentOfBufferInBytes), kNumRingEntries, // Constant Update Engine
SimpletUtil::allocateOnionMemory(Gnm::kIndirectBufferMaximumSizeInBytes, Gnm::kAlignmentOfBufferInBytes), Gnm::kIndirectBufferMaximumSizeInBytes, // Draw command buffer
SimpletUtil::allocateOnionMemory(Gnm::kIndirectBufferMaximumSizeInBytes, Gnm::kAlignmentOfBufferInBytes), Gnm::kIndirectBufferMaximumSizeInBytes // Constant command buffer
);
#if !SCE_GNM_CUE2_DYNAMIC_GLOBAL_TABLE
void *globalResourceTablePtr = SimpletUtil::allocateGarlicMemory(SCE_GNM_SHADER_GLOBAL_TABLE_SIZE, Gnm::kAlignmentOfBufferInBytes);
gfxc.setGlobalResourceTableAddr(globalResourceTablePtr);
#endif //!SCE_GNM_CUE2_DYNAMIC_GLOBAL_TABLE
gfxc.setRenderTarget(0, &fbTarget);
gfxc.setRenderTargetMask(0xF);
gfxc.setupScreenViewport(0, 0, targetWidth, targetHeight, 0.5f, 0.5f);
// Set hardware render in wire frame
Gnm::PrimitiveSetup primSetupReg;
primSetupReg.init();
primSetupReg.setPolygonMode(Gnm::kPrimitiveSetupPolygonModeLine, Gnm::kPrimitiveSetupPolygonModeLine);
gfxc.setLineWidth(8);
gfxc.setPrimitiveSetup(primSetupReg);
// The HW stages used for geometry shading (when tessellation is disabled) are
// ES -> GS -> VS -> PS and the shaders assigned to these stages are:
// Vertex Shader --> Geometry Shader --> (Copy VS shader) --> Pixel Shader
// The shaders assigned to the ES and GS stages both write their data to off-chip memory.
// All of the work described by a single geometry shader invocation is performed by just one thread.
// Do we know anything about foot-print yet?
// set rings
gfxc.setEsGsRingBuffer(esgsRing, esgsRingSize, exportShader->m_memExportVertexSizeInDWord);
gfxc.setGsVsRingBuffers(gsvsRing, gsvsRingSize,
geometryShader->m_memExportVertexSizeInDWord,
geometryShader->m_maxOutputVertexCount);
// Setup streamout config:
const uint32_t streamSizeInDW = 8*1024*1024;
Gnm::StreamoutBufferMapping bufferBinding;
bufferBinding.init();
bufferBinding.bindStream(Gnm::kStreamoutBuffer0,Gnm::StreamoutBufferMapping::kGsStreamBuffer0);
bufferBinding.bindStream(Gnm::kStreamoutBuffer1,Gnm::StreamoutBufferMapping::kGsStreamBuffer0);
// Setting partial vs wave, needed for streamout, the rest of the parameters are default values
gfxc.setVgtControl(255);
// Setting streamout parameters
gfxc.flushStreamout();
gfxc.setStreamoutMapping(&bufferBinding);
gfxc.setStreamoutBufferDimensions(Gnm::kStreamoutBuffer0,streamSizeInDW,16/4);
gfxc.setStreamoutBufferDimensions(Gnm::kStreamoutBuffer1,streamSizeInDW,12/4);
gfxc.writeStreamoutBufferOffset(Gnm::kStreamoutBuffer0,0);
gfxc.writeStreamoutBufferOffset(Gnm::kStreamoutBuffer1,0);
void* soBuf0 = SimpletUtil::allocateGarlicMemory(streamSizeInDW*4, 256);
void* soBuf1 = SimpletUtil::allocateGarlicMemory(streamSizeInDW*4, 256);
// Setup streamout buffers.
Gnm::Buffer sob0;
Gnm::Buffer sob1;
// Set Vertex Shader: ES stage is a vertex shader that writes to the ES-GS ring-buffer
// uint64_t fetchShaderAddr = 0; // in this sample we're not using a vertex buffer
gfxc.setEsShader(exportShader, 0, (void*)0); // so we do not have a fetch shader.
// Set Geometry Shader: GS stage is a geometry shader that writes to the GS-VS ring-buffer
gfxc.setGsVsShaders(geometryShader); // sets up copy VS shader too
// Set Pixel Shader
gfxc.setPsShader(pixelShader);
sob0.initAsGsStreamoutDescriptor(soBuf0, 16);
sob1.initAsGsStreamoutDescriptor(soBuf1, 12);
sob0.setResourceMemoryType(Gnm::kResourceMemoryTypeGC); // we write to it, so it's GPU coherent
sob1.setResourceMemoryType(Gnm::kResourceMemoryTypeGC); // we write to it, so it's GPU coherent
gfxc.setStreamoutBuffers(0, 1, &sob0);
gfxc.setStreamoutBuffers(1, 1, &sob1);
// Set which stages are enabled
gfxc.setActiveShaderStages(Gnm::kActiveShaderStagesEsGsVsPs);
// Initiate the actual rendering
gfxc.setPrimitiveType(Gnm::kPrimitiveTypePointList);
gfxc.drawIndexAuto(NUMSEGS_X*NUMSEGS_Y);
// Set hardware state back to its default state
gfxc.setActiveShaderStages(Gnm::kActiveShaderStagesVsPs);
// In addition of turning off the GS shader stage off; the GS Mode also needs to be turned off.
gfxc.setGsModeOff();
//
// Add a synchronization point:
//
gfxc.writeImmediateAtEndOfPipe(Gnm::kEopFlushCbDbCaches, (void *)label, 0x1, Gnm::kCacheActionWriteBackAndInvalidateL1andL2);
SimpletUtil::registerRenderTargetForDisplay(&fbTarget);
// Loop over the buffer
bool done = false;
while (!done)
{
*label =2;
// Submit the command buffers:
// Note: we are passing the ccb in the last two arguments; when no ccb is used, 0 should be passed in
int32_t state = gfxc.submit();
SCE_GNM_ASSERT(state == sce::Gnm::kSubmissionSuccess);
// Wait until it's done (waiting for the GPU to write "1" in "label")
uint32_t wait = 0;
while (*label != 1)
++wait;
if(screenshot)
{
Gnm::Texture fbTexture;
fbTexture.initFromRenderTarget(&fbTarget, false);
fbTexture.setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // we won't bind this as RWTexture, so it's OK to declare it read-only.
SimpletUtil::SaveTextureToTGA(&fbTexture, "screenshot.tga");
screenshot = 0;
}
// Display the render target on the screen
SimpletUtil::requestFlipAndWait();
// Check to see if user has requested to quit the loop
done = SimpletUtil::handleUserEvents();
// Verify the streamout output by repeating the computation from the geometry shader
// and comparing the output to the data in the streamout buffers.
const float* positions = (float*)soBuf0;
const float* colors = (float*)soBuf1;
bool success = true;
float position[4];
position[2] = 0.f;
position[3] = 1.f;
// The geometry shader outputs a 4 vertices stream that is converted to two triangles (6 vertices)
// so the order the quad's vertices appear in the streamout buffers is as follows:
const unsigned order[6] = { 0, 1, 2, 1, 3, 2};
for( unsigned j = 0; j != NUMSEGS_Y; ++j)
for (unsigned i=0; i != NUMSEGS_X; ++i)
{
// This is the same code the geometry shader uses to create quad's vertices
const unsigned point_index = NUMSEGS_X*j + i;
const float t = (float)point_index/(NUMSEGS_X*NUMSEGS_Y - 1);
const float color[3] = { 0.5f *(t + (1.f - t)),
0.5f * (1.f - t),
0.5f * (1.f - t)
};
for(unsigned idx=0; idx !=6; ++idx )
{
const unsigned v = order[idx];
const unsigned ix = i + (v & 1);
const unsigned iy = j + (v >> 1);
position[0] = 0.5f * (2.f * ix / NUMSEGS_X - 1.f);
position[1] = 0.5f * (2.f * iy / NUMSEGS_Y - 1.f);
// When doing floating point computations on different processors it's possible to get
// slightly different results due to different configuration of the FPUs (e.g. rounding mode, precision etc)
// Because of this, bitwise comparison between the results of the simulated geometry shader and the streamout may fail.
// Instead of bitwise comparison we are checking if the results are close enough by estimating the mean squared error.
float errPos = 0.f;
for(unsigned e = 0; e != 4; ++e)
{
const float d = position[e] - positions[e];
errPos += d*d;
}
float errColor = 0.f;
for(unsigned e = 0; e != 3; ++e)
{
const float d = colors[e] - color[e];
errColor += d*d;
}
const float epsilon = 1e-8f;
if( errPos >= epsilon || errColor >= epsilon)
{
success = false;
printf("Validation failed at grid cell #(%d,%d)\n",i,j);
}
positions += 4;
colors += 3;
}
}
if( success )
printf("Validated OK\n");
}
}
int main(int argc, char *argv[])
{
if (argc > 1 && !strcmp(argv[1], "screenshot"))
screenshot = true;
//
// Initializes system and video memory and memory allocators.
//
SimpletUtil::Init();
{
//
// Run the test
//
Test();
}
return 0;
}
| 35.577778
| 237
| 0.725618
|
Enderderder
|
0281ccab2da476acf4f88b7b6f45cf1692cf0505
| 320
|
cpp
|
C++
|
main.cpp
|
cfiutak1/AdaptiveCacheAwareBlockQuickselect
|
e736585e276832d9c6d50ce67ad37e72b87129ef
|
[
"MIT"
] | 1
|
2020-09-11T19:29:30.000Z
|
2020-09-11T19:29:30.000Z
|
main.cpp
|
cfiutak1/AdaptiveCacheAwareBlockQuickselect
|
e736585e276832d9c6d50ce67ad37e72b87129ef
|
[
"MIT"
] | null | null | null |
main.cpp
|
cfiutak1/AdaptiveCacheAwareBlockQuickselect
|
e736585e276832d9c6d50ce67ad37e72b87129ef
|
[
"MIT"
] | null | null | null |
#include <iterator>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <vector>
#include <cassert>
#include <random>
#include "adaptive_blockquickselect.hpp"
//#include "BlockQuicksort/quickselect.hpp"
//#include "MedianOfNinthers/src/median_of_ninthers.h"
int main() {
std::srand(42);
}
| 11.428571
| 54
| 0.7125
|
cfiutak1
|
0286bd92415463a20b1fec294ade82406f00fe82
| 16,714
|
cpp
|
C++
|
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
|
euhat/EuhatExpert
|
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
|
[
"BSD-2-Clause"
] | null | null | null |
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
|
euhat/EuhatExpert
|
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
|
[
"BSD-2-Clause"
] | null | null | null |
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
|
euhat/EuhatExpert
|
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
|
[
"BSD-2-Clause"
] | null | null | null |
#include "stdafx.h"
#include "../../Expert.h"
#include "../../ExpertDlg.h"
#include "FileManDlg.h"
#include "FileManCfgDlg.h"
#include "FileManSubDlg.h"
#include "../EuhatPeerDlg.h"
#include "../../EuhatRightDlg.h"
#include "../../EuhatLeftDlg.h"
#include "FmFileDlg.h"
#include <app/FileMan/client/FileManClient.h>
#include <app/FileMan/common/FmLocal.h>
#include <app/FileMan/common/FmScheduler.h>
#include <app/FileMan/common/FmTask.h>
#include <EuhatPostDefMfc.h>
#define WM_USER_FILE_MAN_CLIENT_NOTIFY (WM_USER + 1)
FileManSubDlg::FileManSubDlg(EuhatBase *euhatBase)
: MfcBasePage(IDD_FILE_MAN_SUB_DIALOG, euhatBase)
{
}
FileManSubDlg::~FileManSubDlg()
{
remote_.reset();
}
void FileManSubDlg::DoDataExchange(CDataExchange *pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(FileManSubDlg, CDialogEx)
ON_WM_SIZE()
ON_MESSAGE(WM_USER_FILE_MAN_CLIENT_NOTIFY, &FileManSubDlg::onFileManClientNotify)
ON_BN_CLICKED(IDC_BTN_CONNECT, &FileManSubDlg::OnBnClickedBtnConnect)
ON_BN_CLICKED(IDC_BTN_REMOTE_COPY_TO_LOCAL, &FileManSubDlg::OnBnClickedBtnRemoteCopyToLocal)
ON_BN_CLICKED(IDC_BTN_LOCAL_COPY_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnLocalCopyToRemote)
ON_BN_CLICKED(IDC_BTN_REMOTE_MOVE_TO_LOCAL, &FileManSubDlg::OnBnClickedBtnRemoteMoveToLocal)
ON_BN_CLICKED(IDC_BTN_LOCAL_MOVE_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnLocalMoveToRemote)
ON_BN_CLICKED(IDC_BTN_COPY_CLIPBOARD_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnCopyClipboardToRemote)
ON_BN_CLICKED(IDC_BTN_COPY_CLIPBOARD_FROM_REMOTE, &FileManSubDlg::OnBnClickedBtnCopyClipboardFromRemote)
END_MESSAGE_MAP()
void FileManSubDlg::fmscNotify()
{
PostMessage(WM_USER_FILE_MAN_CLIENT_NOTIFY);
}
LRESULT FileManSubDlg::onFileManClientNotify(WPARAM wParam, LPARAM lParam)
{
if (NULL == scheduler_.get())
return 0;
scheduler_->user_->notify();
return 1;
}
void FileManSubDlg::correctPos()
{
if (NULL == GetDlgItem(IDC_LIST_REMOTE_FILE_LIST))
return;
int margin = 8;
int mainBtnWidth = 60;
int btnHeight = 28;
int cmdListHeight = 100;
CRect rc;
GetClientRect(&rc);
correctPos(rc, margin, IDC_LIST_REMOTE_FILE_LIST, dlgRemote_.get());
correctPos(rc, margin, IDC_LIST_LOCAL_FILE_LIST, dlgLocal_.get());
CRect rcCfg;
GetWindowRect(&rcCfg);
euhatBase_->mainWnd_->ScreenToClient(&rcCfg);
}
void FileManSubDlg::correctPos(CRect &rc, int margin, int idd, MfcBasePage *dlg)
{
CRect rcList;
GetDlgItem(idd)->GetWindowRect(&rcList);
ScreenToClient(&rcList);
rcList.bottom = rc.bottom - margin;
dlg->MoveWindow(rcList);
}
BOOL FileManSubDlg::OnInitDialog()
{
MfcBasePage::OnInitDialog();
scheduler_.reset(new FmScheduler(this));
local_.reset(new FmLocal(scheduler_.get()));
scheduler_->local_ = local_.get();
local_->start();
dlgRemote_.reset(new FmFileDlg(euhatBase_));
dlgRemote_->parentDlg_ = this;
dlgRemote_->create(this);
dlgLocal_.reset(new FmFileDlg(euhatBase_));
dlgLocal_->engine_ = local_.get();
dlgLocal_->isLocal_ = 1;
dlgLocal_->parentDlg_ = this;
dlgLocal_->create(this);
browserDir(local_.get(), "");
correctPos();
return TRUE;
}
void FileManSubDlg::OnSize(UINT nType, int cx, int cy)
{
MfcBasePage::OnSize(nType, cx, cy);
correctPos();
}
void FileManSubDlg::browserDir(JyMsgLoop *loop, const char *dir)
{
scheduler_->cleanError();
shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList));
task->path_.reset(opStrDup(dir));
task->action_ = FmTaskGetSubList::ActionInformUi;
scheduler_->add(task);
scheduler_->notifyEngine();
fmscOnRefresh();
}
void FileManSubDlg::fmscOnGetSubList(JyMsgLoop *loop, JyDataReadStream &ds)
{
if (loop == remote_.get())
{
dlgRemote_->displayFiles(ds);
}
else
{
dlgLocal_->displayFiles(ds);
}
}
void FileManSubDlg::fmscNeedReconnect()
{
parentDlg_->resetFileManClient();
scheduler_->notifyEngine();
scheduler_->notifyUi();
}
void FileManSubDlg::fmscOnRefresh()
{
onClipboardFileComing();
parentDlg_->listTask_->rows_.clear();
WhMutexGuard guard(&scheduler_->mutex_);
if (scheduler_->tasks_.size() == 0 && NULL != scheduler_->refreshSubListTask_.get())
{
scheduler_->tasks_.push_back(scheduler_->refreshSubListTask_);
scheduler_->refreshSubListTask_.reset();
scheduler_->notifyEngine();
scheduler_->notifyUi();
return;
}
int idx = 0;
for (list<shared_ptr<FmTask>>::iterator it = scheduler_->tasks_.begin(); it != scheduler_->tasks_.end(); it++, idx++)
{
FmTask *t = (*it).get();
parentDlg_->listTask_->rows_.push_back(EuhatListCtrl::Row());
EuhatListCtrl::Row &row = parentDlg_->listTask_->rows_.back();
row.height_ = 18;
row.cells_.push_back(EuhatListCtrl::Cell(t->id_));
string name;
string detail;
if (t->type_ == FmTask::TypeGetSubList || t->type_ == FmTask::TypeGetPeerSubList)
{
FmTaskGetSubList *task = (FmTaskGetSubList *)t;
name = task->path_.get();
if (task->result_ == FmResultOk)
detail = "refreshing...";
else
detail = "open failed.";
}
else if (t->type_ == FmTask::TypeDownload)
{
FmTaskDownload *task = (FmTaskDownload *)t;
name = task->localPath_.get();
if (task->offset_ < 0)
detail = "downloading...";
else
{
if (task->result_ == FmResultOk)
{
double percent = 100.0 * (task->offset_ + task->eatGuess_) / task->totalFileSize_;
char buf[1024];
sprintf(buf, "downloading %.02f%%", (float)percent);
detail = buf;
}
else
{
detail = "downloading failed.";
}
}
}
else if (t->type_ == FmTask::TypeUpload)
{
FmTaskUpload *task = (FmTaskUpload *)t;
name = task->localPath_.get();
if (task->offset_ < 0)
detail = "uploading...";
else
{
if (task->result_ == FmResultOk)
{
double percent = 100.0 * (task->offset_ + task->eatGuess_) / task->totalFileSize_;
char buf[1024];
sprintf(buf, "uploading %.02f%%", (float)percent);
detail = buf;
}
else
{
detail = "uploading failed.";
}
}
}
else if (t->type_ == FmTask::TypeCopy || t->type_ == FmTask::TypeCopyPeer)
{
FmTaskCopy *task = (FmTaskCopy *)t;
name = task->toPath_.get();
detail = "copying...";
}
else if (t->type_ == FmTask::TypeDel || t->type_ == FmTask::TypeDelPeer)
{
FmTaskDel *task = (FmTaskDel *)t;
name = task->path_.get();
if (task->result_ != FmResultOk)
detail = "deleting failed.";
else
detail = "deleting...";
}
else if (t->type_ == FmTask::TypeNew || t->type_ == FmTask::TypeNewPeer)
{
FmTaskNew *task = (FmTaskNew *)t;
name = task->path_.get();
if (task->result_ != FmResultOk)
detail = "creating failed.";
else
detail = "creating...";
}
else if (t->type_ == FmTask::TypeConnect)
{
FmTaskConnect *task = (FmTaskConnect *)t;
name = "Connecting " + task->ip_ + ":" + intToString(task->port_) + "...";
if (task->retryTimes_ > 0)
{
detail = "retry times: ";
detail += intToString(task->retryTimes_);
}
else if (task->retryTimes_ < 0)
{
if (task->result_ == FmResultVisitCodeMismatch)
detail = "visit code mismatch.";
else
detail = "connected.";
}
}
if (idx > 100)
{
char buf[1024];
sprintf(buf, "%d tasks left not shown...", scheduler_->tasks_.size() - idx);
row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(buf).c_str()));
break;
}
row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(name.c_str()).c_str()));
row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(detail.c_str()).c_str()));
}
EuhatRect rc;
::GetClientRect(parentDlg_->listTask_->hwnd_, &rc.rc_);
parentDlg_->listTask_->vscroller_->setRange(parentDlg_->listTask_->getLogicalHeight(), rc.height());
::InvalidateRect(parentDlg_->listTask_->hwnd_, NULL, 0);
}
void FileManSubDlg::fmscOnGetSysInfo(JyMsgLoop *loop, JyDataReadStream &ds)
{
char *hostName = ds.getStr();
dlgRemote_->curDir_.isUnix_ = ds.get<short>();
remote_->isUnix_ = dlgRemote_->curDir_.isUnix_;
browserDir(loop, ds.getStr());
FileManDlg *mainDlg = parentDlg_;
mainDlg->cfgDlg_->saveData(hostName);
mainDlg->cfgDlg_->dataToUi();
mainDlg->parentDlg_->leftDlg_->modifyItem(mainDlg->parentDlg_, hostName);
}
void FileManSubDlg::OnBnClickedBtnConnect()
{
parentDlg_->connect();
}
void FileManSubDlg::newFolder(JyMsgLoop *loop)
{
}
void FileManSubDlg::delFile(JyMsgLoop *loop)
{
scheduler_->cleanError();
EuhatPath parentDir;
EuhatListCtrl *listCtrl;
if (loop == remote_.get())
{
parentDir = dlgRemote_->curDir_;
listCtrl = dlgRemote_->listCtrl_.get();
}
else
{
parentDir = dlgLocal_->curDir_;
listCtrl = dlgLocal_->listCtrl_.get();
}
if (!parentDir.isUnix_ && parentDir.path_.size() <= 0)
return;
int isToGo = 0;
for (auto it = listCtrl->rows_.begin(); it != listCtrl->rows_.end(); it++)
{
if (!it->isSelected_)
continue;
if (!isToGo)
{
if (IDOK == MessageBox(_T("Are you sure to delete?"), _T("Warning"), MB_OKCANCEL))
{
isToGo = 1;
}
else
{
return;
}
}
string fileName = wstrToUtf8(it->cells_.front().value_.get());
if (it->cells_.size() <= 1)
{
shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList));
parentDir.goSub(fileName.c_str());
task->path_.reset(opStrDup(parentDir.toStr().c_str()));
parentDir.goUp();
task->action_ = FmTaskGetSubList::ActionDel;
scheduler_->add(task);
}
else
{
shared_ptr<FmTaskDel> task(new FmTaskDel(loop == remote_.get()? FmTask::TypeDelPeer : FmTask::TypeDel));
parentDir.goSub(fileName.c_str());
task->path_.reset(opStrDup(parentDir.toStr().c_str()));
parentDir.goUp();
task->isFolder_ = 0;
task->priority_ = 100;
scheduler_->add(task);
}
}
shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList));
task->path_.reset(opStrDup(parentDir.toStr().c_str()));
task->action_ = FmTaskGetSubList::ActionInformUi;
scheduler_->addRefreshTask(task);
scheduler_->notifyEngine();
fmscOnRefresh();
}
void FileManSubDlg::transfer(int isDownload, int isMove)
{
scheduler_->cleanError();
EuhatPath euLocal = dlgLocal_->curDir_;
if (!euLocal.isUnix_ && euLocal.path_.size() <= 0)
return;
EuhatPath euPeer = dlgRemote_->curDir_;
if (!euPeer.isUnix_ && euPeer.path_.size() <= 0)
return;
EuhatListCtrl *listFrom;
EuhatListCtrl *listTo;
if (isDownload)
{
listFrom = dlgRemote_->listCtrl_.get();
listTo = dlgLocal_->listCtrl_.get();
}
else
{
listFrom = dlgLocal_->listCtrl_.get();
listTo = dlgRemote_->listCtrl_.get();
}
list<EuhatListCtrl::Row *> rowsFrom;
list<EuhatListCtrl::Row *> rowsAnd;
for (auto it = listFrom->rows_.begin(); it != listFrom->rows_.end(); it++)
{
if (!it->isSelected_)
continue;
rowsFrom.push_back(&*it);
}
for (auto itTo = listTo->rows_.begin(); itTo != listTo->rows_.end(); itTo++)
{
for (auto itFrom = rowsFrom.begin(); itFrom != rowsFrom.end(); itFrom++)
{
wchar_t *strFrom = (*itFrom)->cells_.front().value_.get();
wchar_t *strTo = itTo->cells_.front().value_.get();
if (opStrCmpNoCase(strFrom, strTo) == 0)
{
rowsAnd.push_back(*itFrom);
}
}
}
if (rowsAnd.size() > 0)
{
wstring txt = L"Below files will be overwritten, Are you sure?\n";
int idx = 0;
list<EuhatListCtrl::Row *>::iterator it;
for (it = rowsAnd.begin(); it != rowsAnd.end() && idx < 5; it++, idx++)
{
txt += L"\n\t";
txt += (*it)->cells_.front().value_.get();
}
if (it != rowsAnd.end())
txt += L"\n\t...";
if (IDOK != MessageBox(txt.c_str(), L"Warning", MB_OKCANCEL))
{
return;
}
}
for (auto it = rowsFrom.begin(); it != rowsFrom.end(); it++)
{
if (!(*it)->isSelected_)
continue;
string fileName = wstrToUtf8((*it)->cells_.front().value_.get());
if ((*it)->cells_.size() <= 1)
{
shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(isDownload? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList));
euLocal.goSub(fileName.c_str());
if (isDownload)
task->peerPath_.reset(opStrDup(euLocal.toStr().c_str()));
else
task->path_.reset(opStrDup(euLocal.toStr().c_str()));
euLocal.goUp();
euPeer.goSub(fileName.c_str());
if (isDownload)
task->path_.reset(opStrDup(euPeer.toStr().c_str()));
else
task->peerPath_.reset(opStrDup(euPeer.toStr().c_str()));
euPeer.goUp();
task->action_ = FmTaskGetSubList::ActionDownUp;
task->isMove_ = isMove;
scheduler_->add(task);
}
else
{
shared_ptr<FmTaskDownload> task(isDownload ? new FmTaskDownload() : new FmTaskUpload());
euLocal.goSub(fileName.c_str());
task->localPath_.reset(opStrDup(euLocal.toStr().c_str()));
euLocal.goUp();
euPeer.goSub(fileName.c_str());
task->peerPath_.reset(opStrDup(euPeer.toStr().c_str()));
euPeer.goUp();
task->isMove_ = isMove;
auto cellIt = (*it)->cells_.begin();
cellIt++;
task->totalFileSize_ = cellIt->i_;
cellIt++;
cellIt++;
task->lastWriteTime_ = cellIt->i_;
task->offset_ = -1;
scheduler_->add(task);
}
}
shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(isDownload ? FmTask::TypeGetSubList : FmTask::TypeGetPeerSubList));
if (isDownload)
task->path_.reset(opStrDup(euLocal.toStr().c_str()));
else
task->path_.reset(opStrDup(euPeer.toStr().c_str()));
task->action_ = FmTaskGetSubList::ActionInformUi;
scheduler_->addRefreshTask(task);
scheduler_->notifyEngine();
fmscOnRefresh();
}
void FileManSubDlg::OnBnClickedBtnRemoteCopyToLocal()
{
transfer(1, 0);
}
void FileManSubDlg::OnBnClickedBtnLocalCopyToRemote()
{
transfer(0, 0);
}
void FileManSubDlg::OnBnClickedBtnRemoteMoveToLocal()
{
transfer(1, 1);
}
void FileManSubDlg::OnBnClickedBtnLocalMoveToRemote()
{
transfer(0, 1);
}
void FileManSubDlg::OnBnClickedBtnCopyClipboardToRemote()
{
EuhatPath localPath;
localPath.isUnix_ = dlgLocal_->curDir_.isUnix_;
string dir = "clipboard";
localPath.goSub(dir.c_str());
string fileName = "client.txt";
localPath.goSub(fileName.c_str());
opMkDir(dir.c_str());
string localPathStr = localPath.toStr();
HWND hWnd = GetSafeHwnd();
::OpenClipboard(hWnd);
HANDLE hClipMemory = ::GetClipboardData(CF_UNICODETEXT);
DWORD dwLength = GlobalSize(hClipMemory);
LPBYTE lpClipMemory = (LPBYTE)GlobalLock(hClipMemory);
string utf8Buf = wstrToUtf8((wchar_t *)lpClipMemory);
memToFile(localPathStr.c_str(), (char*)utf8Buf.c_str(), utf8Buf.length());
GlobalUnlock(hClipMemory);
::CloseClipboard();
EuhatPath remotePath;
remotePath.isUnix_ = dlgRemote_->curDir_.isUnix_;
remotePath.goSub(dir.c_str());
remotePath.goSub(fileName.c_str());
shared_ptr<FmTaskDownload> task(new FmTaskUpload());
task->localPath_.reset(opStrDup(localPathStr.c_str()));
task->peerPath_.reset(opStrDup(remotePath.toStr(0).c_str()));
task->totalFileSize_ = whGetFileSize(localPathStr.c_str());
task->lastWriteTime_ = time(NULL);
task->offset_ = -1;
scheduler_->add(task);
scheduler_->notifyEngine();
fmscOnRefresh();
}
void FileManSubDlg::OnBnClickedBtnCopyClipboardFromRemote()
{
EuhatPath localPath;
localPath.isUnix_ = dlgLocal_->curDir_.isUnix_;
string dir = "clipboard";
localPath.goSub(dir.c_str());
string fileName = "server.txt";
localPath.goSub(fileName.c_str());
opMkDir(dir.c_str());
string localPathStr = localPath.toStr();
opUnlink(localPathStr.c_str());
EuhatPath remotePath;
remotePath.isUnix_ = dlgRemote_->curDir_.isUnix_;
remotePath.goSub(dir.c_str());
remotePath.goSub(fileName.c_str());
shared_ptr<FmTaskDownload> task(new FmTaskDownload());
task->localPath_.reset(opStrDup(localPathStr.c_str()));
task->peerPath_.reset(opStrDup(remotePath.toStr(0).c_str()));
task->totalFileSize_ = 0;
task->lastWriteTime_ = time(NULL);
task->offset_ = -1;
scheduler_->add(task);
scheduler_->notifyEngine();
fmscOnRefresh();
}
void FileManSubDlg::onClipboardFileComing()
{
EuhatPath localPath;
localPath.isUnix_ = dlgLocal_->curDir_.isUnix_;
string dir = "clipboard";
localPath.goSub(dir.c_str());
string fileName = "server.txt";
localPath.goSub(fileName.c_str());
opMkDir(dir.c_str());
string localPathStr = localPath.toStr();
if (!doesFileExist(localPathStr.c_str()))
return;
unsigned int len;
unique_ptr<char[]> buf(memFromWholeFile(localPathStr.c_str(), &len));
wstring wstrBuf = utf8ToWstr(buf.get());
len = (wstrBuf.length() + 1) * sizeof(wchar_t);
HANDLE hGlobalMemory = GlobalAlloc(GHND, len + 1);
LPBYTE lpGlobalMemory = (LPBYTE)GlobalLock(hGlobalMemory);
memcpy(lpGlobalMemory, wstrBuf.c_str(), len);
GlobalUnlock(hGlobalMemory);
HWND hWnd = GetSafeHwnd();
::OpenClipboard(hWnd);
::EmptyClipboard();
::SetClipboardData(CF_UNICODETEXT, hGlobalMemory);
::CloseClipboard();
opUnlink(localPathStr.c_str());
}
| 26.958065
| 136
| 0.698875
|
euhat
|
0288d98acb7eb8d694d664c6cd7fc5dc8baf8af8
| 1,175
|
hpp
|
C++
|
src/JMParser.hpp
|
iCurlmyster/JMLang
|
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
|
[
"MIT"
] | null | null | null |
src/JMParser.hpp
|
iCurlmyster/JMLang
|
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
|
[
"MIT"
] | null | null | null |
src/JMParser.hpp
|
iCurlmyster/JMLang
|
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
|
[
"MIT"
] | null | null | null |
#ifndef JMPARSER_HPP
#define JMPARSER_HPP
#include <string>
#include <vector>
#include "JMTypes.h"
namespace JM {
class Parser
{
/**
* Instance variable to hold the current string being parsed.
* @type std::string
*/
std::string parsedString;
/**
* Instance variable to hold the current Type the parsedString is.
* @type JMType
*/
JMType currentType;
public:
Parser();
~Parser();
/**
* Method to set parsedString variable with string passed
* as parameter and then match the type of what the string is and
* set the currentType variable to the corresponding type.
*
* @param line std::string
* @return JMType
*/
JMType evaluateParse(std::string line);
/**
* Method to return the current string thats held by this class
* broken up by what type it is.
*
* @return std::vector<std::string>
*/
std::vector<std::string> returnParsedString();
/**
* Method to split a string into a std::vector by a specfied delimiter.
*
* @param line std::string
* @param del std::string
* @return std::vector<std::string>
*/
static std::vector<std::string> split(std::string line, std::string del);
};
}
#endif
| 20.258621
| 75
| 0.67234
|
iCurlmyster
|
0289b5f250b067f6fcf14d97a0f4b9525b403928
| 3,257
|
cc
|
C++
|
base-usage/cplusplus/test_thread.cc
|
sczzq/symmetrical-spoon
|
aa0c27bb40a482789c7c6a7088307320a007b49b
|
[
"Unlicense"
] | null | null | null |
base-usage/cplusplus/test_thread.cc
|
sczzq/symmetrical-spoon
|
aa0c27bb40a482789c7c6a7088307320a007b49b
|
[
"Unlicense"
] | null | null | null |
base-usage/cplusplus/test_thread.cc
|
sczzq/symmetrical-spoon
|
aa0c27bb40a482789c7c6a7088307320a007b49b
|
[
"Unlicense"
] | null | null | null |
#include <inttypes.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <string>
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
#define OS_LINUX
#if defined(OS_LINUX)
#include <dirent.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#endif // !OS_LINUX
using namespace std;
inline bool IsLittleEndian() {
uint32_t x = 1;
return *reinterpret_cast<char*>(&x) != 0;
}
static std::atomic<int>& ShouldSecondaryWait() {
static std::atomic<int> should_secondary_wait{1};
return should_secondary_wait;
}
static std::string Key(uint64_t k) {
std::string ret;
if (IsLittleEndian()) {
ret.append(reinterpret_cast<char*>(&k), sizeof(k));
} else {
char buf[sizeof(k)];
buf[0] = k & 0xff;
buf[1] = (k >> 8) & 0xff;
buf[2] = (k >> 16) & 0xff;
buf[3] = (k >> 24) & 0xff;
buf[4] = (k >> 32) & 0xff;
buf[5] = (k >> 40) & 0xff;
buf[6] = (k >> 48) & 0xff;
buf[7] = (k >> 56) & 0xff;
ret.append(buf, sizeof(k));
}
size_t i = 0, j = ret.size() - 1;
while (i < j) {
char tmp = ret[i];
ret[i] = ret[j];
ret[j] = tmp;
++i;
--j;
}
return ret;
}
static uint64_t Key(std::string key) {
assert(key.size() == sizeof(uint64_t));
size_t i = 0, j = key.size() - 1;
while (i < j) {
char tmp = key[i];
key[i] = key[j];
key[j] = tmp;
++i;
--j;
}
uint64_t ret = 0;
if (IsLittleEndian()) {
memcpy(&ret, key.c_str(), sizeof(uint64_t));
} else {
const char* buf = key.c_str();
ret |= static_cast<uint64_t>(buf[0]);
ret |= (static_cast<uint64_t>(buf[1]) << 8);
ret |= (static_cast<uint64_t>(buf[2]) << 16);
ret |= (static_cast<uint64_t>(buf[3]) << 24);
ret |= (static_cast<uint64_t>(buf[4]) << 32);
ret |= (static_cast<uint64_t>(buf[5]) << 40);
ret |= (static_cast<uint64_t>(buf[6]) << 48);
ret |= (static_cast<uint64_t>(buf[7]) << 56);
}
return ret;
}
void secondary_instance_sigint_handler(int signal) {
ShouldSecondaryWait().store(0, std::memory_order_relaxed);
fprintf(stdout, "\n");
fflush(stdout);
};
void RunSecondary() {
::signal(SIGINT, secondary_instance_sigint_handler);
long my_pid = static_cast<long>(getpid());
std::vector<std::thread> test_threads;
auto helper = [&]()
{
std::srand(time(nullptr));
int count = 0;
int kMaxKey = 12345667;
while (1 == ShouldSecondaryWait().load(std::memory_order_relaxed)) {
uint64_t curr_key = std::rand() % kMaxKey;
count++;
fprintf(stderr, "count: %d, key: %llu\n", count, curr_key);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
fprintf(stdout, "[process %ld] Point lookup thread finished\n", my_pid);
};
test_threads.emplace_back(helper);
test_threads.emplace_back(helper);
test_threads.emplace_back(helper);
test_threads.emplace_back(helper);
test_threads.emplace_back(helper);
while (1 == ShouldSecondaryWait().load(std::memory_order_relaxed)) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
for (auto& thr : test_threads) {
thr.join();
}
}
int main(int argc, char** argv) {
RunSecondary();
return 0;
}
| 24.30597
| 76
| 0.61529
|
sczzq
|
028bc7541879411c849c8e67746d3f439745f7a8
| 937
|
hpp
|
C++
|
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
|
Scapior/KompotEngine
|
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
|
[
"MIT"
] | null | null | null |
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
|
Scapior/KompotEngine
|
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
|
[
"MIT"
] | 36
|
2020-10-14T15:17:46.000Z
|
2022-02-07T22:10:54.000Z
|
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
|
Scapior/KompotEngine
|
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
|
[
"MIT"
] | 1
|
2019-05-12T16:59:50.000Z
|
2019-05-12T16:59:50.000Z
|
/*
* RenderingCommon.hpp
* Copyright (C) 2021 by Maxim Stoianov
* Licensed under the MIT license.
*/
#pragma once
#include <string_view>
namespace Kompot
{
class Window;
}
namespace Kompot::Rendering
{
struct WindowRendererAttributes
{
virtual ~WindowRendererAttributes()
{
}
};
enum class ShaderType
{
Vertex,
Fragment,
Compute
};
class IShader
{
public:
virtual ~IShader(){};
virtual std::string_view getSourceFilename() const = 0;
};
class IRenderer
{
public:
virtual ~IRenderer(){};
virtual void draw(Window* window) = 0;
virtual void notifyWindowResized(Window* window) = 0;
virtual WindowRendererAttributes* updateWindowAttributes(Window* window) = 0;
virtual void unregisterWindow(Window* window) = 0;
virtual std::string_view getName() const = 0;
};
} // namespace Kompot
| 17.351852
| 81
| 0.629669
|
Scapior
|
028d25724e5d7df7470a92a80d20211526021349
| 3,715
|
hpp
|
C++
|
source/utils.hpp
|
albanbruder/BruderAlban_119902_Assignment5
|
9cfea32263feef896e2780dffb0726c008e899d4
|
[
"MIT"
] | null | null | null |
source/utils.hpp
|
albanbruder/BruderAlban_119902_Assignment5
|
9cfea32263feef896e2780dffb0726c008e899d4
|
[
"MIT"
] | null | null | null |
source/utils.hpp
|
albanbruder/BruderAlban_119902_Assignment5
|
9cfea32263feef896e2780dffb0726c008e899d4
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <math.h>
#include "line.hpp"
#include "segment.hpp"
/**
* Checks if a point p is in the bounding box spanned by points a and b.
*/
bool between(Point const& p, Point const& a, Point const& b) {
// check for x-coordinates
if(p.x < std::min(a.x, b.x) || p.x > std::max(a.x, b.x)) {
return false;
}
// check for y-coordinates
if(p.y < std::min(a.y, b.y) || p.y > std::max(a.y, b.y)) {
return false;
}
return true;
}
/**
* Intersects 2 lines. (not segments)
* Returns the point of intersection or a point with x and y set to infinity.
*/
Point intersect(Line const& line1, Line const& line2) {
// a1*x + b1*y = c1
float a1 = line1.b.y - line1.a.y;
float b1 = line1.a.x - line1.b.x;
float c1 = a1*line1.a.x + b1*line1.a.y;
// a2*x + b2*y = c2
float a2 = line2.b.y - line2.a.y;
float b2 = line2.a.x - line2.b.x;
float c2 = a2*line2.a.x + b2*line2.a.y;
float det = a1*b2 - a2*b1;
// lines are parallel
if(det == 0) {
return Point();
}
float x = (b2*c1 - b1*c2) / det;
float y = (a1*c2 - a2*c1) / det;
return Point{ x, y };
}
/**
* Intersects a line and a segment.
* Returns the point of intersection or a point with x and y set to infinity.
*/
Point intersect(Line const& line, Segment const& segment) {
Point intersection = intersect(line, Line{ segment.a, segment.b });
if(!between(intersection, segment.a, segment.b)) {
return Point();
} else {
return intersection;
}
}
/**
* Intersect 2 segments.
*/
Point intersect(Segment const& segment1, Segment const& segment2)
{
Point intersection = intersect(Line{ segment1.a, segment1.b }, segment2);
// check for both segments if Point(x,y) is between Point a and b
if(!between(intersection, segment1.a, segment1.b)) {
return Point();
} else {
return intersection;
}
}
/**
* Generate a random Point.
*/
Point generateRandomPoint(int minX, int maxX, int minY, int maxY)
{
float x = minX + std::rand() % (( maxX + 1 ) - minX);
float y = minY + std::rand() % (( maxY + 1 ) - minY);
return Point{x, y};
}
/**
* Generate a random vector of segments.
*/
std::vector<Segment> generateRandomSegements(unsigned int n, int minX, int maxX, int minY, int maxY)
{
// initialize the randomizer
srand(time(0));
std::vector<Point> points;
std::vector<Segment> segments;
// as long as the list is not full
while(segments.size() < n) {
Point a = generateRandomPoint(minX, maxX, minY, maxY);
Point b = generateRandomPoint(minX, maxX, minY, maxY);
// check if line is vertical
// or inverse
if(a.x >= b.x) {
continue;
}
// check if one of the points already exists
auto it = std::find_if(std::cbegin(points), std::cend(points), [a, b](Point const& p) {
return a.x == p.x || b.x == p.x;
});
if(it != std::cend(points)) {
continue;
}
/* std::vector<Point> intersections;
bool duplicateFound = false;
for(auto seg : segments) {
Point intersection = intersect(seg, Segment{a, b});
if(isinf(intersection.x)) {
continue;
}
auto it = std::find_if(std::cbegin(intersections), std::cend(intersections), [intersection](Point const& p) {
return p.x == intersection.x;
});
if(it != std::cend(intersections)) {
duplicateFound = true;
} else {
intersections.push_back(intersection);
}
}
if(duplicateFound) {
continue;
}
points.push_back(a);
points.push_back(b);
for(auto p : intersections) {
points.push_back(p);
} */
segments.push_back({ a, b });
}
return segments;
}
| 23.814103
| 115
| 0.607268
|
albanbruder
|
028d72478ee03fe80f132207cdc39cf07d68c7fa
| 2,293
|
hpp
|
C++
|
stan/math/prim/meta/is_constant.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/prim/meta/is_constant.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
stan/math/prim/meta/is_constant.hpp
|
kedartal/math
|
77248cf73c1110660006c9700f78d9bb7c02be1d
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MATH_PRIM_META_IS_CONSTANT_HPP
#define STAN_MATH_PRIM_META_IS_CONSTANT_HPP
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/bool_constant.hpp>
#include <stan/math/prim/meta/conjunction.hpp>
#include <stan/math/prim/meta/is_vector.hpp>
#include <stan/math/prim/meta/require_generics.hpp>
#include <type_traits>
#include <vector>
namespace stan {
/** \ingroup type_trait
* Metaprogramming struct to detect whether a given type is constant
* in the mathematical sense (not the C++ <code>const</code>
* sense). If the parameter type is constant, <code>value</code>
* will be equal to <code>true</code>.
*
* The baseline implementation in this abstract base class is to
* classify a type <code>T</code> as constant if it can be converted
* (i.e., assigned) to a <code>double</code>. This baseline should
* be overridden for any type that should be treated as a variable.
*
* @tparam T Type being tested.
*/
template <typename T, typename = void>
struct is_constant : bool_constant<std::is_convertible<T, double>::value> {};
/** \ingroup type_trait
* Metaprogram defining an enum <code>value</code> which
* is <code>true</code> if all of the type parameters
* are constant (i.e., primtive types) and
* <code>false</code> otherwise.
*/
template <typename... T>
using is_constant_all = math::conjunction<is_constant<T>...>;
/** \ingroup type_trait
* Defines a static member named value and sets it to true
* if the type of the elements in the provided std::vector
* is constant, false otherwise. This is used in
* the is_constant_all metaprogram.
* @tparam type of the elements in the std::vector
*/
template <typename T>
struct is_constant<T, require_std_vector_t<T>>
: bool_constant<is_constant<typename std::decay_t<T>::value_type>::value> {
};
/** \ingroup type_trait
* Defines a public enum named value and sets it to true
* if the type of the elements in the provided Eigen Matrix
* is constant, false otherwise. This is used in
* the is_constant_all metaprogram.
*
* @tparam T type of the Eigen Matrix
*/
template <typename T>
struct is_constant<T, require_eigen_t<T>>
: bool_constant<is_constant<typename std::decay_t<T>::Scalar>::value> {};
} // namespace stan
#endif
| 35.276923
| 79
| 0.73877
|
kedartal
|
028e4a951c4340e2adc3ea867763a7a604804e74
| 9,052
|
cpp
|
C++
|
cwinte.cpp
|
dylancarlson/citplus
|
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
|
[
"Unlicense"
] | 1
|
2020-08-11T06:12:01.000Z
|
2020-08-11T06:12:01.000Z
|
cwinte.cpp
|
dylancarlson/citplus
|
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
|
[
"Unlicense"
] | null | null | null |
cwinte.cpp
|
dylancarlson/citplus
|
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
|
[
"Unlicense"
] | null | null | null |
// --------------------------------------------------------------------------
// Citadel: CWinTE.CPP
//
// Citadel Windows Text Editor
#ifndef WINCIT
#include "ctdl.h"
#pragma hdrstop
#include "cwindows.h"
// --------------------------------------------------------------------------
// Contents
Bool teHandler(EVENT evt, long param, int more, CITWINDOW *wnd)
{
switch (evt)
{
case EVT_ISCTRLID:
{
return (((TEINFO *)(wnd->LocalData))->ci.id == more);
}
case EVT_NEWWINDOW:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
te->end = strlen((char *)(te->ci.ptr));
te->cur = te->end;
while (te->cur - te->start > wnd->extents.right -
wnd->extents.left - 1)
{
te->start++;
}
break;
}
case EVT_LOSTFOCUS: // when losing focus, return cursor
{
TEINFO *te = (TEINFO *) wnd->LocalData;
CitWindowsCsr = FALSE;
cursoff();
position(logiRow, logiCol);
te->focused = FALSE;
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
break;
}
case EVT_GOTFOCUS: // when getting focus, capture cursor
{
TEINFO *te = (TEINFO *) wnd->LocalData;
CitWindowsCsr = TRUE;
te->focused = TRUE;
physPosition((uchar) wnd->parent->extents.top + wnd->extents.top,
(uchar) wnd->parent->extents.left + wnd->extents.left +
te->cur - te->start);
if (!wnd->parent->flags.minimized)
{
if (te->ins)
{
curshalf();
}
else
{
curson();
}
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
break;
}
case EVT_DESTROY:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->ci.ptr)
{
freeMemG(te->ci.ptr);
te->ci.ptr = NULL;
}
if (te->ci.more)
{
freeMemG(te->ci.more);
te->ci.more = NULL;
}
break;
}
case EVT_DRAWINT:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
SRECT pr = wnd->parent->extents;
SRECT r = wnd->extents;
int attr;
if (te->focused)
{
physPosition((uchar) wnd->parent->extents.top + wnd->extents.top,
(uchar) wnd->parent->extents.left + wnd->extents.left +
te->cur - te->start);
attr = cfg.cattr;
}
else
{
attr = cfg.attr;
}
wnd->parent->extents.right = wnd->parent->extents.left + r.right;
wnd->parent->extents.bottom = wnd->parent->extents.top + r.bottom;
wnd->parent->extents.top += r.top;
wnd->parent->extents.left += r.left;
if (buildClipArray(wnd->parent))
{
int i;
if (te->usenopwecho)
{
char Output;
if (cfg.nopwecho == 1) // Nothing (actually, spaces for us)
{
Output = 0;
}
else if (cfg.nopwecho) // Echo character (count if digit)
{
Output = cfg.nopwecho;
}
for (i = 0; i < te->end - te->start; i++)
{
char ToOutput;
if (!cfg.nopwecho) // Echo it
{
ToOutput = ((char *)(te->ci.ptr))[te->start + i];
}
else // Echo mask
{
// if digit - count (this is really stupid: it
// should happen after the assignment. However,
// we don't set the precedent here. That's in
// getString()...
if (isdigit(Output))
{
Output++;
if (!isdigit(Output))
{
Output = '0';
}
}
ToOutput = Output;
}
CitWindowOutChr(wnd->parent, i, 0, ToOutput, attr);
}
}
else
{
CitWindowOutStr(wnd->parent, 0, 0,
(char *)(te->ci.ptr) + te->start, attr);
}
for (i = te->end - te->start; i < r.right - r.left; i++)
{
CitWindowOutChr(wnd->parent, i, 0, ' ', cfg.attr);
}
freeClipArray();
}
wnd->parent->extents = pr;
break;
}
case EVT_INKEY:
{
if (param == 13) // return string
{
TEINFO *te = (TEINFO *) wnd->LocalData;
normalizeString((char *) te->ci.ptr);
(wnd->parent->func)(EVT_CTRLRET, (long) &(te->ci),
0, wnd->parent);
return (TRUE);
}
else if (param == ESC) // abort edit
{
destroyCitWindow(wnd->parent, FALSE);
return (TRUE);
}
else if (param == 8) // backspace
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur)
{
int i;
te->cur--;
te->end--;
if (te->cur < te->start)
{
te->start = te->cur;
}
for (i = te->cur; ((char *)(te->ci.ptr))[i]; i++)
{
((char *)(te->ci.ptr))[i] =
((char *)(te->ci.ptr))[i + 1];
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
else if (param < 256 && param > 31) // add to string
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if ((te->cur < te->len) && (!te->ins || (te->end < te->len)))
{
if (te->ins)
{
int i;
((char *)(te->ci.ptr))[te->end + 1] = 0;
for (i = te->end; i != te->cur; i--)
{
((char *)(te->ci.ptr))[i] =
((char *)(te->ci.ptr))[i - 1];
}
}
((char *)(te->ci.ptr))[te->cur] = (char) param;
te->cur++;
if (te->cur > te->end || te->ins)
{
te->end++;
}
while (te->cur - te->start > wnd->extents.right -
wnd->extents.left - 1)
{
te->start++;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
else if (param > 255)
{
switch (param >> 8)
{
case CURS_DEL:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur != te->end)
{
int i;
for (i = te->cur; ((char *)(te->ci.ptr))[i]; i++)
{
((char *)(te->ci.ptr))[i] =
((char *)(te->ci.ptr))[i + 1];
}
te->end--;
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
case CURS_INS:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
te->ins = !te->ins;
if (!wnd->parent->flags.minimized)
{
if (te->ins)
{
curshalf();
}
else
{
curson();
}
}
return (TRUE);
}
case CTL_CURS_LEFT:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur)
{
// eat up space
while (te->cur &&
isspace(((char *)(te->ci.ptr))[te->cur - 1]))
{
te->cur--;
}
// eat up word
while (te->cur &&
!isspace(((char *)(te->ci.ptr))[te->cur - 1]))
{
te->cur--;
}
if (te->cur < te->start)
{
te->start = te->cur;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
case CTL_CURS_RIGHT:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur < te->end)
{
// eat up word
while ((te->cur < te->end) &&
!isspace(((char *)(te->ci.ptr))[te->cur + 1]))
{
te->cur++;
}
// eat up space
while ((te->cur < te->end) &&
isspace(((char *)(te->ci.ptr))[te->cur + 1]))
{
te->cur++;
}
if (te->cur < te->end)
{
te->cur++;
}
while (te->cur - te->start >
wnd->extents.right -
wnd->extents.left - 1)
{
te->start++;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
case CURS_LEFT:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur)
{
te->cur--;
if (te->cur < te->start)
{
te->start = te->cur;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
case CURS_RIGHT:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
if (te->cur < te->end)
{
te->cur++;
while (te->cur - te->start >
wnd->extents.right -
wnd->extents.left - 1)
{
te->start++;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
}
return (TRUE);
}
case CURS_HOME:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
te->start = te->cur = 0;
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
return (TRUE);
}
case CURS_END:
{
TEINFO *te = (TEINFO *) wnd->LocalData;
te->end = strlen((char *)(te->ci.ptr));
te->cur = te->end;
while (te->cur - te->start >
wnd->extents.right - wnd->extents.left - 1)
{
te->start++;
}
(wnd->func)(EVT_DRAWINT, 0, 0, wnd);
return (TRUE);
}
}
}
return (FALSE);
}
default:
{
return (FALSE);
}
}
return (TRUE);
}
#endif
| 19.056842
| 78
| 0.422559
|
dylancarlson
|
028fc7c23e790ff567d5c756ef09fadbcf3eda44
| 1,324
|
cpp
|
C++
|
tests/test_silence_remover.cpp
|
CyberSinh/chromaprint
|
3dbc9adeec86f1bafc7a05969766562b9217deac
|
[
"MIT"
] | 582
|
2016-06-14T14:49:36.000Z
|
2022-03-27T16:17:57.000Z
|
tests/test_silence_remover.cpp
|
CyberSinh/chromaprint
|
3dbc9adeec86f1bafc7a05969766562b9217deac
|
[
"MIT"
] | 72
|
2016-07-28T14:27:55.000Z
|
2022-03-19T18:32:44.000Z
|
tests/test_silence_remover.cpp
|
CyberSinh/chromaprint
|
3dbc9adeec86f1bafc7a05969766562b9217deac
|
[
"MIT"
] | 102
|
2016-08-21T17:36:10.000Z
|
2022-02-13T15:35:44.000Z
|
#include <gtest/gtest.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include "test_utils.h"
#include "silence_remover.h"
#include "audio_buffer.h"
#include "utils.h"
using namespace chromaprint;
TEST(SilenceRemover, PassThrough)
{
short samples[] = { 1000, 2000, 3000, 4000, 5000, 6000 };
std::vector<short> data(samples, samples + NELEMS(samples));
AudioBuffer buffer;
SilenceRemover processor(&buffer);
processor.Reset(44100, 1);
processor.Consume(data.data(), data.size());
processor.Flush();
ASSERT_EQ(data.size(), buffer.data().size());
for (size_t i = 0; i < data.size(); i++) {
ASSERT_EQ(data[i], buffer.data()[i]) << "Signals differ at index " << i;
}
}
TEST(SilenceRemover, RemoveLeadingSilence)
{
short samples1[] = { 0, 60, 0, 1000, 2000, 0, 4000, 5000, 0 };
std::vector<short> data1(samples1, samples1 + NELEMS(samples1));
short samples2[] = { 1000, 2000, 0, 4000, 5000, 0 };
std::vector<short> data2(samples2, samples2 + NELEMS(samples2));
AudioBuffer buffer;
SilenceRemover processor(&buffer, 100);
processor.Reset(44100, 1);
processor.Consume(data1.data(), data1.size());
processor.Flush();
ASSERT_EQ(data2.size(), buffer.data().size());
for (size_t i = 0; i < data2.size(); i++) {
ASSERT_EQ(data2[i], buffer.data()[i]) << "Signals differ at index " << i;
}
}
| 27.583333
| 75
| 0.679758
|
CyberSinh
|
02950af9a8771f70640dd8f535517ebb3b106091
| 5,382
|
cpp
|
C++
|
EncoderOpus.cpp
|
dcealopez/VUPlayer
|
ff8a5032579a0adf01740e03a9067aa2875d7af1
|
[
"MIT"
] | 57
|
2017-06-05T00:10:05.000Z
|
2022-02-17T10:59:54.000Z
|
EncoderOpus.cpp
|
dcealopez/VUPlayer
|
ff8a5032579a0adf01740e03a9067aa2875d7af1
|
[
"MIT"
] | 26
|
2018-07-09T00:05:46.000Z
|
2021-12-30T22:50:24.000Z
|
EncoderOpus.cpp
|
dcealopez/VUPlayer
|
ff8a5032579a0adf01740e03a9067aa2875d7af1
|
[
"MIT"
] | 4
|
2019-07-31T13:31:51.000Z
|
2021-08-16T21:50:32.000Z
|
#include "EncoderOpus.h"
#include "Handler.h"
#include "Utility.h"
#include <vector>
// Minimum/maximum/default bit rates.
static const int s_MinimumBitrate = 8;
static const int s_MaximumBitrate = 256;
static const int s_DefaultBitrate = 128;
EncoderOpus::EncoderOpus() :
Encoder(),
m_Channels( 0 ),
m_OpusEncoder( nullptr ),
m_Callbacks( {} )
{
}
EncoderOpus::~EncoderOpus()
{
}
int EncoderOpus::WriteCallback( void *user_data, const unsigned char *ptr, opus_int32 len )
{
FILE* f = reinterpret_cast<FILE*>( user_data );
if ( ( nullptr != f ) && ( nullptr != ptr ) && ( len > 0 ) ) {
fwrite( ptr, 1, len, f );
}
return 0;
}
int EncoderOpus::CloseCallback( void *user_data )
{
FILE* f = reinterpret_cast<FILE*>( user_data );
if ( nullptr != f ) {
fclose( f );
}
return 0;
}
bool EncoderOpus::Open( std::wstring& filename, const long sampleRate, const long channels, const std::optional<long> /*bitsPerSample*/, const std::string& settings )
{
m_Channels = channels;
OggOpusComments* opusComments = ope_comments_create();
if ( nullptr != opusComments ) {
filename += L".opus";
FILE* f = _wfsopen( filename.c_str(), L"wb", _SH_DENYRW );
if ( nullptr != f ) {
m_Callbacks.write = WriteCallback;
m_Callbacks.close = CloseCallback;
m_OpusEncoder = ope_encoder_create_callbacks( &m_Callbacks, f /*userData*/, opusComments, sampleRate, channels, 0 /*family*/, nullptr /*error*/ );
if ( nullptr != m_OpusEncoder ) {
const int bitrate = 1000 * GetBitrate( settings );
ope_encoder_ctl( m_OpusEncoder, OPUS_SET_BITRATE( bitrate ) );
}
}
ope_comments_destroy( opusComments );
}
const bool success = ( nullptr != m_OpusEncoder );
return success;
}
bool EncoderOpus::Write( float* samples, const long sampleCount )
{
// For multi-channel streams, change from BASS to Opus channel ordering.
switch ( m_Channels ) {
case 3 : {
// (left, right, center) ->
// (left, center, right)
long offset = 0;
for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) {
std::swap( samples[ offset + 1 ], samples[ offset + 2 ] );
}
break;
}
case 5 : {
// (front left, front right, front center, rear left, rear right) ->
// (front left, front center, front right, rear left, rear right)
long offset = 0;
for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) {
std::swap( samples[ offset + 1 ], samples[ offset + 2 ] );
}
break;
}
case 6 : {
// (front left, front right, front center, LFE, rear left, rear right) ->
// (front left, front center, front right, rear left, rear right, LFE)
long offset = 0;
for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) {
std::swap( samples[ offset + 1 ], samples[ offset + 2 ] );
const float lfe = samples[ offset + 3 ];
const float rearL = samples[ offset + 4 ];
const float rearR = samples[ offset + 5 ];
samples[ offset + 3 ] = rearL;
samples[ offset + 4 ] = rearR;
samples[ offset + 5 ] = lfe;
}
break;
}
case 7 : {
// (front left, front right, front center, LFE, rear center, side left, side right) ->
// (front left, front center, front right, side left, side right, rear center, LFE)
long offset = 0;
for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) {
std::swap( samples[ offset + 1 ], samples[ offset + 2 ] );
const float lfe = samples[ offset + 3 ];
const float rearC = samples[ offset + 4 ];
const float sideL = samples[ offset + 5 ];
const float sideR = samples[ offset + 6 ];
samples[ offset + 3 ] = sideL;
samples[ offset + 4 ] = sideR;
samples[ offset + 5 ] = rearC;
samples[ offset + 6 ] = lfe;
}
break;
}
case 8 : {
// (front left, front right, front center, LFE, rear left, rear right, side left, side right) ->
// (front left, front center, front right, side left, side right, rear left, rear right, LFE)
long offset = 0;
for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) {
std::swap( samples[ offset + 1 ], samples[ offset + 2 ] );
const float lfe = samples[ offset + 3 ];
const float rearL = samples[ offset + 4 ];
const float rearR = samples[ offset + 5 ];
const float sideL = samples[ offset + 6 ];
const float sideR = samples[ offset + 7 ];
samples[ offset + 3 ] = sideL;
samples[ offset + 4 ] = sideR;
samples[ offset + 5 ] = rearL;
samples[ offset + 6 ] = rearR;
samples[ offset + 7 ] = lfe;
}
break;
}
default: {
break;
}
}
const bool success = ( OPE_OK == ope_encoder_write_float( m_OpusEncoder, samples, sampleCount ) );
return success;
}
void EncoderOpus::Close()
{
if ( nullptr != m_OpusEncoder ) {
ope_encoder_drain( m_OpusEncoder );
ope_encoder_destroy( m_OpusEncoder );
}
}
int EncoderOpus::GetBitrate( const std::string& settings )
{
int bitrate = s_DefaultBitrate;
try {
bitrate = std::stoi( settings );
} catch ( ... ) {
}
LimitBitrate( bitrate );
return bitrate;
}
int EncoderOpus::GetDefaultBitrate()
{
return s_DefaultBitrate;
}
int EncoderOpus::GetMinimumBitrate()
{
return s_MinimumBitrate;
}
int EncoderOpus::GetMaximumBitrate()
{
return s_MaximumBitrate;
}
void EncoderOpus::LimitBitrate( int& bitrate )
{
if ( bitrate < s_MinimumBitrate ) {
bitrate = s_MinimumBitrate;
} else if ( bitrate > s_MaximumBitrate ) {
bitrate = s_MaximumBitrate;
}
}
| 28.17801
| 166
| 0.63861
|
dcealopez
|
029dcd2075705ce8d975377091a9464af8e6fff7
| 6,343
|
cpp
|
C++
|
src/ftxui/component/component_options.cpp
|
VatamanuBogdan/FTXUI
|
62fb6298bef19618a43aff9f09401309c307a156
|
[
"MIT"
] | 1
|
2022-01-24T23:53:32.000Z
|
2022-01-24T23:53:32.000Z
|
src/ftxui/component/component_options.cpp
|
VatamanuBogdan/FTXUI
|
62fb6298bef19618a43aff9f09401309c307a156
|
[
"MIT"
] | null | null | null |
src/ftxui/component/component_options.cpp
|
VatamanuBogdan/FTXUI
|
62fb6298bef19618a43aff9f09401309c307a156
|
[
"MIT"
] | null | null | null |
#include "ftxui/component/component_options.hpp"
#include <memory> // for allocator, shared_ptr
#include "ftxui/component/animation.hpp" // for Function, Duration
#include "ftxui/dom/elements.hpp" // for Element, operator|, text, bold, dim, inverted, automerge
namespace ftxui {
void AnimatedColorOption::Set(Color a_inactive,
Color a_active,
animation::Duration a_duration,
animation::easing::Function a_function) {
enabled = true;
inactive = a_inactive;
active = a_active;
duration = a_duration;
function = a_function;
}
void UnderlineOption::SetAnimation(animation::Duration d,
animation::easing::Function f) {
SetAnimationDuration(d);
SetAnimationFunction(f);
}
void UnderlineOption::SetAnimationDuration(animation::Duration d) {
leader_duration = d;
follower_duration = d;
}
void UnderlineOption::SetAnimationFunction(animation::easing::Function f) {
leader_function = f;
follower_function = f;
}
void UnderlineOption::SetAnimationFunction(
animation::easing::Function f_leader,
animation::easing::Function f_follower) {
leader_function = f_leader;
follower_function = f_follower;
}
// static
MenuOption MenuOption::Horizontal() {
MenuOption option;
option.direction = Direction::Right;
option.entries.transform = [](EntryState state) {
Element e = text(state.label);
if (state.focused)
e |= inverted;
if (state.active)
e |= bold;
if (!state.focused && !state.active)
e |= dim;
return e;
};
option.elements_infix = [] { return text(" "); };
return option;
}
// static
MenuOption MenuOption::HorizontalAnimated() {
auto option = Horizontal();
option.underline.enabled = true;
return option;
}
// static
MenuOption MenuOption::Vertical() {
MenuOption option;
option.entries.transform = [](EntryState state) {
if (state.active)
state.label = "> " + state.label;
else
state.label = " " + state.label;
Element e = text(state.label);
if (state.focused)
e |= inverted;
if (state.active)
e |= bold;
if (!state.focused && !state.active)
e |= dim;
return e;
};
return option;
}
// static
MenuOption MenuOption::VerticalAnimated() {
auto option = MenuOption::Vertical();
option.entries.transform = [](EntryState state) {
Element e = text(state.label);
if (state.focused)
e |= inverted;
if (state.active)
e |= bold;
if (!state.focused && !state.active)
e |= dim;
return e;
};
option.underline.enabled = true;
return option;
}
// static
MenuOption MenuOption::Toggle() {
auto option = MenuOption::Horizontal();
option.elements_infix = [] { return text("│") | automerge; };
return option;
}
/// @brief Create a ButtonOption, highlighted using [] characters.
// static
ButtonOption ButtonOption::Ascii() {
ButtonOption option;
option.transform = [](EntryState s) {
s.label = s.focused ? "[" + s.label + "]" //
: " " + s.label + " ";
return text(s.label);
};
return option;
}
/// @brief Create a ButtonOption, inverted when focused.
// static
ButtonOption ButtonOption::Simple() {
ButtonOption option;
option.transform = [](EntryState s) {
auto element = text(s.label) | borderLight;
if (s.focused)
element |= inverted;
return element;
};
return option;
}
/// @brief Create a ButtonOption, using animated colors.
// static
ButtonOption ButtonOption::Animated() {
return Animated(Color::Black, Color::GrayLight, //
Color::GrayDark, Color::White);
}
/// @brief Create a ButtonOption, using animated colors.
// static
ButtonOption ButtonOption::Animated(Color color) {
return ButtonOption::Animated(Color::Interpolate(0.85f, color, Color::Black),
Color::Interpolate(0.10f, color, Color::White),
Color::Interpolate(0.10f, color, Color::Black),
Color::Interpolate(0.85f, color, Color::White));
}
/// @brief Create a ButtonOption, using animated colors.
// static
ButtonOption ButtonOption::Animated(Color background, Color foreground) {
return ButtonOption::Animated(background, foreground, foreground, background);
}
/// @brief Create a ButtonOption, using animated colors.
// static
ButtonOption ButtonOption::Animated(Color background,
Color foreground,
Color background_focused,
Color foreground_focused) {
ButtonOption option;
option.transform = [](EntryState s) {
auto element = text(s.label) | borderEmpty;
if (s.focused)
element |= bold;
return element;
};
option.animated_colors.foreground.Set(foreground, foreground_focused);
option.animated_colors.background.Set(background, background_focused);
return option;
}
/// @brief Option for standard Checkbox.
// static
CheckboxOption CheckboxOption::Simple() {
auto option = CheckboxOption();
option.transform = [](EntryState s) {
#if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK)
// Microsoft terminal do not use fonts able to render properly the default
// radiobox glyph.
auto prefix = text(s.state ? "[X] " : "[ ] ");
#else
auto prefix = text(s.state ? "▣ " : "☐ ");
#endif
auto t = text(s.label);
if (s.active)
t |= bold;
if (s.focused)
t |= inverted;
return hbox({prefix, t});
};
return option;
}
/// @brief Option for standard Radiobox
// static
RadioboxOption RadioboxOption::Simple() {
auto option = RadioboxOption();
option.transform = [](EntryState s) {
#if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK)
// Microsoft terminal do not use fonts able to render properly the default
// radiobox glyph.
auto prefix = text(s.state ? "(*) " : "( ) ");
#else
auto prefix = text(s.state ? "◉ " : "○ ");
#endif
auto t = text(s.label);
if (s.active)
t |= bold;
if (s.focused)
t |= inverted;
return hbox({prefix, t});
};
return option;
}
} // namespace ftxui
// Copyright 2022 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
| 27.69869
| 98
| 0.63976
|
VatamanuBogdan
|
029e698687a9d36ee1095d0ed42fd2d9c03112ad
| 4,960
|
cpp
|
C++
|
deprecated_compiler/src/StringReader.cpp
|
Limvot/kraken
|
6e5a372f07a864555c0e6492de4f46ffab75bfe7
|
[
"MIT"
] | 14
|
2015-12-28T10:33:33.000Z
|
2022-03-29T04:04:52.000Z
|
deprecated_compiler/src/StringReader.cpp
|
Limvot/kraken
|
6e5a372f07a864555c0e6492de4f46ffab75bfe7
|
[
"MIT"
] | 3
|
2016-04-20T23:10:09.000Z
|
2022-01-30T21:59:56.000Z
|
deprecated_compiler/src/StringReader.cpp
|
Limvot/kraken
|
6e5a372f07a864555c0e6492de4f46ffab75bfe7
|
[
"MIT"
] | 1
|
2016-04-20T01:02:53.000Z
|
2016-04-20T01:02:53.000Z
|
#include "StringReader.h"
#include <cassert>
StringReader::StringReader()
{
str_pos = 0;
}
StringReader::StringReader(std::string inputString)
{
str_pos = 0;
setString(inputString);
}
StringReader::~StringReader()
{
//dtor
}
void StringReader::setString(std::string inputString)
{
rd_string = inputString;
end_reached = false;
}
std::string StringReader::word(bool truncateEnd)
{
std::string result = getTokens(" \n\t", truncateEnd);
while (result == " " || result == "\n" || result == "\t")
{
result = getTokens(" \n\t", truncateEnd);
}
return(result);
}
std::string StringReader::line(bool truncateEnd)
{
return getTokens("\n", truncateEnd);
}
std::string StringReader::getTokens(const char *stop_chars, bool truncateEnd)
{
if (str_pos >= rd_string.size())
return "";
size_t found_pos = rd_string.find_first_of(stop_chars, str_pos);
if (rd_string[str_pos] == '\"') {
//Find the next quote
found_pos = rd_string.find("\"", str_pos+1);
//Check to see if the quote is escaped
int numBackslashes = 0;
int countBack = 1;
while (found_pos >= countBack && rd_string[found_pos-countBack] == '\\') {
numBackslashes++;
countBack++;
}
//While the quote is escaped
while (numBackslashes % 2 == 1) {
//find the next quote
found_pos = rd_string.find("\"", found_pos+1);
//Check to see if it's escaped
numBackslashes = 0;
countBack = 1;
while (found_pos >= countBack && rd_string[found_pos-countBack] == '\\') {
numBackslashes++;
countBack++;
}
}
}
if (found_pos == str_pos) //We are at the endline
{
std::string stop_char(1, rd_string[str_pos]);
str_pos++;
return stop_char;
} else if (found_pos == std::string::npos) //We are at the end of the file
{
//End of String
end_reached = true;
//std::cout << "Reached end of file!\n";
return "";
} else {
if (truncateEnd) //If we want to get rid of the delimiting character, which is the default, don't add the last char. Note we have to increase str_pos by one manually later
found_pos -= 1;
if (rd_string[str_pos] == '\"')
found_pos++;
std::string string_section = rd_string.substr(str_pos, found_pos - str_pos + 1);
str_pos = found_pos + 1;
if (truncateEnd) //Ok, we didn't add the last char, but str_pos now points at that char. So we move it one ahead.
str_pos++;
return string_section;
}
}
void StringReader::test()
{
{
StringReader reader("\"x\"");
assert(reader.word() == "\"x\"");
assert(reader.word() == "");
}
{
StringReader reader("\"y\" ;\n");
assert(reader.word() == "\"y\"");
assert(reader.word() == ";");
assert(reader.word() == "");
}
{
StringReader reader("Goal = greeting ;\n"
"greeting = \"hello\" | greeting \"world\" ;\n");
assert(reader.word() == "Goal");
assert(reader.word() == "=");
assert(reader.word() == "greeting");
assert(reader.word() == ";");
assert(reader.word() == "greeting");
assert(reader.word() == "=");
assert(reader.word() == "\"hello\"");
assert(reader.word() == "|");
assert(reader.word() == "greeting");
assert(reader.word() == "\"world\"");
assert(reader.word() == ";");
assert(reader.word() == "");
}
{
StringReader reader("one # pretend this is a comment\n"
" two\n");
assert(reader.word() == "one");
assert(reader.word() == "#");
assert(reader.line() == "pretend this is a comment");
assert(reader.word() == "two");
assert(reader.word() == "");
}
{
// Quoted strings can span lines.
StringReader reader("x = \"\n \" ;\n");
assert(reader.word() == "x");
assert(reader.word() == "=");
assert(reader.word() == "\"\n \"");
assert(reader.word() == ";");
assert(reader.word() == "");
}
{
// Strings may contain backslash-escaped quote characters.
StringReader reader( "\"abc\\\"def\\\\\\\\\\\" \"\n");
assert(reader.word() == "\"abc\\\"def\\\\\\\\\\\" \"");
assert(reader.word() == "");
}
{
// A backslash-escaped backslash can be the last character in a string.
StringReader reader( "\"\\\\\" \n");
assert(reader.word() == "\"\\\\\"");
assert(reader.word() == "");
}
std::cout << "StringReader tests pass\n";
}
| 29.700599
| 217
| 0.509879
|
Limvot
|
02a21e1be3d55119cb4936b7741881775c7b9f5e
| 3,117
|
cpp
|
C++
|
tools/relation_finder_client.cpp
|
fhd/relation-finder
|
37dec835be079e6158c1304cffcb33d43cd13393
|
[
"MIT"
] | 1
|
2018-09-11T02:37:42.000Z
|
2018-09-11T02:37:42.000Z
|
tools/relation_finder_client.cpp
|
fhd/relation-finder
|
37dec835be079e6158c1304cffcb33d43cd13393
|
[
"MIT"
] | null | null | null |
tools/relation_finder_client.cpp
|
fhd/relation-finder
|
37dec835be079e6158c1304cffcb33d43cd13393
|
[
"MIT"
] | null | null | null |
/*
* This is an example client for relation-finder, demonstrating its protocol
* using Boost.Asio for network communication.
*
* The protocol is pretty simple, the only data send is a couple of unsigned
* 32-bit integers. It basically works like this:
* 1. Connect to relation-finder via TCP.
* 2. Send the user ID of the first person (user A).
* 3. Send the user ID of the second person (user B).
* 4. Read the length of path. If that number is 0, no path could be found.
* 5. Read as many user IDs as the path was long.
* This is the result, the path from user A to user B.
*/
#include <string>
#include <iostream>
#include <boost/array.hpp>
#include <asio.hpp>
using asio::ip::tcp;
uint32_t read_uint(tcp::socket& socket)
{
asio::error_code error;
uint32_t uint;
socket.read_some(asio::buffer((void*) &uint, sizeof(uint)), error);
if (error)
throw asio::system_error(error);
return uint;
}
void write_uint(tcp::socket& socket, uint32_t uint)
{
asio::error_code error;
socket.write_some(asio::buffer((void*) &uint, sizeof(uint)), error);
if (error)
throw asio::system_error(error);
}
int main(int argc, char* argv[])
{
// Read address and request parameters from the commandline
if (argc < 5) {
std::cerr << "relation-finder-client - asks relation-finder for a "
<< "connection between two people" << std::endl
<< "Usage: relation-finder-client HOST PORT PERSON1 PERSON2"
<< std::endl;
return 1;
}
std::string host = argv[1];
std::string port = argv[2];
unsigned int pid1 = atoi(argv[3]);
unsigned int pid2 = atoi(argv[4]);
try {
// Resolve the host
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, port);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
// Connect to the server
tcp::socket socket(io_service);
asio::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end) {
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error)
throw asio::system_error(error);
// Write the person's id
write_uint(socket, pid1);
// Write the other person's id
write_uint(socket, pid2);
// Read the length of the path
int path_length = read_uint(socket);
if (path_length == 0) {
std::cout << "No path was found." << std::endl;
} else {
std::cout << "Found a path: ";
// Read the path
for (int i = 0; i < path_length; i++) {
unsigned int node = read_uint(socket);
std::cout << node;
if (i != path_length - 1)
std::cout << " -> ";
}
std::cout << std::endl;
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| 30.558824
| 78
| 0.582291
|
fhd
|
02a5f62e1280a8f6927bc550e79d8ad56d3f86b0
| 3,072
|
cpp
|
C++
|
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | null | null | null |
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | 3
|
2020-12-11T10:01:27.000Z
|
2022-02-13T22:12:05.000Z
|
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
|
1pkg/dump
|
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
|
[
"MIT"
] | null | null | null |
#include "Pivot.hpp"
namespace GameAct
{
namespace Physical
{
void
Pivot::initialize()
{
Object::initialize();
getBody()->setDynamic( false );
}
std::string
Pivot::getResourcesName() const
{
return "Pivot";
}
void
Pivot::setAdditionalParam( std::string additionalParam )
{
std::string rotationTime = ThirdParty::readToken( additionalParam );
_time = atof( rotationTime.data() );
Object::setAdditionalParam( additionalParam );
}
void
Pivot::setRotation( float angle )
{
_angle = angle;
Object::setRotation( angle );
}
void
Pivot::runAction( const std::string & action )
{
if( action == "RotateSaw" )
{
float delta = getSize().width / 2.0f;
float deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) );
float deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) );
cocos2d::Vec2 center = getPosition();
center.x -= deltaX;
center.y -= deltaY;
cocos2d::Vector< cocos2d::FiniteTimeAction * > rotatePnt;
cocos2d::Vec2 posit = getPosition();
posit.x += deltaX;
posit.y += deltaY;
for( int i = 0; i < 360; ++i )
{
rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 360, posit ) );
posit = rotatePoint( posit, center, 1.0f );
}
auto action = cocos2d::RepeatForever::create( cocos2d::Sequence::create( rotatePnt ) );
_representation->runAction( cocos2d::RepeatForever::create( action ) );
}
if( action == "FluctuatePendulum" )
{
float delta = getSize().width / 2.0f;
float deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) );
float deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) );
cocos2d::Vec2 center = getPosition();
center.x -= deltaX;
center.y -= deltaY;
cocos2d::Vector< cocos2d::FiniteTimeAction * > rotatePnt;
cocos2d::Vec2 posit = getPosition();
posit.x += deltaX;
posit.y += deltaY;
for( int i = 0; i < 60; ++i )
{
rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) );
posit = rotatePoint( posit, center, 1.0f );
}
for( int i = 0; i < 120; ++i )
{
rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) );
posit = rotatePoint( posit, center, -1.0f );
}
for( int i = 0; i < 60; ++i )
{
rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) );
posit = rotatePoint( posit, center, 1.0f );
}
auto action = cocos2d::RepeatForever::create( cocos2d::Sequence::create( rotatePnt ) );
}
if( action == "Stop" || action == "Off" )
{
_representation->setAnchorPoint( cocos2d::Vec2( 0.5f, 0.5f ) );
_representation->stopAllActions();
}
}
cocos2d::Vec2
Pivot::rotatePoint( cocos2d::Vec2 point, cocos2d::Vec2 center, float angle ) const
{
angle = CC_DEGREES_TO_RADIANS( angle );
float rotatedX = cos( angle ) * (point.x - center.x) + sin( angle ) * ( point.y - center.y ) + center.x;
float rotatedY = -sin( angle ) * ( point.x - center.x ) + cos( angle ) * ( point.y - center.y ) + center.y;
return cocos2d::Vec2( rotatedX, rotatedY );
}
}
}
| 27.185841
| 112
| 0.627279
|
1pkg
|
02a94f378ed16f784a838b13b832a3baa61b2354
| 5,554
|
cpp
|
C++
|
cynosdb/src/v20190107/model/NetAddr.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 1
|
2022-01-27T09:27:34.000Z
|
2022-01-27T09:27:34.000Z
|
cynosdb/src/v20190107/model/NetAddr.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
cynosdb/src/v20190107/model/NetAddr.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cynosdb/v20190107/model/NetAddr.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cynosdb::V20190107::Model;
using namespace std;
NetAddr::NetAddr() :
m_vipHasBeenSet(false),
m_vportHasBeenSet(false),
m_wanDomainHasBeenSet(false),
m_wanPortHasBeenSet(false),
m_netTypeHasBeenSet(false)
{
}
CoreInternalOutcome NetAddr::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Vip") && !value["Vip"].IsNull())
{
if (!value["Vip"].IsString())
{
return CoreInternalOutcome(Core::Error("response `NetAddr.Vip` IsString=false incorrectly").SetRequestId(requestId));
}
m_vip = string(value["Vip"].GetString());
m_vipHasBeenSet = true;
}
if (value.HasMember("Vport") && !value["Vport"].IsNull())
{
if (!value["Vport"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `NetAddr.Vport` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_vport = value["Vport"].GetInt64();
m_vportHasBeenSet = true;
}
if (value.HasMember("WanDomain") && !value["WanDomain"].IsNull())
{
if (!value["WanDomain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `NetAddr.WanDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_wanDomain = string(value["WanDomain"].GetString());
m_wanDomainHasBeenSet = true;
}
if (value.HasMember("WanPort") && !value["WanPort"].IsNull())
{
if (!value["WanPort"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `NetAddr.WanPort` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_wanPort = value["WanPort"].GetInt64();
m_wanPortHasBeenSet = true;
}
if (value.HasMember("NetType") && !value["NetType"].IsNull())
{
if (!value["NetType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `NetAddr.NetType` IsString=false incorrectly").SetRequestId(requestId));
}
m_netType = string(value["NetType"].GetString());
m_netTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void NetAddr::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_vipHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Vip";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_vip.c_str(), allocator).Move(), allocator);
}
if (m_vportHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Vport";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_vport, allocator);
}
if (m_wanDomainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "WanDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_wanDomain.c_str(), allocator).Move(), allocator);
}
if (m_wanPortHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "WanPort";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_wanPort, allocator);
}
if (m_netTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NetType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_netType.c_str(), allocator).Move(), allocator);
}
}
string NetAddr::GetVip() const
{
return m_vip;
}
void NetAddr::SetVip(const string& _vip)
{
m_vip = _vip;
m_vipHasBeenSet = true;
}
bool NetAddr::VipHasBeenSet() const
{
return m_vipHasBeenSet;
}
int64_t NetAddr::GetVport() const
{
return m_vport;
}
void NetAddr::SetVport(const int64_t& _vport)
{
m_vport = _vport;
m_vportHasBeenSet = true;
}
bool NetAddr::VportHasBeenSet() const
{
return m_vportHasBeenSet;
}
string NetAddr::GetWanDomain() const
{
return m_wanDomain;
}
void NetAddr::SetWanDomain(const string& _wanDomain)
{
m_wanDomain = _wanDomain;
m_wanDomainHasBeenSet = true;
}
bool NetAddr::WanDomainHasBeenSet() const
{
return m_wanDomainHasBeenSet;
}
int64_t NetAddr::GetWanPort() const
{
return m_wanPort;
}
void NetAddr::SetWanPort(const int64_t& _wanPort)
{
m_wanPort = _wanPort;
m_wanPortHasBeenSet = true;
}
bool NetAddr::WanPortHasBeenSet() const
{
return m_wanPortHasBeenSet;
}
string NetAddr::GetNetType() const
{
return m_netType;
}
void NetAddr::SetNetType(const string& _netType)
{
m_netType = _netType;
m_netTypeHasBeenSet = true;
}
bool NetAddr::NetTypeHasBeenSet() const
{
return m_netTypeHasBeenSet;
}
| 25.59447
| 135
| 0.662405
|
suluner
|
02aa1c90a68e80c19bcdd0b2a1f9d1f98238024d
| 5,709
|
cpp
|
C++
|
examples/airhockey/openglwindow.cpp
|
LJC-DB/abcg
|
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
|
[
"MIT"
] | null | null | null |
examples/airhockey/openglwindow.cpp
|
LJC-DB/abcg
|
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
|
[
"MIT"
] | null | null | null |
examples/airhockey/openglwindow.cpp
|
LJC-DB/abcg
|
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
|
[
"MIT"
] | null | null | null |
#include "openglwindow.hpp"
#include <imgui.h>
#include <string>
#include "abcg.hpp"
void OpenGLWindow::handleEvent(SDL_Event &event) {
// Keyboard events
if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_UP)
m_gameData.m_input.set(static_cast<size_t>(Input::Up));
if (event.key.keysym.sym == SDLK_DOWN)
m_gameData.m_input.set(static_cast<size_t>(Input::Down));
if (event.key.keysym.sym == SDLK_LEFT)
m_gameData.m_input.set(static_cast<size_t>(Input::Left));
if (event.key.keysym.sym == SDLK_RIGHT)
m_gameData.m_input.set(static_cast<size_t>(Input::Right));
if (event.key.keysym.sym == SDLK_w)
m_gameData.m_input.set(static_cast<size_t>(Input::W));
if (event.key.keysym.sym == SDLK_s)
m_gameData.m_input.set(static_cast<size_t>(Input::S));
if (event.key.keysym.sym == SDLK_a)
m_gameData.m_input.set(static_cast<size_t>(Input::A));
if (event.key.keysym.sym == SDLK_d)
m_gameData.m_input.set(static_cast<size_t>(Input::D));
}
if (event.type == SDL_KEYUP) {
if (event.key.keysym.sym == SDLK_UP)
m_gameData.m_input.reset(static_cast<size_t>(Input::Up));
if (event.key.keysym.sym == SDLK_DOWN)
m_gameData.m_input.reset(static_cast<size_t>(Input::Down));
if (event.key.keysym.sym == SDLK_LEFT)
m_gameData.m_input.reset(static_cast<size_t>(Input::Left));
if (event.key.keysym.sym == SDLK_RIGHT)
m_gameData.m_input.reset(static_cast<size_t>(Input::Right));
if (event.key.keysym.sym == SDLK_w)
m_gameData.m_input.reset(static_cast<size_t>(Input::W));
if (event.key.keysym.sym == SDLK_s)
m_gameData.m_input.reset(static_cast<size_t>(Input::S));
if (event.key.keysym.sym == SDLK_a)
m_gameData.m_input.reset(static_cast<size_t>(Input::A));
if (event.key.keysym.sym == SDLK_d)
m_gameData.m_input.reset(static_cast<size_t>(Input::D));
}
}
void OpenGLWindow::initializeGL() {
// Load a new font
ImGuiIO &io{ImGui::GetIO()};
auto filename{getAssetsPath() + "Inconsolata-Medium.ttf"};
m_font = io.Fonts->AddFontFromFileTTF(filename.c_str(), 60.0f);
if (m_font == nullptr) {
throw abcg::Exception{abcg::Exception::Runtime("Cannot load font file")};
}
// Create program to render the other objects
m_objectsProgram = createProgramFromFile(getAssetsPath() + "objects.vert",
getAssetsPath() + "objects.frag");
abcg::glClearColor(0, 0, 0, 1);
#if !defined(__EMSCRIPTEN__)
abcg::glEnable(GL_PROGRAM_POINT_SIZE);
#endif
restart();
}
void OpenGLWindow::restart() {
m_gameData.m_state = State::Playing;
m_player.initializeGL(m_objectsProgram);
m_puck.initializeGL(m_objectsProgram);
m_board.initializeGL(m_objectsProgram);
}
void OpenGLWindow::update() {
const float deltaTime{static_cast<float>(getDeltaTime())};
// Wait 5 seconds before restarting
if (m_gameData.m_state != State::Playing &&
m_restartWaitTimer.elapsed() > 5) {
m_gameData.m_score.fill(0);
restart();
return;
}
m_player.update(m_gameData, deltaTime);
m_puck.update(m_player, m_gameData, deltaTime);
if (m_gameData.m_state == State::Playing) {
checkGoals();
checkWinCondition();
}
}
void OpenGLWindow::paintGL() {
update();
abcg::glClear(GL_COLOR_BUFFER_BIT);
abcg::glViewport(0, 0, m_viewportWidth, m_viewportHeight);
m_player.paintGL(m_gameData);
m_puck.paintGL(m_gameData);
m_board.paintGL(m_gameData);
}
void OpenGLWindow::paintUI() {
abcg::OpenGLWindow::paintUI();
{
ImVec2 size;
ImVec2 position;
if (m_gameData.m_state == State::Playing) {
size = ImVec2(180, 80);
position = ImVec2((m_viewportWidth - size.x) / 2.0f,
(m_viewportHeight - size.y) / 4.0f);
} else {
size = ImVec2(400, 85);
position = ImVec2((m_viewportWidth - size.x) / 2.0f,
(m_viewportHeight - size.y) / 2.0f);
}
ImGui::SetNextWindowPos(position);
ImGui::SetNextWindowSize(size);
ImGuiWindowFlags flags{ImGuiWindowFlags_NoBackground |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoInputs};
ImGui::Begin(" ", nullptr, flags);
ImGui::PushFont(m_font);
if (m_gameData.m_state == State::WinP1) {
ImGui::Text("Player 1 Wins!");
} else if (m_gameData.m_state == State::WinP2) {
ImGui::Text("Player 2 Wins!");
} else {
std::string text = std::to_string(m_gameData.m_score.at(0)) +
std::string(" ") +
std::to_string(m_gameData.m_score.at(1));
ImGui::Text(text.c_str());
}
ImGui::PopFont();
ImGui::End();
}
}
void OpenGLWindow::resizeGL(int width, int height) {
m_viewportWidth = width;
m_viewportHeight = height;
abcg::glClear(GL_COLOR_BUFFER_BIT);
}
void OpenGLWindow::terminateGL() {
abcg::glDeleteProgram(m_objectsProgram);
m_player.terminateGL();
m_puck.terminateGL();
m_board.terminateGL();
}
void OpenGLWindow::checkGoals() {
auto pos_x = abs(m_puck.m_translation.x) + m_puck.m_scale;
auto pos_y = abs(m_puck.m_translation.y) + m_puck.m_scale;
if (pos_x >= .9f && pos_y < .3f) {
if (m_puck.m_translation.x > 0)
m_gameData.m_score.at(0)++;
else
m_gameData.m_score.at(1)++;
restart();
}
}
void OpenGLWindow::checkWinCondition() {
if (std::any_of(std::begin(m_gameData.m_score), std::end(m_gameData.m_score),
[=](int n) { return n >= 5; })) {
if (m_gameData.m_score.at(0) >= 5)
m_gameData.m_state = State::WinP1;
else
m_gameData.m_state = State::WinP2;
m_restartWaitTimer.restart();
}
}
| 30.529412
| 79
| 0.652128
|
LJC-DB
|
02ac059c16f068988bd9a138885c13f70391079a
| 1,589
|
cpp
|
C++
|
source/Ch10/Drill10.cpp
|
DBalazs22/UDProg-Introduction
|
b443a831f2e3496928593d4b5d73db141d8be17c
|
[
"CC0-1.0"
] | null | null | null |
source/Ch10/Drill10.cpp
|
DBalazs22/UDProg-Introduction
|
b443a831f2e3496928593d4b5d73db141d8be17c
|
[
"CC0-1.0"
] | null | null | null |
source/Ch10/Drill10.cpp
|
DBalazs22/UDProg-Introduction
|
b443a831f2e3496928593d4b5d73db141d8be17c
|
[
"CC0-1.0"
] | null | null | null |
#include "std_lib_facilities.h"
struct Point
{
int x,y;
};
vector<Point> original_points;
vector<Point> processed_points;
void get_points()
{
int x,y;
while (cin >> x >> y )
{
original_points.push_back(Point{x,y});
if(original_points.size()==7) break;
}
}
void write_points()
{
string name = "pontok.txt";
ofstream ost {name};
if (!ost) error ("Can't open output file ", name);
for (int i=0;i<original_points.size();++i)
{
ost << original_points[i].x << ' ' << original_points[i].y << endl;
}
ost.close();
}
void read_points()
{
int x,y;
string name = "pontok.txt";
ifstream ist {name};
if (!ist) error ("Can't open input file ", name);
while (ist >> x >> y)
{
processed_points.push_back(Point{x,y});
}
}
void compare()
{
for (int i=0; i<original_points.size(); i++)
{
if ((original_points[i].x!=processed_points[i].x) || (original_points[i].y!=processed_points[i].y))
error("Something's wrong");
}
}
int main()
try{
cout << "Kérlek adj meg 7 db x és y pár egész számot\n";
get_points();
write_points();
read_points();
// eredeti vektor
cout << "Eredeti pontok: \n";
for (int i=0;i<original_points.size();++i)
{
cout << original_points[i].x << ' ' << original_points[i].y << endl;
}
// beolvasott vektor
cout << "Feldolgozott pontok: \n";
for (int i=0;i<processed_points.size();++i)
{
cout << processed_points[i].x << ' ' << processed_points[i].y << endl;
}
compare();
return 0;
} catch (exception& e) {
cout<<e.what()<<endl;
return 1;
}
catch (...) {
cerr << "Oops: unknown exception!\n";
return 2;
}
| 16.050505
| 101
| 0.618628
|
DBalazs22
|
02add380db14246448830f81bc6c9ae9dc762dba
| 6,669
|
hpp
|
C++
|
src/config/config-schema.hpp
|
bsc-ssrg/NORNS
|
4fd2d181019eceadb8b1b04a94e3756476326239
|
[
"MIT"
] | 2
|
2019-11-11T11:34:56.000Z
|
2020-12-08T02:13:48.000Z
|
src/config/config-schema.hpp
|
bsc-ssrg/NORNS
|
4fd2d181019eceadb8b1b04a94e3756476326239
|
[
"MIT"
] | null | null | null |
src/config/config-schema.hpp
|
bsc-ssrg/NORNS
|
4fd2d181019eceadb8b1b04a94e3756476326239
|
[
"MIT"
] | null | null | null |
/*************************************************************************
* Copyright (C) 2017-2019 Barcelona Supercomputing Center *
* Centro Nacional de Supercomputacion *
* All rights reserved. *
* *
* This file is part of NORNS, a service that allows other programs to *
* start, track and manage asynchronous transfers of data resources *
* between different storage backends. *
* *
* See AUTHORS file in the top level directory for information regarding *
* developers and contributors. *
* *
* This software was developed as part of the EC H2020 funded project *
* NEXTGenIO (Project ID: 671951). *
* www.nextgenio.eu *
* *
* 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 __CONFIG_SCHEMA_HPP__
#define __CONFIG_SCHEMA_HPP__
#include "file-options.hpp"
#include "parsers.hpp"
#include "keywords.hpp"
#include "defaults.hpp"
namespace norns {
namespace config {
using file_options::file_schema;
using file_options::declare_option;
using file_options::declare_list;
using file_options::declare_group;
using file_options::declare_file;
using file_options::converter;
using file_options::sec_type;
using file_options::opt_type;
// define the configuration file structure and declare the supported options
const file_schema valid_options = declare_file({
// section for global settings
declare_section(
keywords::global_settings,
sec_type::mandatory,
declare_group({
declare_option<bool>(
keywords::use_syslog,
opt_type::mandatory,
converter<bool>(parsers::parse_bool)),
declare_option<bfs::path>(
keywords::log_file,
opt_type::optional,
converter<bfs::path>(parsers::parse_path)),
declare_option<uint32_t>(
keywords::log_file_max_size,
opt_type::optional,
converter<uint32_t>(parsers::parse_capacity)),
declare_option<bool>(
keywords::dry_run,
opt_type::optional,
defaults::dry_run,
converter<bool>(parsers::parse_bool)),
declare_option<bfs::path>(
keywords::global_socket,
opt_type::mandatory,
converter<bfs::path>(parsers::parse_path)),
declare_option<bfs::path>(
keywords::control_socket,
opt_type::mandatory,
converter<bfs::path>(parsers::parse_path)),
declare_option<std::string>(
keywords::bind_address,
opt_type::mandatory),
declare_option<uint32_t>(
keywords::remote_port,
opt_type::mandatory,
converter<uint32_t>(parsers::parse_number)),
declare_option<bfs::path>(
keywords::pidfile,
opt_type::mandatory,
converter<bfs::path>(parsers::parse_path)),
declare_option<uint32_t>(
keywords::workers,
opt_type::mandatory,
converter<uint32_t>(parsers::parse_number)),
declare_option<bfs::path>(
keywords::staging_directory,
opt_type::mandatory,
converter<bfs::path>(parsers::parse_path)),
})
),
// section for namespaces
declare_section(
keywords::namespaces,
sec_type::optional,
declare_list({
declare_option<std::string>(
keywords::nsid,
opt_type::mandatory),
declare_option<bool>(
keywords::track_contents,
opt_type::mandatory,
converter<bool>(parsers::parse_bool)),
declare_option<bfs::path>(
keywords::mountpoint,
opt_type::mandatory,
converter<bfs::path>(parsers::parse_existing_path)),
declare_option<std::string>(
keywords::type,
opt_type::mandatory),
declare_option<uint64_t>(
keywords::capacity,
opt_type::mandatory,
converter<uint64_t>(parsers::parse_capacity)),
declare_option<std::string>(
keywords::visibility,
opt_type::mandatory)
})
)
});
} // namespace config
} // namespace norns
#endif /* __CONFIG_SCHEMA_HPP__ */
| 42.477707
| 76
| 0.504873
|
bsc-ssrg
|
02b18662fc96a17a916f6576826a6c7903305d48
| 2,882
|
cpp
|
C++
|
dibot _template/DIBotFramework/CAN/can.cpp
|
Guvernant/DIBot
|
dfda9924b0fd39eca725a2724bc759e7b62ef671
|
[
"Apache-2.0"
] | null | null | null |
dibot _template/DIBotFramework/CAN/can.cpp
|
Guvernant/DIBot
|
dfda9924b0fd39eca725a2724bc759e7b62ef671
|
[
"Apache-2.0"
] | null | null | null |
dibot _template/DIBotFramework/CAN/can.cpp
|
Guvernant/DIBot
|
dfda9924b0fd39eca725a2724bc759e7b62ef671
|
[
"Apache-2.0"
] | null | null | null |
#include "can.hpp"
Can::Can()
{
}
bool Can::begin()
{
static PORT_InitTypeDef PortInit;
/* Fill PortInit structure*/
PortInit.PORT_PULL_UP = PORT_PULL_UP_OFF;
PortInit.PORT_PULL_DOWN = PORT_PULL_DOWN_OFF;
PortInit.PORT_PD_SHM = PORT_PD_SHM_OFF;
PortInit.PORT_PD = PORT_PD_DRIVER;
PortInit.PORT_GFEN = PORT_GFEN_OFF;
PortInit.PORT_FUNC = PORT_FUNC_ALTER;
PortInit.PORT_SPEED = PORT_SPEED_MAXFAST;
PortInit.PORT_MODE = PORT_MODE_DIGITAL;
/* Configure PORTA pins 7 (CAN2_RX) as input */
PortInit.PORT_OE = PORT_OE_IN;
PortInit.PORT_Pin = PORT_Pin_7;
PORT_Init(MDR_PORTA, &PortInit);
/* Configure PORTA pins 6 (CAN2_TX) as output */
PortInit.PORT_OE = PORT_OE_OUT;
PortInit.PORT_Pin = PORT_Pin_6;
PORT_Init(MDR_PORTA, &PortInit);
CAN_InitTypeDef sCAN;
RST_CLK_PCLKcmd((RST_CLK_PCLK_RST_CLK | RST_CLK_PCLK_CAN1),ENABLE);
RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTA,ENABLE);
CAN_BRGInit(MDR_CAN1,CAN_HCLKdiv1);
/* CAN register init */
CAN_DeInit(MDR_CAN1);
/* CAN cell init */
CAN_StructInit (&sCAN);
sCAN.CAN_ROP = ENABLE;
sCAN.CAN_SAP = ENABLE;
sCAN.CAN_STM = DISABLE;
sCAN.CAN_ROM = DISABLE;
//сделать расчет частоты на 500кбс
sCAN.CAN_PSEG = CAN_PSEG_Mul_2TQ;
sCAN.CAN_SEG1 = CAN_SEG1_Mul_5TQ;
sCAN.CAN_SEG2 = CAN_SEG2_Mul_5TQ;
sCAN.CAN_SJW = CAN_SJW_Mul_4TQ;
sCAN.CAN_SB = CAN_SB_3_SAMPLE;
sCAN.CAN_BRP = 1;
CAN_Init (MDR_CAN1,&sCAN);
CAN_Cmd(MDR_CAN1, ENABLE);
/* Disable all CAN1 interrupt */
CAN_ITConfig( MDR_CAN1, CAN_IT_GLBINTEN | CAN_IT_RXINTEN | CAN_IT_TXINTEN |
CAN_IT_ERRINTEN | CAN_IT_ERROVERINTEN, DISABLE);
/* Enable CAN1 interrupt from receive buffer */
CAN_RxITConfig( MDR_CAN1 ,rx_buf, ENABLE);
/* Enable CAN1 interrupt from transmit buffer */
CAN_TxITConfig( MDR_CAN1 ,tx_buf, ENABLE);
/* receive buffer enable */
CAN_Receive(MDR_CAN1, rx_buf, DISABLE);
return true;
}
void Can::end()
{
}
void Can::write()
{
CAN_TxMsgTypeDef TxMsg;
/* transmit */
TxMsg.IDE = CAN_ID_STD;
TxMsg.DLC = 0x08;
TxMsg.PRIOR_0 = DISABLE;
TxMsg.ID = 0x7;
TxMsg.Data[1] = 0x01234567;
TxMsg.Data[0] = 0x89ABCDEF;
CAN_Transmit(MDR_CAN1, tx_buf, &TxMsg);
uint32_t i = 0;
//i это таймаут
while(((CAN_GetStatus(MDR_CAN1) & CAN_STATUS_TX_READY) != RESET) && (i != 0xFFF))
{
i++;
}
CAN_ITClearRxTxPendingBit(MDR_CAN1, tx_buf, CAN_STATUS_TX_READY);
}
void Can::read()
{
CAN_RxMsgTypeDef RxMsg;
uint32_t i = 0;
//i это таймаут
while(((CAN_GetStatus(MDR_CAN1) & CAN_STATUS_RX_READY) == RESET) && (i != 0xFFF))
{
i++;
}
CAN_GetRawReceivedData(MDR_CAN1, rx_buf, &RxMsg);
CAN_ITClearRxTxPendingBit(MDR_CAN1, rx_buf, CAN_STATUS_RX_READY);
}
| 23.430894
| 85
| 0.667939
|
Guvernant
|
02b4a4cd0b1806a0738989533c578016d79446a2
| 1,464
|
hpp
|
C++
|
src/types/inc/User32Utils.hpp
|
hessedoneen/terminal
|
aa54de1d648f45920996aeba1edecc67237c6642
|
[
"MIT"
] | 34,359
|
2019-05-06T21:04:42.000Z
|
2019-05-14T22:06:43.000Z
|
src/types/inc/User32Utils.hpp
|
Ingridamilsina/terminal
|
788d33ce94d28e2903bc49f841ce279211b7f557
|
[
"MIT"
] | 356
|
2019-05-06T21:03:35.000Z
|
2019-05-14T21:38:47.000Z
|
src/types/inc/User32Utils.hpp
|
Ingridamilsina/terminal
|
788d33ce94d28e2903bc49f841ce279211b7f557
|
[
"MIT"
] | 3,164
|
2019-05-06T21:06:01.000Z
|
2019-05-14T20:25:52.000Z
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// Routine Description:
// - Retrieves the string resource from the current module with the given ID
// from the resources files. See resource.h and the .rc definitions for valid
// IDs.
// Arguments:
// - id - Resource ID
// Return Value:
// - String resource retrieved from that ID.
// NOTE: `__declspec(noinline) inline`: make one AND ONLY ONE copy of this
// function, and don't actually inline it
__declspec(noinline) inline std::wstring GetStringResource(const UINT id)
{
// Calling LoadStringW with a pointer-sized storage and no length will
// return a read-only pointer directly to the resource data instead of
// copying it immediately into a buffer.
LPWSTR readOnlyResource = nullptr;
const auto length = LoadStringW(wil::GetModuleInstanceHandle(),
id,
reinterpret_cast<LPWSTR>(&readOnlyResource),
0);
LOG_LAST_ERROR_IF(length == 0);
// However, the pointer and length given are NOT guaranteed to be
// zero-terminated and most uses of this data will probably want a
// zero-terminated string. So we're going to construct and return a
// std::wstring copy from the pointer/length since those are certainly
// zero-terminated.
return { readOnlyResource, gsl::narrow<size_t>(length) };
}
| 45.75
| 81
| 0.661202
|
hessedoneen
|
02b5e1ad621cc806ee5bd2275752aab00db6b8a8
| 12,117
|
hpp
|
C++
|
libraries/belle/Source/Modern/Music/State.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 47
|
2017-09-05T02:49:22.000Z
|
2022-01-20T08:11:47.000Z
|
libraries/belle/Source/Modern/Music/State.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 106
|
2018-05-16T14:58:52.000Z
|
2022-01-12T13:57:24.000Z
|
libraries/belle/Source/Modern/Music/State.hpp
|
jogawebb/Spaghettis
|
78f21ba3065ce316ef0cb84e94aecc9e8787343d
|
[
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause"
] | 11
|
2018-05-16T06:44:51.000Z
|
2021-11-10T07:04:46.000Z
|
/*
Copyright (c) 2007-2013 William Andrew Burnson.
Copyright (c) 2013-2020 Nicolas Danet.
*/
/* < http://opensource.org/licenses/BSD-2-Clause > */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* State while traversing the graph. */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace belle {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
namespace State {
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Clef { /* Get accidental and line depending on clef and key. */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Clef()
{
setKeyAccidentals (mica::NoAccidentals);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
#if PRIM_CPP11
public:
Clef (const Clef&) = delete;
Clef& operator = (const Clef&) = delete;
#else
private:
Clef (const Clef&);
Clef& operator = (const Clef&);
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void reset()
{
attributes_.clear();
actives_.clear();
keys_.clear();
setKeyAccidentals (mica::NoAccidentals);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void parse (NodePtr token)
{
mica::Concept kind = token->getObject().getAttribute (mica::Kind);
mica::Concept value = token->getObject().getAttribute (mica::Value);
if (kind == mica::Clef) { attributes_[kind] = value; }
else if (kind == mica::KeySignature) { actives_.clear(); setKeyAccidentals (value); }
else if (kind == mica::Barline) { actives_.clear(); }
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
mica::Concept getAttribute (mica::Concept concept) const
{
return attributes_[concept];
}
mica::Concept getLinespace (mica::Concept chromatic) const
{
mica::Concept diatonic = mica::map (chromatic, mica::DiatonicPitch);
mica::Concept linespace = mica::map (getAttribute (mica::Clef), diatonic);
return linespace;
}
mica::Concept getAccidental (mica::Concept chromatic)
{
mica::Concept accidental = mica::map (chromatic, mica::Accidental);
mica::Concept diatonic = mica::map (chromatic, mica::DiatonicPitch);
mica::Concept letter = mica::map (diatonic, mica::Letter);
mica::Concept current = actives_[diatonic];
if (current != mica::Undefined) { if (accidental == current) { return mica::Undefined; } }
else if (keys_[letter] == accidental) { return mica::Undefined; }
actives_[diatonic] = accidental;
return accidental;
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
private:
void setKeyAccidentals (mica::Concept keySignature)
{
keys_ = mica::MIR::Utils::getAccidentalsByLetters (keySignature);
}
private:
Table < mica::Concept > attributes_;
Table < mica::Concept > actives_; /* Active accidentals. */
Table < mica::Concept > keys_; /* Key accidentals. */
private:
PRIM_LEAK_DETECTOR (Clef)
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Chord { /* Buffering chord values to define ties. */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Chord()
{
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
#if PRIM_CPP11
public:
Chord (const Chord&) = delete;
Chord& operator = (const Chord&) = delete;
#else
private:
Chord (const Chord&);
Chord& operator = (const Chord&);
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void reset()
{
attributes_.clear();
stamps_.clear();
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void parse (NodePtr island, NodePtr token, const Pointer < Stamp > & stamp)
{
mica::Concept kind = token->getObject().getAttribute (mica::Kind);
mica::Concept value = token->getObject().getAttribute (mica::Value);
if (kind == mica::Chord) {
attributes_[mica::Stem] = token->getObject().getAttribute (mica::Stem);
attributes_[mica::Size] = token->getObject().getAttribute (mica::Size);
attributes_[mica::Status] = island->getObject().getAttribute (mica::Status);
} else if (kind == mica::Note) {
mica::Concept tie = token->getObject().getAttribute (mica::Tie);
if (tie == mica::End) { stamps_[value] = nullptr; }
else if (tie == mica::Beginning || tie == mica::Middle) {
stamps_[value] = stamp;
}
}
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
mica::Concept getAttribute (mica::Concept concept) const
{
return attributes_[concept];
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
/* Note that values are returned in context. */
public:
Path getPath (mica::Concept chromatic) const
{
if (stamps_[chromatic] == nullptr) { return Path(); }
else {
return stamps_[chromatic]->getPath (stamps_[chromatic]->getContext());
}
}
Box getBox (mica::Concept chromatic) const
{
if (stamps_[chromatic] == nullptr) { return Box::empty(); }
else {
return stamps_[chromatic]->getBox (chromatic, stamps_[chromatic]->getContext());
}
}
private:
Table < mica::Concept > attributes_;
Table < mica::Concept, Pointer < Stamp > > stamps_; /* Stamps of active notes to determine ties. */
private:
PRIM_LEAK_DETECTOR (Chord)
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
class Group { /* Collecting chords to define tuplets and beams. */
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
Group()
{
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
#if PRIM_CPP11
public:
Group (const Group&) = delete;
Group& operator = (const Group&) = delete;
#else
private:
Group (const Group&);
Group& operator = (const Group&);
#endif
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void reset()
{
group_.clear();
boxes_.clear();
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void setBox (mica::Concept concept, const Box& box)
{
if (concept != mica::Undefined) { boxes_[concept] = box; }
}
Box getBox (mica::Concept concept) const
{
return boxes_[concept];
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
void add (NodePtr token)
{
group_.add (token);
}
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
// MARK: -
public:
const Array < NodePtr > & getTokens() const
{
return group_;
}
Array < NodePtr > reclaimTokens()
{
Array < NodePtr > scoped;
scoped.swapWith (group_);
return scoped;
}
private:
Array < NodePtr > group_;
Table < mica::Concept, Box > boxes_;
private:
PRIM_LEAK_DETECTOR (Group)
};
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace State
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
} // namespace belle
// -----------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
| 34.132394
| 110
| 0.28885
|
jogawebb
|
02b5f782dd156093ddf25189a779ef8ad353b5fd
| 3,107
|
hpp
|
C++
|
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
|
ddj116/gmat
|
39673be967d856f14616462fb6473b27b21b149f
|
[
"NASA-1.3"
] | 1
|
2020-05-16T16:58:21.000Z
|
2020-05-16T16:58:21.000Z
|
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
|
ddj116/gmat
|
39673be967d856f14616462fb6473b27b21b149f
|
[
"NASA-1.3"
] | null | null | null |
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
|
ddj116/gmat
|
39673be967d856f14616462fb6473b27b21b149f
|
[
"NASA-1.3"
] | null | null | null |
//$Id$
//------------------------------------------------------------------------------
// CelestialBodyPropertiesPanel
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002-2011 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Wendy C. Shoan
// Created: 2009.01.13
//
/**
* This is the panel for the Properties tab on the notebook on the CelestialBody
* Panel.
*
*/
//------------------------------------------------------------------------------
#ifndef CelestialBodyPropertiesPanel_hpp
#define CelestialBodyPropertiesPanel_hpp
#include "gmatdefs.hpp"
#include "CelestialBody.hpp"
#include "gmatwxdefs.hpp"
#include "GuiItemManager.hpp"
#include "GmatPanel.hpp"
#include "GmatStaticBoxSizer.hpp"
class CelestialBodyPropertiesPanel : public wxPanel
{
public:
CelestialBodyPropertiesPanel(GmatPanel *cbPanel, wxWindow *parent, CelestialBody *body);
~CelestialBodyPropertiesPanel();
void SaveData();
void LoadData();
bool IsDataChanged() { return dataChanged;};
bool CanClosePanel() { return canClose;};
private:
bool dataChanged;
bool canClose;
CelestialBody *theBody;
GuiItemManager *guiManager;
Real mu;
Real eqRad;
Real flat;
std::string textureMap;
bool muChanged;
bool eqRadChanged;
bool flatChanged;
bool textureChanged;
GmatPanel *theCBPanel;
void Create();
void ResetChangeFlags(bool discardMods = false);
//Event Handling
DECLARE_EVENT_TABLE();
void OnMuTextCtrlChange(wxCommandEvent &event);
void OnEqRadTextCtrlChange(wxCommandEvent &event);
void OnFlatTextCtrlChange(wxCommandEvent &event);
void OnTextureTextCtrlChange(wxCommandEvent &event);
void OnBrowseButton(wxCommandEvent &event);
wxString ToString(Real rval);
// wx
wxStaticText *muStaticText;
wxStaticText *eqRadStaticText;
wxStaticText *flatStaticText;
wxStaticText *textureStaticText;
wxStaticText *muUnitsStaticText;
wxStaticText *eqRadUnitsStaticText;
wxStaticText *flatUnitsStaticText;
wxTextCtrl *muTextCtrl;
wxTextCtrl *eqRadTextCtrl;
wxTextCtrl *flatTextCtrl;
wxTextCtrl *textureTextCtrl;
wxBitmapButton *browseButton;
/// string versions of current data
wxString muString;
wxString eqRadString;
wxString flatString;
wxString textureString;
GmatStaticBoxSizer *pageSizer;
/// IDs for the controls
enum
{
ID_TEXT = 7100,
ID_BUTTON_BROWSE,
ID_TEXT_CTRL_MU,
ID_TEXT_CTRL_EQRAD,
ID_TEXT_CTRL_FLAT,
ID_TEXT_CTRL_TEXTURE,
};
};
#endif // CelestialBodyPropertiesPanel_hpp
| 26.109244
| 91
| 0.626006
|
ddj116
|
02b8d4f257288fd229dc1d940117855bd9d32eaf
| 2,241
|
cpp
|
C++
|
klib_renewal/menu_squad.cpp
|
asm128/gpk_samples
|
7875af0c9116d0c9377a2e7ade0a61364358f4b1
|
[
"Apache-2.0"
] | null | null | null |
klib_renewal/menu_squad.cpp
|
asm128/gpk_samples
|
7875af0c9116d0c9377a2e7ade0a61364358f4b1
|
[
"Apache-2.0"
] | null | null | null |
klib_renewal/menu_squad.cpp
|
asm128/gpk_samples
|
7875af0c9116d0c9377a2e7ade0a61364358f4b1
|
[
"Apache-2.0"
] | null | null | null |
#include "Agent_helper.h"
#include "draw.h"
::klib::SGameState drawSquadSetupMenu (::klib::SGame& instanceGame) {
::klib::drawSquadSlots(instanceGame);
::klib::SGamePlayer & player = instanceGame.Players[::klib::PLAYER_INDEX_USER];
::gpk::array_obj<::gpk::array_pod<char_t>> menuItems = {};
::gpk::array_obj<::gpk::view_const_char> menuItemsView = {};
menuItems .resize(player.Tactical.Squad.Size);
menuItemsView .resize(menuItems.size());
static int32_t maxNameLen = 0;
for(uint32_t i = 0, count = player.Tactical.Squad.Size; i < count; ++i) {
char buffer[128];
if(player.Tactical.Squad.Agents[i] != -1) {
const ::klib::CCharacter & playerAgent = *player.Tactical.Army[player.Tactical.Squad.Agents[i]];
maxNameLen = ::gpk::max(maxNameLen, sprintf_s(buffer, "Agent #%u: %s", i + 1, playerAgent.Name.begin()));
menuItems[i] = ::gpk::view_const_string{buffer};
}
else {
maxNameLen = ::gpk::max(maxNameLen, sprintf_s(buffer, "Agent #%u: Empty slot", i + 1));
menuItems[i] = ::gpk::view_const_string{buffer};
}
menuItemsView[i] = menuItems[i];
}
static ::klib::SDrawMenuState menuState;
int32_t result = ::klib::drawMenu
( menuState
, instanceGame.GlobalDisplay.Screen.Color.View
, instanceGame.GlobalDisplay.Screen.DepthStencil.begin()
, ::gpk::view_const_string{"Squad setup"}
, ::gpk::view_array<const ::gpk::view_const_char>{menuItemsView.begin(), menuItemsView.size()}
, instanceGame.FrameInput
, -1
, ::gpk::max(24, maxNameLen+4)
);
if(menuItems.size() == (uint32_t)result)
return {::klib::GAME_STATE_WELCOME_COMMANDER};
if( result < 0 || result >= (int32_t)player.Tactical.Squad.Agents.size() )
return {::klib::GAME_STATE_MENU_SQUAD_SETUP};
player.Tactical.Selection.PlayerUnit = (int16_t)result;
if( player.Tactical.Squad.Agents[result] != -1 && 0 == instanceGame.FrameInput.Keys[VK_LSHIFT] )
return {::klib::GAME_STATE_MENU_EQUIPMENT};
return {::klib::GAME_STATE_MENU_EQUIPMENT, ::klib::GAME_SUBSTATE_CHARACTER};
}
| 43.941176
| 121
| 0.629183
|
asm128
|
02bf76daecd4b55313c0e9b8fc047c19960f1f06
| 1,341
|
cpp
|
C++
|
src/VKUFrame.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
src/VKUFrame.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
src/VKUFrame.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
#include "VKUFrame.h"
#include "VKUFormFactory.h"
#include "VKUPanelFactory.h"
#include "AppResourceId.h"
#include "ObjectCounter.h"
using namespace Tizen::Base;
using namespace Tizen::Ui;
using namespace Tizen::Ui::Controls;
using namespace Tizen::Ui::Scenes;
VKUFrame::VKUFrame(void) {
CONSTRUCT(L"VKUFrame");
}
VKUFrame::~VKUFrame(void) {
DESTRUCT(L"VKUFrame");
}
result VKUFrame::OnInitializing(void) {
result r = E_SUCCESS;
SceneManager* pSceneManager = SceneManager::GetInstance();
TryCatch(GetLastResult() == E_SUCCESS, r = GetLastResult(), "Failed SceneManager::GetInstance");
static VKUFormFactory formFactory;
static VKUPanelFactory panelFactory;
r = pSceneManager->RegisterFormFactory(formFactory);
TryCatch(r == E_SUCCESS, , "Failed RegisterFormFactory");
r = pSceneManager->RegisterPanelFactory(panelFactory);
TryCatch(r == E_SUCCESS, , "Failed RegisterPanelFactory");
r = pSceneManager->RegisterScene(L"workflow");
TryCatch(r == E_SUCCESS, , "Failed RegisterScene");
r = pSceneManager->GoForward(SceneTransitionId(ID_SCNT_START));
TryCatch(r == E_SUCCESS, , "Failed GoForward");
return r;
CATCH:
AppLogException("OnInitializing is failed.", GetErrorMessage(r));
return r;
}
result VKUFrame::OnTerminating(void) {
result r = E_SUCCESS;
// TODO:
// Add your termination code here
return r;
}
| 24.381818
| 97
| 0.747949
|
igorglotov
|
02bffe093fc3864ecef598ca30f7c1a97c7dfb76
| 19,213
|
cpp
|
C++
|
src/lib/Camera.cpp
|
edisonlee0212/UniEngine
|
62278ae811235179e6a1c24eb35acf73e400fe28
|
[
"BSD-3-Clause"
] | 22
|
2020-05-18T02:37:09.000Z
|
2022-03-13T18:44:30.000Z
|
src/lib/Camera.cpp
|
edisonlee0212/UniEngine
|
62278ae811235179e6a1c24eb35acf73e400fe28
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Camera.cpp
|
edisonlee0212/UniEngine
|
62278ae811235179e6a1c24eb35acf73e400fe28
|
[
"BSD-3-Clause"
] | 3
|
2020-12-21T01:21:03.000Z
|
2021-09-06T08:07:41.000Z
|
#include "AssetManager.hpp"
#include <Utilities.hpp>
#include <Camera.hpp>
#include <Cubemap.hpp>
#include <EditorManager.hpp>
#include <Gui.hpp>
#include <PostProcessing.hpp>
#include <RenderManager.hpp>
#include <SerializationManager.hpp>
#include <Texture2D.hpp>
using namespace UniEngine;
CameraInfoBlock Camera::m_cameraInfoBlock;
std::unique_ptr<OpenGLUtils::GLUBO> Camera::m_cameraUniformBufferBlock;
Plane::Plane() : m_a(0), m_b(0), m_c(0), m_d(0)
{
}
void Plane::Normalize()
{
const float mag = glm::sqrt(m_a * m_a + m_b * m_b + m_c * m_c);
m_a /= mag;
m_b /= mag;
m_c /= mag;
m_d /= mag;
}
void Camera::CalculatePlanes(std::vector<Plane> &planes, glm::mat4 projection, glm::mat4 view)
{
glm::mat4 comboMatrix = projection * glm::transpose(view);
planes[0].m_a = comboMatrix[3][0] + comboMatrix[0][0];
planes[0].m_b = comboMatrix[3][1] + comboMatrix[0][1];
planes[0].m_c = comboMatrix[3][2] + comboMatrix[0][2];
planes[0].m_d = comboMatrix[3][3] + comboMatrix[0][3];
planes[1].m_a = comboMatrix[3][0] - comboMatrix[0][0];
planes[1].m_b = comboMatrix[3][1] - comboMatrix[0][1];
planes[1].m_c = comboMatrix[3][2] - comboMatrix[0][2];
planes[1].m_d = comboMatrix[3][3] - comboMatrix[0][3];
planes[2].m_a = comboMatrix[3][0] - comboMatrix[1][0];
planes[2].m_b = comboMatrix[3][1] - comboMatrix[1][1];
planes[2].m_c = comboMatrix[3][2] - comboMatrix[1][2];
planes[2].m_d = comboMatrix[3][3] - comboMatrix[1][3];
planes[3].m_a = comboMatrix[3][0] + comboMatrix[1][0];
planes[3].m_b = comboMatrix[3][1] + comboMatrix[1][1];
planes[3].m_c = comboMatrix[3][2] + comboMatrix[1][2];
planes[3].m_d = comboMatrix[3][3] + comboMatrix[1][3];
planes[4].m_a = comboMatrix[3][0] + comboMatrix[2][0];
planes[4].m_b = comboMatrix[3][1] + comboMatrix[2][1];
planes[4].m_c = comboMatrix[3][2] + comboMatrix[2][2];
planes[4].m_d = comboMatrix[3][3] + comboMatrix[2][3];
planes[5].m_a = comboMatrix[3][0] - comboMatrix[2][0];
planes[5].m_b = comboMatrix[3][1] - comboMatrix[2][1];
planes[5].m_c = comboMatrix[3][2] - comboMatrix[2][2];
planes[5].m_d = comboMatrix[3][3] - comboMatrix[2][3];
planes[0].Normalize();
planes[1].Normalize();
planes[2].Normalize();
planes[3].Normalize();
planes[4].Normalize();
planes[5].Normalize();
}
void Camera::CalculateFrustumPoints(
const std::shared_ptr<Camera> &cameraComponrnt,
float nearPlane,
float farPlane,
glm::vec3 cameraPos,
glm::quat cameraRot,
glm::vec3 *points)
{
const glm::vec3 front = cameraRot * glm::vec3(0, 0, -1);
const glm::vec3 right = cameraRot * glm::vec3(1, 0, 0);
const glm::vec3 up = cameraRot * glm::vec3(0, 1, 0);
const glm::vec3 nearCenter = front * nearPlane;
const glm::vec3 farCenter = front * farPlane;
const float e = tanf(glm::radians(cameraComponrnt->m_fov * 0.5f));
const float near_ext_y = e * nearPlane;
const float near_ext_x = near_ext_y * cameraComponrnt->GetResolutionRatio();
const float far_ext_y = e * farPlane;
const float far_ext_x = far_ext_y * cameraComponrnt->GetResolutionRatio();
points[0] = cameraPos + nearCenter - right * near_ext_x - up * near_ext_y;
points[1] = cameraPos + nearCenter - right * near_ext_x + up * near_ext_y;
points[2] = cameraPos + nearCenter + right * near_ext_x + up * near_ext_y;
points[3] = cameraPos + nearCenter + right * near_ext_x - up * near_ext_y;
points[4] = cameraPos + farCenter - right * far_ext_x - up * far_ext_y;
points[5] = cameraPos + farCenter - right * far_ext_x + up * far_ext_y;
points[6] = cameraPos + farCenter + right * far_ext_x + up * far_ext_y;
points[7] = cameraPos + farCenter + right * far_ext_x - up * far_ext_y;
}
glm::quat Camera::ProcessMouseMovement(float yawAngle, float pitchAngle, bool constrainPitch)
{
// Make sure that when pitch is out of bounds, screen doesn't get flipped
if (constrainPitch)
{
if (pitchAngle > 89.0f)
pitchAngle = 89.0f;
if (pitchAngle < -89.0f)
pitchAngle = -89.0f;
}
glm::vec3 front;
front.x = cos(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle));
front.y = sin(glm::radians(pitchAngle));
front.z = sin(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle));
front = glm::normalize(front);
const glm::vec3 right = glm::normalize(glm::cross(
front, glm::vec3(0.0f, 1.0f, 0.0f))); // Normalize the vectors, because their length gets closer to 0 the more
// you look up or down which results in slower movement.
const glm::vec3 up = glm::normalize(glm::cross(right, front));
return glm::quatLookAt(front, up);
}
void Camera::ReverseAngle(const glm::quat &rotation, float &pitchAngle, float &yawAngle, const bool &constrainPitch)
{
const auto angle = glm::degrees(glm::eulerAngles(rotation));
pitchAngle = angle.x;
yawAngle = glm::abs(angle.z) > 90.0f ? 90.0f - angle.y : -90.0f - angle.y;
if (constrainPitch)
{
if (pitchAngle > 89.0f)
pitchAngle = 89.0f;
if (pitchAngle < -89.0f)
pitchAngle = -89.0f;
}
}
std::shared_ptr<Texture2D> Camera::GetTexture() const
{
return m_colorTexture;
}
std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferDepth()
{
return m_gBufferDepth;
}
std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferNormal()
{
return m_gBufferNormal;
}
std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferAlbedo()
{
return m_gBufferAlbedo;
}
std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferMetallicRoughnessEmissionAmbient()
{
return m_gBufferMetallicRoughnessEmissionAmbient;
}
glm::mat4 Camera::GetProjection() const
{
return glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance);
}
glm::vec3 Camera::Project(GlobalTransform <w, glm::vec3 position)
{
return m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view * glm::vec4(position, 1.0f);
}
glm::vec3 Camera::UnProject(GlobalTransform <w, glm::vec3 position) const
{
glm::mat4 inversed = glm::inverse(m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view);
glm::vec4 start = glm::vec4(position, 1.0f);
start = inversed * start;
return start / start.w;
}
glm::vec3 Camera::GetMouseWorldPoint(GlobalTransform <w, glm::vec2 mousePosition) const
{
const float halfX = static_cast<float>(m_resolutionX) / 2.0f;
const float halfY = static_cast<float>(m_resolutionY) / 2.0f;
const glm::vec4 start =
glm::vec4((mousePosition.x - halfX) / halfX, -1 * (mousePosition.y - halfY) / halfY, 0.0f, 1.0f);
return start / start.w;
}
void Camera::SetClearColor(glm::vec3 color) const
{
m_frameBuffer->ClearColor(glm::vec4(color.x, color.y, color.z, 0.0f));
m_frameBuffer->Clear();
m_frameBuffer->ClearColor(glm::vec4(0.0f));
}
Ray Camera::ScreenPointToRay(GlobalTransform <w, glm::vec2 mousePosition) const
{
const auto position = ltw.GetPosition();
const auto rotation = ltw.GetRotation();
const glm::vec3 front = rotation * glm::vec3(0, 0, -1);
const glm::vec3 up = rotation * glm::vec3(0, 1, 0);
const auto projection =
glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance);
const auto view = glm::lookAt(position, position + front, up);
const glm::mat4 inv = glm::inverse(projection * view);
const float halfX = static_cast<float>(m_resolutionX) / 2.0f;
const float halfY = static_cast<float>(m_resolutionY) / 2.0f;
const auto realX = (mousePosition.x + halfX) / halfX;
const auto realY = (mousePosition.y - halfY) / halfY;
if (glm::abs(realX) > 1.0f || glm::abs(realY) > 1.0f)
return {glm::vec3(FLT_MAX), glm::vec3(FLT_MAX)};
glm::vec4 start = glm::vec4(realX, -1 * realY, -1, 1.0);
glm::vec4 end = glm::vec4(realX, -1.0f * realY, 1.0f, 1.0f);
start = inv * start;
end = inv * end;
start /= start.w;
end /= end.w;
const glm::vec3 dir = glm::normalize(glm::vec3(end - start));
return {glm::vec3(ltw.m_value[3]) + m_nearDistance * dir, glm::vec3(ltw.m_value[3]) + m_farDistance * dir};
}
void Camera::GenerateMatrices()
{
m_cameraUniformBufferBlock = std::make_unique<OpenGLUtils::GLUBO>();
m_cameraUniformBufferBlock->SetData(sizeof(CameraInfoBlock), nullptr, GL_STREAM_DRAW);
m_cameraUniformBufferBlock->SetBase(0);
}
void Camera::ResizeResolution(int x, int y)
{
if (m_resolutionX == x && m_resolutionY == y)
return;
m_resolutionX = x > 0 ? x : 1;
m_resolutionY = y > 0 ? y : 1;
m_gBufferNormal->ReSize(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY);
m_gBufferDepth->ReSize(0, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, 0, m_resolutionX, m_resolutionY);
m_gBufferAlbedo->ReSize(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY);
m_gBufferMetallicRoughnessEmissionAmbient->ReSize(
0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY);
m_gBuffer->SetResolution(m_resolutionX, m_resolutionY);
m_colorTexture->m_texture->ReSize(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY);
m_depthStencilTexture->m_texture->ReSize(
0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0, m_resolutionX, m_resolutionY);
}
void Camera::OnCreate()
{
m_resolutionX = 1;
m_resolutionY = 1;
m_frameCount = 0;
m_colorTexture = AssetManager::CreateAsset<Texture2D>();
m_colorTexture->m_name = "CameraTexture";
m_colorTexture->m_texture =
std::make_shared<OpenGLUtils::GLTexture2D>(0, GL_RGBA16F, m_resolutionX, m_resolutionY, false);
m_colorTexture->m_texture->SetData(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0);
m_colorTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_colorTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
AttachTexture(m_colorTexture->m_texture.get(), GL_COLOR_ATTACHMENT0);
m_depthStencilTexture = AssetManager::CreateAsset<Texture2D>();
m_depthStencilTexture->m_texture =
std::make_shared<OpenGLUtils::GLTexture2D>(0, GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY, false);
m_depthStencilTexture->m_texture->SetData(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0);
m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
AttachTexture(m_depthStencilTexture->m_texture.get(), GL_DEPTH_STENCIL_ATTACHMENT);
m_gBuffer = std::make_unique<RenderTarget>(m_resolutionX, m_resolutionY);
m_gBufferDepth =
std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_DEPTH_COMPONENT32F, m_resolutionX, m_resolutionY, false);
m_gBufferDepth->SetData(0, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
m_gBufferDepth->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_gBufferDepth->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_gBufferDepth->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_gBufferDepth->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
m_gBuffer->AttachTexture(m_gBufferDepth.get(), GL_DEPTH_ATTACHMENT);
m_gBufferNormal = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGB16F, m_resolutionX, m_resolutionY, false);
m_gBufferNormal->SetData(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0);
m_gBufferNormal->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_gBufferNormal->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_gBufferNormal->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_gBufferNormal->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
m_gBuffer->AttachTexture(m_gBufferNormal.get(), GL_COLOR_ATTACHMENT0);
m_gBufferAlbedo = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGB16F, m_resolutionX, m_resolutionY, false);
m_gBufferAlbedo->SetData(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0);
m_gBufferAlbedo->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_gBufferAlbedo->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_gBufferAlbedo->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_gBufferAlbedo->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
m_gBuffer->AttachTexture(m_gBufferAlbedo.get(), GL_COLOR_ATTACHMENT1);
m_gBufferMetallicRoughnessEmissionAmbient =
std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGBA16F, m_resolutionX, m_resolutionY, false);
m_gBufferMetallicRoughnessEmissionAmbient->SetData(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0);
m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
m_gBuffer->AttachTexture(m_gBufferMetallicRoughnessEmissionAmbient.get(), GL_COLOR_ATTACHMENT2);
m_gBuffer->Clear();
SetEnabled(true);
}
void Camera::Serialize(YAML::Emitter &out)
{
out << YAML::Key << "m_resolutionX" << YAML::Value << m_resolutionX;
out << YAML::Key << "m_resolutionY" << YAML::Value << m_resolutionY;
out << YAML::Key << "m_useClearColor" << YAML::Value << m_useClearColor;
out << YAML::Key << "m_clearColor" << YAML::Value << m_clearColor;
out << YAML::Key << "m_allowAutoResize" << YAML::Value << m_allowAutoResize;
out << YAML::Key << "m_nearDistance" << YAML::Value << m_nearDistance;
out << YAML::Key << "m_farDistance" << YAML::Value << m_farDistance;
out << YAML::Key << "m_fov" << YAML::Value << m_fov;
m_skybox.Save("m_skybox", out);
}
void Camera::Deserialize(const YAML::Node &in)
{
int resolutionX = in["m_resolutionX"].as<int>();
int resolutionY = in["m_resolutionY"].as<int>();
m_useClearColor = in["m_useClearColor"].as<bool>();
m_clearColor = in["m_clearColor"].as<glm::vec3>();
m_allowAutoResize = in["m_allowAutoResize"].as<bool>();
m_nearDistance = in["m_nearDistance"].as<float>();
m_farDistance = in["m_farDistance"].as<float>();
m_fov = in["m_fov"].as<float>();
ResizeResolution(resolutionX, resolutionY);
m_skybox.Load("m_skybox", in);
}
void Camera::OnDestroy()
{
}
void Camera::OnInspect()
{
ImGui::Checkbox("Allow auto resize", &m_allowAutoResize);
if (!m_allowAutoResize)
{
glm::ivec2 resolution = {m_resolutionX, m_resolutionY};
if (ImGui::DragInt2("Resolution", &resolution.x))
{
ResizeResolution(resolution.x, resolution.y);
}
}
ImGui::Checkbox("Use clear color", &m_useClearColor);
const bool savedState = (this == EntityManager::GetCurrentScene()->m_mainCamera.Get<Camera>().get());
bool isMainCamera = savedState;
ImGui::Checkbox("Main Camera", &isMainCamera);
if (savedState != isMainCamera)
{
if (isMainCamera)
{
EntityManager::GetCurrentScene()->m_mainCamera = GetOwner().GetOrSetPrivateComponent<Camera>().lock();
}
else
{
EntityManager::GetCurrentScene()->m_mainCamera.Clear();
}
}
if (m_useClearColor)
{
ImGui::ColorEdit3("Clear Color", (float *)(void *)&m_clearColor);
}
else
{
EditorManager::DragAndDropButton<Cubemap>(m_skybox, "Skybox");
}
ImGui::DragFloat("Near", &m_nearDistance, m_nearDistance / 10.0f, 0, m_farDistance);
ImGui::DragFloat("Far", &m_farDistance, m_farDistance / 10.0f, m_nearDistance);
ImGui::DragFloat("FOV", &m_fov, 1.0f, 1, 359);
FileUtils::SaveFile("Screenshot", "Texture2D", {".png", ".jpg"}, [this](const std::filesystem::path &filePath) {
m_colorTexture->SetPathAndSave(filePath);
});
if (ImGui::TreeNode("Debug"))
{
static float debugSacle = 0.25f;
ImGui::DragFloat("Scale", &debugSacle, 0.01f, 0.1f, 1.0f);
debugSacle = glm::clamp(debugSacle, 0.1f, 1.0f);
ImGui::Image(
(ImTextureID)m_colorTexture->UnsafeGetGLTexture()->Id(),
ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle),
ImVec2(0, 1),
ImVec2(1, 0));
ImGui::Image(
(ImTextureID)m_gBufferNormal->Id(),
ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle),
ImVec2(0, 1),
ImVec2(1, 0));
ImGui::Image(
(ImTextureID)m_gBufferAlbedo->Id(),
ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle),
ImVec2(0, 1),
ImVec2(1, 0));
ImGui::Image(
(ImTextureID)m_gBufferMetallicRoughnessEmissionAmbient->Id(),
ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle),
ImVec2(0, 1),
ImVec2(1, 0));
ImGui::TreePop();
}
}
void Camera::PostCloneAction(const std::shared_ptr<IPrivateComponent> &target)
{
}
void Camera::Start()
{
}
void Camera::CollectAssetRef(std::vector<AssetRef> &list)
{
list.push_back(m_skybox);
}
std::shared_ptr<Texture2D> Camera::GetDepthStencil() const
{
return m_depthStencilTexture;
}
Camera &Camera::operator=(const Camera &source)
{
m_allowAutoResize = source.m_allowAutoResize;
m_nearDistance = source.m_nearDistance;
m_farDistance = source.m_farDistance;
m_fov = source.m_fov;
m_useClearColor = source.m_useClearColor;
m_clearColor = source.m_clearColor;
m_skybox = source.m_skybox;
return *this;
}
void CameraInfoBlock::UpdateMatrices(const std::shared_ptr<Camera> &camera, glm::vec3 position, glm::quat rotation)
{
const glm::vec3 front = rotation * glm::vec3(0, 0, -1);
const glm::vec3 up = rotation * glm::vec3(0, 1, 0);
const auto ratio = camera->GetResolutionRatio();
m_projection =
glm::perspective(glm::radians(camera->m_fov * 0.5f), ratio, camera->m_nearDistance, camera->m_farDistance);
m_position = glm::vec4(position, 0);
m_view = glm::lookAt(position, position + front, up);
m_inverseProjection = glm::inverse(m_projection);
m_inverseView = glm::inverse(m_view);
m_reservedParameters = glm::vec4(
camera->m_nearDistance,
camera->m_farDistance,
glm::tan(glm::radians(camera->m_fov * 0.5f)),
static_cast<float>(camera->m_resolutionX) / camera->m_resolutionY);
m_clearColor = glm::vec4(camera->m_clearColor, 1.0f);
if(camera->m_useClearColor){
m_clearColor.w = 1.0f;
}else{
m_clearColor.w = 0.0f;
}
}
void CameraInfoBlock::UploadMatrices(const std::shared_ptr<Camera> &camera) const
{
Camera::m_cameraUniformBufferBlock->SubData(0, sizeof(CameraInfoBlock), this);
}
| 40.61945
| 127
| 0.687451
|
edisonlee0212
|
02c14f97597e4f5c3756cb0597674a3ef166e17a
| 1,071
|
hpp
|
C++
|
src/modules/module_manager.hpp
|
ECP-VeloC/veloc
|
d27224029349b156f6420d764cf23547cf3f2b53
|
[
"MIT"
] | null | null | null |
src/modules/module_manager.hpp
|
ECP-VeloC/veloc
|
d27224029349b156f6420d764cf23547cf3f2b53
|
[
"MIT"
] | null | null | null |
src/modules/module_manager.hpp
|
ECP-VeloC/veloc
|
d27224029349b156f6420d764cf23547cf3f2b53
|
[
"MIT"
] | null | null | null |
#ifndef __MODULE_MANAGER_HPP
#define __MODULE_MANAGER_HPP
#include "common/command.hpp"
#include "common/status.hpp"
#include "common/config.hpp"
#include "modules/client_watchdog.hpp"
#include "modules/client_aggregator.hpp"
#include "modules/ec_module.hpp"
#include "modules/transfer_module.hpp"
#include "modules/chksum_module.hpp"
#include "modules/versioning_module.hpp"
#include <functional>
#include <vector>
#include <mpi.h>
class module_manager_t {
typedef std::function<int (const command_t &)> method_t;
std::vector<method_t> modules;
client_watchdog_t *watchdog = NULL;
transfer_module_t *transfer = NULL;
client_aggregator_t *ec_agg = NULL;
ec_module_t *redset = NULL;
chksum_module_t *chksum = NULL;
versioning_module_t *versioning = NULL;
public:
module_manager_t();
~module_manager_t();
void add_default(const config_t &cfg, MPI_Comm comm = MPI_COMM_NULL);
void add_module(const method_t &m) {
modules.push_back(m);
}
int notify_command(const command_t &c);
};
#endif // __MODULE_MANAGER_HPP
| 26.775
| 73
| 0.745098
|
ECP-VeloC
|
02c37cd234d326e4236068424db52eb986a1ee7f
| 8,678
|
cpp
|
C++
|
src/engine/input.cpp
|
Timurinyo/classic_game_template
|
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
|
[
"MIT"
] | null | null | null |
src/engine/input.cpp
|
Timurinyo/classic_game_template
|
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
|
[
"MIT"
] | null | null | null |
src/engine/input.cpp
|
Timurinyo/classic_game_template
|
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
|
[
"MIT"
] | null | null | null |
#include <engine/pch.h>
#include <engine/input.h>
namespace cgt
{
Input::ScancodeMappings GenerateScancodeMappings();
Input::ScancodeMappings Input::s_ScancodeMappings = GenerateScancodeMappings();
Input::Input(Input::InputProcessingMode mode)
: m_Mode(mode)
{
}
WindowEventControlFlow Input::ProcessWindowEvent(const SDL_Event& event)
{
bool eventHandled = false;
switch (event.type)
{
case SDL_KEYDOWN:
{
auto scancode = event.key.keysym.scancode;
SetKeyboardKeyState(m_Pressed, scancode, true);
SetKeyboardKeyState(m_Held, scancode, true);
eventHandled = true;
break;
}
case SDL_KEYUP:
{
auto scancode = event.key.keysym.scancode;
SetKeyboardKeyState(m_Held, scancode, false);
SetKeyboardKeyState(m_Released, scancode, true);
eventHandled = true;
break;
}
case SDL_MOUSEBUTTONDOWN:
{
u8 buttonIndex = event.button.button;
SetMouseButtonState(m_Pressed, buttonIndex, true);
SetMouseButtonState(m_Held, buttonIndex, true);
eventHandled = true;
break;
}
case SDL_MOUSEBUTTONUP:
{
u8 buttonIndex = event.button.button;
SetMouseButtonState(m_Held, buttonIndex, false);
SetMouseButtonState(m_Released, buttonIndex, true);
eventHandled = true;
break;
}
case SDL_MOUSEWHEEL:
i32 motion = event.wheel.y;
m_MouseWheelMotion += motion;
eventHandled = true;
break;
}
if (eventHandled && m_Mode == InputProcessingMode::Consume)
{
return WindowEventControlFlow::ConsumeEvent;
}
return WindowEventControlFlow::PassthroughEvent;
}
void Input::NewFrame()
{
m_Pressed.reset();
m_Released.reset();
m_MouseWheelMotion = 0;
}
bool Input::IsKeyPressed(KeyCode keyCode) const
{
return Get(m_Pressed, keyCode);
}
bool Input::IsKeyReleased(KeyCode keyCode) const
{
return Get(m_Released, keyCode);
}
bool Input::IsKeyHeld(KeyCode keyCode) const
{
return Get(m_Held, keyCode);
}
glm::ivec2 Input::GetMousePosition() const
{
glm::ivec2 position;
SDL_GetMouseState(&position.x, &position.y);
return position;
}
i32 Input::GetMouseWheelMotion() const
{
return m_MouseWheelMotion;
}
bool Input::Get(const Input::KeysBitset& bitset, KeyCode key) const
{
if (key == KeyCode::Any)
{
return bitset.any();
}
return bitset.test((usize)key);
}
void Input::SetKeyboardKeyState(KeysBitset& bitset, SDL_Scancode scancode, bool active)
{
CGT_ASSERT(scancode < s_ScancodeMappings.size());
const auto keyCode = s_ScancodeMappings[scancode];
if (keyCode != KeyCode::Any)
{
bitset.set((usize)keyCode, active);
}
}
void Input::SetMouseButtonState(KeysBitset& bitset, u8 buttonIndex, bool active)
{
auto keyCode = KeyCode::Any;
switch (buttonIndex)
{
case SDL_BUTTON_LEFT:
keyCode = KeyCode::LeftMouseButton;
break;
case SDL_BUTTON_RIGHT:
keyCode = KeyCode::RightMouseButton;
break;
case SDL_BUTTON_MIDDLE:
keyCode = KeyCode::MiddleMouseButton;
break;
}
if (keyCode != KeyCode::Any)
{
bitset.set((usize)keyCode, active);
}
}
void Input::Reset()
{
m_Pressed.reset();
m_Held.reset();
m_Released.reset();
m_MouseWheelMotion = 0;
}
Input::ScancodeMappings GenerateScancodeMappings()
{
Input::ScancodeMappings mappings;
mappings[SDL_SCANCODE_A] = KeyCode::A;
mappings[SDL_SCANCODE_B] = KeyCode::B;
mappings[SDL_SCANCODE_C] = KeyCode::C;
mappings[SDL_SCANCODE_D] = KeyCode::D;
mappings[SDL_SCANCODE_E] = KeyCode::E;
mappings[SDL_SCANCODE_F] = KeyCode::F;
mappings[SDL_SCANCODE_G] = KeyCode::G;
mappings[SDL_SCANCODE_H] = KeyCode::H;
mappings[SDL_SCANCODE_I] = KeyCode::I;
mappings[SDL_SCANCODE_J] = KeyCode::J;
mappings[SDL_SCANCODE_K] = KeyCode::K;
mappings[SDL_SCANCODE_L] = KeyCode::L;
mappings[SDL_SCANCODE_M] = KeyCode::M;
mappings[SDL_SCANCODE_N] = KeyCode::N;
mappings[SDL_SCANCODE_O] = KeyCode::O;
mappings[SDL_SCANCODE_P] = KeyCode::P;
mappings[SDL_SCANCODE_Q] = KeyCode::Q;
mappings[SDL_SCANCODE_R] = KeyCode::R;
mappings[SDL_SCANCODE_S] = KeyCode::S;
mappings[SDL_SCANCODE_T] = KeyCode::T;
mappings[SDL_SCANCODE_U] = KeyCode::U;
mappings[SDL_SCANCODE_V] = KeyCode::V;
mappings[SDL_SCANCODE_W] = KeyCode::W;
mappings[SDL_SCANCODE_X] = KeyCode::X;
mappings[SDL_SCANCODE_Y] = KeyCode::Y;
mappings[SDL_SCANCODE_Z] = KeyCode::Z;
mappings[SDL_SCANCODE_1] = KeyCode::Number1;
mappings[SDL_SCANCODE_2] = KeyCode::Number2;
mappings[SDL_SCANCODE_3] = KeyCode::Number3;
mappings[SDL_SCANCODE_4] = KeyCode::Number4;
mappings[SDL_SCANCODE_5] = KeyCode::Number5;
mappings[SDL_SCANCODE_6] = KeyCode::Number6;
mappings[SDL_SCANCODE_7] = KeyCode::Number7;
mappings[SDL_SCANCODE_8] = KeyCode::Number8;
mappings[SDL_SCANCODE_9] = KeyCode::Number9;
mappings[SDL_SCANCODE_0] = KeyCode::Number0;
mappings[SDL_SCANCODE_RETURN] = KeyCode::Return;
mappings[SDL_SCANCODE_ESCAPE] = KeyCode::Escape;
mappings[SDL_SCANCODE_BACKSPACE] = KeyCode::Backspace;
mappings[SDL_SCANCODE_TAB] = KeyCode::Tab;
mappings[SDL_SCANCODE_SPACE] = KeyCode::Space;
mappings[SDL_SCANCODE_MINUS] = KeyCode::Minus;
mappings[SDL_SCANCODE_EQUALS] = KeyCode::Equals;
mappings[SDL_SCANCODE_LEFTBRACKET] = KeyCode::LeftBracket;
mappings[SDL_SCANCODE_RIGHTBRACKET] = KeyCode::RightBracket;
mappings[SDL_SCANCODE_BACKSLASH] = KeyCode::Backslash;
mappings[SDL_SCANCODE_SEMICOLON] = KeyCode::Semicolon;
mappings[SDL_SCANCODE_APOSTROPHE] = KeyCode::Apostrophe;
mappings[SDL_SCANCODE_GRAVE] = KeyCode::Grave;
mappings[SDL_SCANCODE_COMMA] = KeyCode::Comma;
mappings[SDL_SCANCODE_PERIOD] = KeyCode::Period;
mappings[SDL_SCANCODE_SLASH] = KeyCode::Slash;
mappings[SDL_SCANCODE_CAPSLOCK] = KeyCode::Capslock;
mappings[SDL_SCANCODE_F1] = KeyCode::F1;
mappings[SDL_SCANCODE_F2] = KeyCode::F2;
mappings[SDL_SCANCODE_F3] = KeyCode::F3;
mappings[SDL_SCANCODE_F4] = KeyCode::F4;
mappings[SDL_SCANCODE_F5] = KeyCode::F5;
mappings[SDL_SCANCODE_F6] = KeyCode::F6;
mappings[SDL_SCANCODE_F7] = KeyCode::F7;
mappings[SDL_SCANCODE_F8] = KeyCode::F8;
mappings[SDL_SCANCODE_F9] = KeyCode::F9;
mappings[SDL_SCANCODE_F10] = KeyCode::F10;
mappings[SDL_SCANCODE_F11] = KeyCode::F11;
mappings[SDL_SCANCODE_F12] = KeyCode::F12;
mappings[SDL_SCANCODE_PRINTSCREEN] = KeyCode::Printscreen;
mappings[SDL_SCANCODE_SCROLLLOCK] = KeyCode::Scrolllock;
mappings[SDL_SCANCODE_PAUSE] = KeyCode::Pause;
mappings[SDL_SCANCODE_INSERT] = KeyCode::Insert;
mappings[SDL_SCANCODE_HOME] = KeyCode::Home;
mappings[SDL_SCANCODE_PAGEUP] = KeyCode::PageUp;
mappings[SDL_SCANCODE_DELETE] = KeyCode::Delete;
mappings[SDL_SCANCODE_END] = KeyCode::End;
mappings[SDL_SCANCODE_PAGEDOWN] = KeyCode::PageDown;
mappings[SDL_SCANCODE_RIGHT] = KeyCode::Right;
mappings[SDL_SCANCODE_LEFT] = KeyCode::Left;
mappings[SDL_SCANCODE_DOWN] = KeyCode::Down;
mappings[SDL_SCANCODE_UP] = KeyCode::Up;
mappings[SDL_SCANCODE_KP_DIVIDE] = KeyCode::NumPadDivide;
mappings[SDL_SCANCODE_KP_MULTIPLY] = KeyCode::NumPadMultiply;
mappings[SDL_SCANCODE_KP_MINUS] = KeyCode::NumPadMinus;
mappings[SDL_SCANCODE_KP_PLUS] = KeyCode::NumPadPlus;
mappings[SDL_SCANCODE_KP_ENTER] = KeyCode::NumPadEnter;
mappings[SDL_SCANCODE_KP_1] = KeyCode::NumPad1;
mappings[SDL_SCANCODE_KP_2] = KeyCode::NumPad2;
mappings[SDL_SCANCODE_KP_3] = KeyCode::NumPad3;
mappings[SDL_SCANCODE_KP_4] = KeyCode::NumPad4;
mappings[SDL_SCANCODE_KP_5] = KeyCode::NumPad5;
mappings[SDL_SCANCODE_KP_6] = KeyCode::NumPad6;
mappings[SDL_SCANCODE_KP_7] = KeyCode::NumPad7;
mappings[SDL_SCANCODE_KP_8] = KeyCode::NumPad8;
mappings[SDL_SCANCODE_KP_9] = KeyCode::NumPad9;
mappings[SDL_SCANCODE_KP_0] = KeyCode::NumPad0;
mappings[SDL_SCANCODE_KP_PERIOD] = KeyCode::NumPadPeriod;
mappings[SDL_SCANCODE_KP_COMMA] = KeyCode::NumPadComma;
mappings[SDL_SCANCODE_LCTRL] = KeyCode::LeftCtrl;
mappings[SDL_SCANCODE_LSHIFT] = KeyCode::LeftShift;
mappings[SDL_SCANCODE_LALT] = KeyCode::LeftAlt;
mappings[SDL_SCANCODE_LGUI] = KeyCode::LeftGui;
mappings[SDL_SCANCODE_RCTRL] = KeyCode::RightCtrl;
mappings[SDL_SCANCODE_RSHIFT] = KeyCode::RightShift;
mappings[SDL_SCANCODE_RALT] = KeyCode::RightAlt;
mappings[SDL_SCANCODE_RGUI] = KeyCode::RightGui;
return mappings;
}
}
| 31.787546
| 87
| 0.707536
|
Timurinyo
|
02ca5391639149cdef1c7023f5df3d4e3e3c158a
| 40
|
hpp
|
C++
|
engine/src/Engine.hpp
|
codekrafter/CodekraftEngine
|
c0965b74dc4926e4612e1ff953be248acceb3198
|
[
"MIT"
] | null | null | null |
engine/src/Engine.hpp
|
codekrafter/CodekraftEngine
|
c0965b74dc4926e4612e1ff953be248acceb3198
|
[
"MIT"
] | 1
|
2018-06-26T14:00:35.000Z
|
2018-06-26T14:00:57.000Z
|
engine/src/Engine.hpp
|
codekrafter/CodekraftEngine
|
c0965b74dc4926e4612e1ff953be248acceb3198
|
[
"MIT"
] | 1
|
2018-03-28T18:19:19.000Z
|
2018-03-28T18:19:19.000Z
|
#pragma once
#include "Core/Engine.hpp"
| 13.333333
| 26
| 0.75
|
codekrafter
|
02ca54d8208161ca2a9bcca46891d4c941d5fcf4
| 2,788
|
cpp
|
C++
|
src/opts/SkBlitRow_opts_SSE4.cpp
|
Perspex/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | 27
|
2016-04-27T01:02:03.000Z
|
2021-12-13T08:53:19.000Z
|
src/opts/SkBlitRow_opts_SSE4.cpp
|
AvaloniaUI/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | 2
|
2017-03-09T09:00:50.000Z
|
2017-09-21T15:48:20.000Z
|
src/opts/SkBlitRow_opts_SSE4.cpp
|
AvaloniaUI/skia
|
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
|
[
"Apache-2.0"
] | 17
|
2016-04-27T02:06:39.000Z
|
2019-12-18T08:07:00.000Z
|
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBlitRow_opts_SSE4.h"
// Some compilers can't compile SSSE3 or SSE4 intrinsics. We give them stub methods.
// The stubs should never be called, so we make them crash just to confirm that.
#if SK_CPU_SSE_LEVEL < SK_CPU_SSE_LEVEL_SSE41
void S32A_Opaque_BlitRow32_SSE4(SkPMColor* SK_RESTRICT, const SkPMColor* SK_RESTRICT, int, U8CPU) {
sk_throw();
}
#else
#include <smmintrin.h> // SSE4.1 intrinsics
#include "SkColorPriv.h"
#include "SkColor_opts_SSE2.h"
void S32A_Opaque_BlitRow32_SSE4(SkPMColor* SK_RESTRICT dst,
const SkPMColor* SK_RESTRICT src,
int count,
U8CPU alpha) {
SkASSERT(alpha == 255);
// As long as we can, we'll work on 16 pixel pairs at once.
int count16 = count / 16;
__m128i* dst4 = (__m128i*)dst;
const __m128i* src4 = (const __m128i*)src;
for (int i = 0; i < count16 * 4; i += 4) {
// Load 16 source pixels.
__m128i s0 = _mm_loadu_si128(src4+i+0),
s1 = _mm_loadu_si128(src4+i+1),
s2 = _mm_loadu_si128(src4+i+2),
s3 = _mm_loadu_si128(src4+i+3);
const __m128i alphaMask = _mm_set1_epi32(0xFF << SK_A32_SHIFT);
const __m128i ORed = _mm_or_si128(s3, _mm_or_si128(s2, _mm_or_si128(s1, s0)));
if (_mm_testz_si128(ORed, alphaMask)) {
// All 16 source pixels are fully transparent. There's nothing to do!
continue;
}
const __m128i ANDed = _mm_and_si128(s3, _mm_and_si128(s2, _mm_and_si128(s1, s0)));
if (_mm_testc_si128(ANDed, alphaMask)) {
// All 16 source pixels are fully opaque. There's no need to read dst or blend it.
_mm_storeu_si128(dst4+i+0, s0);
_mm_storeu_si128(dst4+i+1, s1);
_mm_storeu_si128(dst4+i+2, s2);
_mm_storeu_si128(dst4+i+3, s3);
continue;
}
// The general slow case: do the blend for all 16 pixels.
_mm_storeu_si128(dst4+i+0, SkPMSrcOver_SSE2(s0, _mm_loadu_si128(dst4+i+0)));
_mm_storeu_si128(dst4+i+1, SkPMSrcOver_SSE2(s1, _mm_loadu_si128(dst4+i+1)));
_mm_storeu_si128(dst4+i+2, SkPMSrcOver_SSE2(s2, _mm_loadu_si128(dst4+i+2)));
_mm_storeu_si128(dst4+i+3, SkPMSrcOver_SSE2(s3, _mm_loadu_si128(dst4+i+3)));
}
// Wrap up the last <= 15 pixels.
for (int i = count16*16; i < count; i++) {
// This check is not really necessarily, but it prevents pointless autovectorization.
if (src[i] & 0xFF000000) {
dst[i] = SkPMSrcOver(src[i], dst[i]);
}
}
}
#endif
| 38.722222
| 99
| 0.620875
|
Perspex
|
c49cd43e742500e91bd39afa0b55d12bcacc9318
| 41,168
|
hpp
|
C++
|
include/cascade/detail/cascade_impl.hpp
|
Thompson-Liu/cascade
|
283d99eb70da99ac1d11611037e9750397c5d011
|
[
"BSD-3-Clause"
] | null | null | null |
include/cascade/detail/cascade_impl.hpp
|
Thompson-Liu/cascade
|
283d99eb70da99ac1d11611037e9750397c5d011
|
[
"BSD-3-Clause"
] | null | null | null |
include/cascade/detail/cascade_impl.hpp
|
Thompson-Liu/cascade
|
283d99eb70da99ac1d11611037e9750397c5d011
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <memory>
#include <map>
namespace derecho {
namespace cascade {
#define debug_enter_func_with_args(format,...) \
dbg_default_debug("Entering {} with parameter:" #format ".", __func__, __VA_ARGS__)
#define debug_leave_func_with_value(format,...) \
dbg_default_debug("Leaving {} with " #format "." , __func__, __VA_ARGS__)
#define debug_enter_func() dbg_default_debug("Entering {}.")
#define debug_leave_func() dbg_default_debug("Leaving {}.")
///////////////////////////////////////////////////////////////////////////////
// 1 - Volatile Cascade Store Implementation
///////////////////////////////////////////////////////////////////////////////
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::put(const VT& value) const {
debug_enter_func_with_args("value.get_key_ref={}",value.get_key_ref());
derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_put)>(value);
auto& replies = results.get();
std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0);
// TODO: verfiy consistency ?
for (auto& reply_pair : replies) {
ret = reply_pair.second.get();
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret));
return ret;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::remove(const KT& key) const {
debug_enter_func_with_args("key={}",key);
derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_remove)>(key);
auto& replies = results.get();
std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0);
// TODO: verify consistency ?
for (auto& reply_pair : replies) {
ret = reply_pair.second.get();
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret));
return ret;
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT VolatileCascadeStore<KT,VT,IK,IV>::get(const KT& key, const persistent::version_t& ver, bool) const {
debug_enter_func_with_args("key={},ver=0x{:x}",key,ver);
if (ver != CURRENT_VERSION) {
debug_leave_func_with_value("Cannot support versioned get, ver=0x{:x}", ver);
return *IV;
}
derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get)>(key);
auto& replies = results.get();
// TODO: verify consistency ?
// for (auto& reply_pair : replies) {
// ret = reply_pair.second.get();
// }
debug_leave_func();
return replies.begin()->second.get();
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT VolatileCascadeStore<KT,VT,IK,IV>::get_by_time(const KT& key, const uint64_t& ts_us) const {
// VolatileCascadeStore does not support this.
debug_enter_func();
debug_leave_func();
return *IV;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::list_keys(const persistent::version_t& ver) const {
debug_enter_func_with_args("ver=0x{:x}",ver);
if (ver != CURRENT_VERSION) {
debug_leave_func_with_value("Cannot support versioned list_keys, ver=0x{:x}", ver);
return {};
}
derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_list_keys)>();
auto& replies = results.get();
std::vector<KT> ret;
// TODO: verfity consistency ?
for (auto& reply_pair : replies) {
ret = reply_pair.second.get();
}
debug_leave_func();
return ret;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::list_keys_by_time(const uint64_t& ts_us) const {
// VolatileCascadeStore does not support this.
debug_enter_func_with_args("ts_us=0x{:x}", ts_us);
debug_leave_func();
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t VolatileCascadeStore<KT,VT,IK,IV>::get_size(const KT& key, const persistent::version_t& ver, bool) const {
debug_enter_func_with_args("key={},ver=0x{:x}",key,ver);
if (ver != CURRENT_VERSION) {
debug_leave_func_with_value("Cannot support versioned get, ver=0x{:x}", ver);
return 0;
}
derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get_size)>(key);
auto& replies = results.get();
// TODO: verify consistency ?
// for (auto& reply_pair : replies) {
// ret = reply_pair.second.get();
// }
debug_leave_func();
return replies.begin()->second.get();
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t VolatileCascadeStore<KT,VT,IK,IV>::get_size_by_time(const KT& key, const uint64_t& ts_us) const {
// VolatileCascadeStore does not support this.
debug_enter_func();
debug_leave_func();
return 0;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::ordered_list_keys() {
std::vector<KT> key_list;
debug_enter_func();
for(auto kv: this->kv_map) {
key_list.push_back(kv.first);
}
debug_leave_func();
return key_list;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::ordered_put(const VT& value) {
debug_enter_func_with_args("key={}",value.get_key_ref());
std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_next_version();
if constexpr (std::is_base_of<IKeepVersion,VT>::value) {
value.set_version(std::get<0>(version_and_timestamp));
}
if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) {
value.set_timestamp(std::get<1>(version_and_timestamp));
}
// Verify previous version MUST happen before update previous versions.
if constexpr (std::is_base_of<IVerifyPreviousVersion,VT>::value) {
bool verify_result;
if (this->kv_map.find(value.get_key_ref())!=this->kv_map.end()) {
verify_result = value.verify_previous_version(this->update_version,this->kv_map.at(value.get_key_ref()).get_version());
} else {
verify_result = value.verify_previous_version(this->update_version,persistent::INVALID_VERSION);
}
if (!verify_result) {
// reject the update by returning an invalid version and timestamp
return {persistent::INVALID_VERSION,0};
}
}
if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) {
if (this->kv_map.find(value.get_key_ref())!=this->kv_map.end()) {
value.set_previous_version(this->update_version,this->kv_map.at(value.get_key_ref()).get_version());
} else {
value.set_previous_version(this->update_version,persistent::INVALID_VERSION);
}
}
this->kv_map.erase(value.get_key_ref()); // remove
this->kv_map.emplace(value.get_key_ref(), value); // copy constructor
this->update_version = std::get<0>(version_and_timestamp);
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
// group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id
this->subgroup_index, // this is subgroup index
group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_shard_num(),
value.get_key_ref(), value, cascade_context_ptr);
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return version_and_timestamp;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::ordered_remove(const KT& key) {
debug_enter_func_with_args("key={}",key);
std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_next_version();
if (this->kv_map.find(key)==this->kv_map.end()) {
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return version_and_timestamp;
}
auto value = create_null_object_cb<KT,VT,IK,IV>(key);
if constexpr (std::is_base_of<IKeepVersion,VT>::value) {
value.set_version(std::get<0>(version_and_timestamp));
}
if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) {
value.set_timestamp(std::get<1>(version_and_timestamp));
}
if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) {
if (this->kv_map.find(key)!=this->kv_map.end()) {
value.set_previous_version(this->update_version,this->kv_map.at(key).get_version());
} else {
value.set_previous_version(this->update_version,persistent::INVALID_VERSION);
}
}
this->kv_map.erase(key); // remove
this->kv_map.emplace(key, value);
this->update_version = std::get<0>(version_and_timestamp);
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
// group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id
this->subgroup_index,
group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_shard_num(),
key, value,cascade_context_ptr);
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return version_and_timestamp;
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT VolatileCascadeStore<KT,VT,IK,IV>::ordered_get(const KT& key) {
debug_enter_func_with_args("key={}",key);
if (this->kv_map.find(key) != this->kv_map.end()) {
debug_leave_func_with_value("key={}",key);
return this->kv_map.at(key);
} else {
debug_leave_func();
return *IV;
}
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t VolatileCascadeStore<KT,VT,IK,IV>::ordered_get_size(const KT& key) {
debug_enter_func_with_args("key={}",key);
if (this->kv_map.find(key) != this->kv_map.end()) {
return mutils::bytes_size(this->kv_map.at(key));
} else {
debug_leave_func();
return 0;
}
}
template<typename KT, typename VT, KT* IK, VT* IV>
void VolatileCascadeStore<KT,VT,IK,IV>::trigger_put(const VT& value) const {
debug_enter_func_with_args("key={}",value.get_key_ref());
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
this->subgroup_index,
group->template get_subgroup<VolatileCascadeStore<KT,VT,IK,IV>>(this->subgroup_index).get_shard_num(),
value.get_key_ref(), value, cascade_context_ptr, true);
}
debug_leave_func();
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::unique_ptr<VolatileCascadeStore<KT,VT,IK,IV>> VolatileCascadeStore<KT,VT,IK,IV>::from_bytes(
mutils::DeserializationManager* dsm,
char const* buf) {
auto kv_map_ptr = mutils::from_bytes<std::map<KT,VT>>(dsm,buf);
auto update_version_ptr = mutils::from_bytes<persistent::version_t>(dsm,buf+mutils::bytes_size(*kv_map_ptr));
auto volatile_cascade_store_ptr =
std::make_unique<VolatileCascadeStore>(std::move(*kv_map_ptr),
*update_version_ptr,
dsm->registered<CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>>()):nullptr,
dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr);
return volatile_cascade_store_ptr;
}
template<typename KT, typename VT, KT* IK, VT* IV>
VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore(
CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
update_version(persistent::INVALID_VERSION),
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {
debug_enter_func();
debug_leave_func();
}
template<typename KT, typename VT, KT* IK, VT* IV>
VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore(
const std::map<KT,VT>& _kvm,
persistent::version_t _uv,
CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
kv_map(_kvm),
update_version(_uv),
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {
debug_enter_func_with_args("copy to kv_map, size={}",kv_map.size());
debug_leave_func();
}
template<typename KT, typename VT, KT* IK, VT* IV>
VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore(
std::map<KT,VT>&& _kvm,
persistent::version_t _uv,
CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
kv_map(std::move(_kvm)),
update_version(_uv),
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {
debug_enter_func_with_args("move to kv_map, size={}",kv_map.size());
debug_leave_func();
}
///////////////////////////////////////////////////////////////////////////////
// 2 - Persistent Cascade Store Implementation
///////////////////////////////////////////////////////////////////////////////
template <typename KT, typename VT, KT* IK, VT* IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::set_data_len(const size_t& dlen) {
assert(capacity >= dlen);
this->len = dlen;
}
template <typename KT, typename VT, KT* IK, VT* IV>
char* DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::data_ptr() {
assert(buffer != nullptr);
return buffer;
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::calibrate(const size_t& dlen) {
size_t new_cap = dlen;
if(this->capacity >= new_cap) {
return;
}
// calculate new capacity
int width = sizeof(size_t) << 3;
int right_shift_bits = 1;
new_cap--;
while(right_shift_bits < width) {
new_cap |= new_cap >> right_shift_bits;
right_shift_bits = right_shift_bits << 1;
}
new_cap++;
// resize
this->buffer = (char*)realloc(buffer, new_cap);
if(this->buffer == nullptr) {
dbg_default_crit("{}:{} Failed to allocate delta buffer. errno={}", __FILE__, __LINE__, errno);
throw derecho::derecho_exception("Failed to allocate delta buffer.");
} else {
this->capacity = new_cap;
}
}
template <typename KT, typename VT, KT* IK, VT *IV>
bool DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::is_empty() {
return (this->len == 0);
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::clean() {
this->len = 0;
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::destroy() {
if(this->capacity > 0) {
free(this->buffer);
}
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::initialize_delta() {
delta.buffer = (char*)malloc(DEFAULT_DELTA_BUFFER_CAPACITY);
if (delta.buffer == nullptr) {
dbg_default_crit("{}:{} Failed to allocate delta buffer. errno={}", __FILE__, __LINE__, errno);
throw derecho::derecho_exception("Failed to allocate delta buffer.");
}
delta.capacity = DEFAULT_DELTA_BUFFER_CAPACITY;
delta.len = 0;
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::finalizeCurrentDelta(const persistent::DeltaFinalizer& df) {
df(this->delta.buffer, this->delta.len);
this->delta.clean();
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::applyDelta(char const* const delta) {
apply_ordered_put(*mutils::from_bytes<VT>(nullptr,delta));
mutils::deserialize_and_run(nullptr,delta,[this](const VT& value){
this->apply_ordered_put(value);
});
}
template <typename KT, typename VT, KT* IK, VT *IV>
void DeltaCascadeStoreCore<KT,VT,IK,IV>::apply_ordered_put(const VT& value) {
this->kv_map.erase(value.get_key_ref());
this->kv_map.emplace(value.get_key_ref(),value);
}
template <typename KT, typename VT, KT* IK, VT *IV>
std::unique_ptr<DeltaCascadeStoreCore<KT,VT,IK,IV>> DeltaCascadeStoreCore<KT,VT,IK,IV>::create(mutils::DeserializationManager* dm) {
if (dm != nullptr) {
try {
return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>();
} catch (...) {
}
}
return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>();
}
template <typename KT, typename VT, KT* IK, VT *IV>
bool DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_put(const VT& value, persistent::version_t prev_ver) {
// verify version MUST happen before updating it's previous versions (prev_ver,prev_ver_by_key).
if constexpr (std::is_base_of<IVerifyPreviousVersion,VT>::value) {
bool verify_result;
if (kv_map.find(value.get_key_ref())!=this->kv_map.end()) {
verify_result = value.verify_previous_version(prev_ver,this->kv_map.at(value.get_key_ref()).get_version());
} else {
verify_result = value.verify_previous_version(prev_ver,persistent::INVALID_VERSION);
}
if (!verify_result) {
// reject the package if verify failed.
return false;
}
}
if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) {
persistent::version_t prev_ver_by_key = persistent::INVALID_VERSION;
if (kv_map.find(value.get_key_ref()) != kv_map.end()) {
prev_ver_by_key = kv_map.at(value.get_key_ref()).get_version();
}
value.set_previous_version(prev_ver,prev_ver_by_key);
}
// create delta.
assert(this->delta.is_empty());
this->delta.calibrate(mutils::bytes_size(value));
mutils::to_bytes(value,this->delta.data_ptr());
this->delta.set_data_len(mutils::bytes_size(value));
// apply_ordered_put
apply_ordered_put(value);
return true;
}
template <typename KT, typename VT, KT* IK, VT *IV>
bool DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_remove(const VT& value, persistent::version_t prev_ver) {
auto& key = value.get_key_ref();
// test if key exists
if (kv_map.find(key) == kv_map.end()) {
// skip it when no such key.
return false;
} else if (kv_map.at(key).is_null()) {
// and skip the keys has been deleted already.
return false;
}
if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) {
value.set_previous_version(prev_ver,kv_map.at(key).get_version());
}
// create delta.
assert(this->delta.is_empty());
this->delta.calibrate(mutils::bytes_size(value));
mutils::to_bytes(value,this->delta.data_ptr());
this->delta.set_data_len(mutils::bytes_size(value));
// apply_ordered_put
apply_ordered_put(value);
return true;
}
template <typename KT, typename VT, KT* IK, VT* IV>
const VT DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_get(const KT& key) {
if (kv_map.find(key) != kv_map.end()) {
return kv_map.at(key);
} else {
return *IV;
}
}
template <typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_list_keys() {
std::vector<KT> key_list;
for (auto& kv: kv_map) {
key_list.push_back(kv.first);
}
return key_list;
}
template <typename KT, typename VT, KT* IK, VT* IV>
uint64_t DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_get_size(const KT& key) {
if (kv_map.find(key) != kv_map.end()) {
return mutils::bytes_size(kv_map.at(key));
} else {
return 0;
}
}
template <typename KT, typename VT, KT* IK, VT* IV>
DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore() {
initialize_delta();
}
template <typename KT, typename VT, KT* IK, VT* IV>
DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore(const std::map<KT,VT>& _kv_map): kv_map(_kv_map) {
initialize_delta();
}
template <typename KT, typename VT, KT* IK, VT* IV>
DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore(std::map<KT,VT>&& _kv_map): kv_map(_kv_map) {
initialize_delta();
}
template<typename KT, typename VT, KT* IK, VT* IV>
DeltaCascadeStoreCore<KT,VT,IK,IV>::~DeltaCascadeStoreCore() {
if (this->delta.buffer != nullptr) {
free(this->delta.buffer);
}
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::put(const VT& value) const {
debug_enter_func_with_args("value.get_key_ref()={}",value.get_key_ref());
derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_put)>(value);
auto& replies = results.get();
std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0);
// TODO: verfiy consistency ?
for (auto& reply_pair : replies) {
ret = reply_pair.second.get();
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret));
return ret;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::remove(const KT& key) const {
debug_enter_func_with_args("key={}",key);
derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_remove)>(key);
auto& replies = results.get();
std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0);
// TODO: verify consistency ?
for (auto& reply_pair : replies) {
ret = reply_pair.second.get();
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret));
return ret;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::get(const KT& key, const persistent::version_t& ver, bool exact) const {
debug_enter_func_with_args("key={},ver=0x{:x}",key,ver);
if (ver != CURRENT_VERSION) {
debug_leave_func();
return persistent_core.template getDelta<VT>(ver, [&key,ver,exact,this](const VT& v){
if (key == v.get_key_ref()) {
return v;
} else {
if (exact) {
// return invalid object for EXACT search.
return *IV;
} else {
// fall back to the slow path.
auto versioned_state_ptr = persistent_core.get(ver);
if (versioned_state_ptr->kv_map.find(key) != versioned_state_ptr->kv_map.end()) {
return versioned_state_ptr->kv_map.at(key);
}
return *IV;
}
}
});
}
derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get)>(key);
auto& replies = results.get();
// TODO: verify consistency ?
// for (auto& reply_pair : replies) {
// ret = reply_pair.second.get();
// }
debug_leave_func();
return replies.begin()->second.get();
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::get_by_time(const KT& key, const uint64_t& ts_us) const {
debug_enter_func_with_args("key={},ts_us={}",key,ts_us);
const HLC hlc(ts_us,0ull);
try {
debug_leave_func();
uint64_t idx = persistent_core.getIndexAtTime({ts_us,0});
if (idx == persistent::INVALID_INDEX) {
return *IV;
} else {
// Reconstructing the state is extremely slow!!!
// TODO: get the version at time ts_us, and go back from there.
auto versioned_state_ptr = persistent_core.get(hlc);
if (versioned_state_ptr->kv_map.find(key) != versioned_state_ptr->kv_map.end()) {
return versioned_state_ptr->kv_map.at(key);
}
return *IV;
}
} catch (const int64_t &ex) {
dbg_default_warn("temporal query throws exception:0x{:x}. key={}, ts={}", ex, key, ts_us);
} catch (...) {
dbg_default_warn("temporal query throws unknown exception. key={}, ts={}", key, ts_us);
}
debug_leave_func();
return *IV;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::get_size(const KT& key, const persistent::version_t& ver, bool exact) const {
debug_enter_func_with_args("key={},ver=0x{:x}",key,ver);
if (ver != CURRENT_VERSION) {
if (exact) {
return persistent_core.template getDelta<VT>(ver,[](const VT& value){return mutils::bytes_size(value);});
} else {
return mutils::bytes_size(persistent_core.get(ver)->kv_map.at(key));
}
}
derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get_size)>(key);
auto& replies = results.get();
// TODO: verify consistency ?
// for (auto& reply_pair : replies) {
// ret = reply_pair.second.get();
// }
debug_leave_func();
return replies.begin()->second.get();
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::get_size_by_time(const KT& key, const uint64_t& ts_us) const {
debug_enter_func_with_args("key={},ts_us={}",key,ts_us);
const HLC hlc(ts_us,0ull);
try {
debug_leave_func();
return mutils::bytes_size(persistent_core.get(hlc)->kv_map.at(key));
} catch (const int64_t &ex) {
dbg_default_warn("temporal query throws exception:0x{:x}. key={}, ts={}", ex, key, ts_us);
} catch (...) {
dbg_default_warn("temporal query throws unknown exception. key={}, ts={}", key, ts_us);
}
debug_leave_func();
return 0;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::list_keys(const persistent::version_t& ver) const {
debug_enter_func_with_args("ver=0x{:x}.",ver);
if (ver != CURRENT_VERSION) {
std::vector<KT> key_list;
auto kv_map = persistent_core.get(ver)->kv_map;
for (auto& kv:kv_map) {
key_list.push_back(kv.first);
}
debug_leave_func();
return key_list;
}
derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index);
auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_list_keys)>();
auto& replies = results.get();
// TODO: verify consistency ?
debug_leave_func();
return replies.begin()->second.get();
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::list_keys_by_time(const uint64_t& ts_us) const {
debug_enter_func_with_args("ts_us={}",ts_us);
const HLC hlc(ts_us,0ull);
try {
auto kv_map = persistent_core.get(hlc)->kv_map;
std::vector<KT> key_list;
for(auto& kv:kv_map) {
key_list.push_back(kv.first);
}
debug_leave_func();
return key_list;
} catch (const int64_t& ex) {
dbg_default_warn("temporal query throws exception:0x{:x]. ts={}", ex, ts_us);
} catch (...) {
dbg_default_warn("temporal query throws unknown exception. ts={}", ts_us);
}
debug_leave_func();
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_put(const VT& value) {
debug_enter_func_with_args("key={}",value.get_key_ref());
std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_next_version();
if constexpr (std::is_base_of<IKeepVersion,VT>::value) {
value.set_version(std::get<0>(version_and_timestamp));
}
if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) {
value.set_timestamp(std::get<1>(version_and_timestamp));
}
if (this->persistent_core->ordered_put(value,this->persistent_core.getLatestVersion()) == false) {
// verification failed. S we return invalid versions.
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return {persistent::INVALID_VERSION,0};
}
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
// group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id
this->subgroup_index,
group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_shard_num(),
value.get_key_ref(), value, cascade_context_ptr);
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return version_and_timestamp;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_remove(const KT& key) {
debug_enter_func_with_args("key={}",key);
std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_next_version();
auto value = create_null_object_cb<KT,VT,IK,IV>(key);
if constexpr (std::is_base_of<IKeepVersion,VT>::value) {
value.set_version(std::get<0>(version_and_timestamp));
}
if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) {
value.set_timestamp(std::get<1>(version_and_timestamp));
}
if(this->persistent_core->ordered_remove(value,this->persistent_core.getLatestVersion())) {
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
// group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id
this->subgroup_index,
group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_shard_num(),
key, value, cascade_context_ptr);
}
}
debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp));
return version_and_timestamp;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_get(const KT& key) {
debug_enter_func_with_args("key={}",key);
debug_leave_func();
return this->persistent_core->ordered_get(key);
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_get_size(const KT& key) {
debug_enter_func_with_args("key={}",key);
debug_leave_func();
return this->persistent_core->ordered_get_size(key);
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
void PersistentCascadeStore<KT,VT,IK,IV,ST>::trigger_put(const VT& value) const {
debug_enter_func_with_args("key={}",value.get_key_ref());
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
this->subgroup_index,
group->template get_subgroup<PersistentCascadeStore<KT,VT,IK,IV,ST>>(this->subgroup_index).get_shard_num(),
value.get_key_ref(), value, cascade_context_ptr, true);
}
debug_leave_func();
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_list_keys() {
debug_enter_func();
debug_leave_func();
return this->persistent_core->ordered_list_keys();
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
std::unique_ptr<PersistentCascadeStore<KT,VT,IK,IV,ST>> PersistentCascadeStore<KT,VT,IK,IV,ST>::from_bytes(mutils::DeserializationManager* dsm, char const* buf) {
auto persistent_core_ptr = mutils::from_bytes<persistent::Persistent<DeltaCascadeStoreCore<KT,VT,IK,IV>,ST>>(dsm,buf);
auto persistent_cascade_store_ptr =
std::make_unique<PersistentCascadeStore>(std::move(*persistent_core_ptr),
dsm->registered<CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>>()):nullptr,
dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr);
return persistent_cascade_store_ptr;
}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
PersistentCascadeStore<KT,VT,IK,IV,ST>::PersistentCascadeStore(
persistent::PersistentRegistry* pr,
CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
persistent_core(
[](){
return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>();
},
nullptr,
pr),
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
PersistentCascadeStore<KT,VT,IK,IV,ST>::PersistentCascadeStore(
persistent::Persistent<DeltaCascadeStoreCore<KT,VT,IK,IV>,ST>&&
_persistent_core,
CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
persistent_core(std::move(_persistent_core)),
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {}
template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST>
PersistentCascadeStore<KT,VT,IK,IV,ST>::~PersistentCascadeStore() {}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::put(const VT& value) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {persistent::INVALID_VERSION,0};
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::remove(const KT& key) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {persistent::INVALID_VERSION,0};
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT TriggerCascadeNoStore<KT,VT,IK,IV>::get(const KT& key, const persistent::version_t& ver, bool) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return *IV;
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT TriggerCascadeNoStore<KT,VT,IK,IV>::get_by_time(const KT& key, const uint64_t& ts_us) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return *IV;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::list_keys(const persistent::version_t& ver) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::list_keys_by_time(const uint64_t& ts_us) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::get_size(const KT& key, const persistent::version_t& ver, bool) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return 0;
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::get_size_by_time(const KT& key, const uint64_t& ts_us) const {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return 0;
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_list_keys() {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_put(const VT& value) {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_remove(const KT& key) {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return {};
}
template<typename KT, typename VT, KT* IK, VT* IV>
const VT TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_get(const KT& key) {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return *IV;
}
template<typename KT, typename VT, KT* IK, VT* IV>
uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_get_size(const KT& key) {
dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__);
return 0;
}
template<typename KT, typename VT, KT* IK, VT* IV>
void TriggerCascadeNoStore<KT,VT,IK,IV>::trigger_put(const VT& value) const {
debug_enter_func_with_args("key={}",value.get_key_ref());
if (cascade_watcher_ptr) {
(*cascade_watcher_ptr)(
this->subgroup_index,
group->template get_subgroup<TriggerCascadeNoStore<KT,VT,IK,IV>>(this->subgroup_index).get_shard_num(),
value.get_key_ref(), value, cascade_context_ptr, true);
}
debug_leave_func();
}
template<typename KT, typename VT, KT* IK, VT* IV>
std::unique_ptr<TriggerCascadeNoStore<KT,VT,IK,IV>> TriggerCascadeNoStore<KT,VT,IK,IV>::from_bytes(mutils::DeserializationManager* dsm, char const* buf) {
return std::make_unique<TriggerCascadeNoStore<KT,VT,IK,IV>>(
dsm->registered<CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>>()):nullptr,
dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr);
}
template<typename KT, typename VT, KT* IK, VT* IV>
mutils::context_ptr<TriggerCascadeNoStore<KT,VT,IK,IV>> TriggerCascadeNoStore<KT,VT,IK,IV>::from_bytes_noalloc(mutils::DeserializationManager* dsm, char const* buf) {
return mutils::context_ptr<TriggerCascadeNoStore>(from_bytes(dsm,buf));
}
template<typename KT, typename VT, KT* IK, VT* IV>
TriggerCascadeNoStore<KT,VT,IK,IV>::TriggerCascadeNoStore(CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>* cw,
ICascadeContext* cc):
cascade_watcher_ptr(cw),
cascade_context_ptr(cc) {}
}//namespace cascade
}//namespace derecho
| 43.564021
| 215
| 0.665225
|
Thompson-Liu
|
c49cffb82d3dd3f3c682c5b58a4d44a9bf7a4330
| 1,450
|
cpp
|
C++
|
codes/UVA/01001-01999/uva1327.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/UVA/01001-01999/uva1327.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
codes/UVA/01001-01999/uva1327.cpp
|
JeraKrs/ACM
|
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
const int maxn = 4005;
int N, pre[maxn], sccno[maxn], dfsclock, cntscc;
vector<int> G[maxn];
stack<int> S;
int dfs (int u) {
int lowu = pre[u] = ++dfsclock;
S.push(u);
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!pre[v]) {
int lowv = dfs(v);
lowu = min(lowu, lowv);
} else if (!sccno[v])
lowu = min(lowu, pre[v]);
}
if (lowu == pre[u]) {
cntscc++;
while (true) {
int x = S.top();
S.pop();
sccno[x] = cntscc;
if (x == u) break;
}
}
return lowu;
}
void findSCC () {
dfsclock = cntscc = 0;
memset(pre, 0, sizeof(pre));
memset(sccno, 0, sizeof(sccno));
for (int i = 1; i <= 2*N; i++)
if (!pre[i]) dfs(i);
}
int main () {
while (scanf("%d", &N) == 1) {
int t, x;
for (int i = 1; i <= N; i++) {
G[i].clear();
scanf("%d", &t);
while (t--) {
scanf("%d", &x);
G[i].push_back(x + N);
}
}
for (int i = 1; i <= N; i++) {
scanf("%d", &x);
G[x+N].clear();
G[x+N].push_back(i);
}
findSCC();
vector<int> ans;
for (int i = 1; i <= N; i++) {
ans.clear();
for (int j = 0; j < G[i].size(); j++) {
if (sccno[i] == sccno[G[i][j]]) ans.push_back(G[i][j]-N);
}
printf("%lu", ans.size());
sort(ans.begin(), ans.end());
for (int j = 0; j < ans.size(); j++)
printf(" %d", ans[j]);
printf("\n");
}
}
return 0;
}
| 17.682927
| 61
| 0.488966
|
JeraKrs
|
c49df0ee578b8acf93b362ebb177937ae76b8787
| 2,327
|
cpp
|
C++
|
Project6/proj6.cpp
|
nicky189/cs202
|
ecfb9b92e094bfa29102e586ffd615d719b45532
|
[
"MIT"
] | null | null | null |
Project6/proj6.cpp
|
nicky189/cs202
|
ecfb9b92e094bfa29102e586ffd615d719b45532
|
[
"MIT"
] | null | null | null |
Project6/proj6.cpp
|
nicky189/cs202
|
ecfb9b92e094bfa29102e586ffd615d719b45532
|
[
"MIT"
] | null | null | null |
/**
* @brief CS-202 Project 6 Test Driver
* @Author Christos Papachristos (cpapachristos@unr.edu)
* @date March, 2019
*
* This file is a test driver for the Polymorphic classes prescribed in Project 6 of CS-202
*/
#include <iostream>
#include "Car.h"
using namespace std;
int main(){
cout << "\n" <<
"////////////////////////////////\n" <<
"///// Constructor Tests /////\n" <<
"////////////////////////////////" << endl;
cout << endl << "Testing Derived Default ctor" << endl;
Car c1;
cout << endl << "Testing Derived Parametrized ctor" << endl;
float lla_rno[3] = {39.54, 119.82, 4500.0};
Car c_rno(lla_rno);
cout << endl << "Testing Derived Copy ctor" << endl;
Car c_cpy( c_rno );
cout << endl << "Testing Derived Assignment operator" << endl;
c1 = c_cpy;
cout << "\n" <<
"/////////////////////////////////\n" <<
"///// Polymorphism Tests /////\n" <<
"/////////////////////////////////" << endl;
cout << endl << "Testing VIRTUAL Move Function for DERIVED Class Objects" << endl;
float lla_new[3] = {37.77, 122.42, 52.0};
c1.Move( lla_new );
cout << endl << "Testing Insertion operator<< Overload for BASE Class Objects" << endl;
cout << c_rno << endl;
// Just setting some distinct values to our objects again here
float lla_ny[3] = {40.71, 74.00, 10.0};
c1.SetLLA( lla_ny );
float lla_la[3] = {34.05, 118.24, 71.01};
c_cpy.SetLLA( lla_la );
cout << "\n" <<
"///////////////////////////////////////////////////\n" <<
"///// Polymorphic Base Class Pointer Tests /////\n" <<
"///////////////////////////////////////////////////" << endl;
Vehicle* vehicles_array[3];
vehicles_array[0] = &c1;
vehicles_array[1] = &c_rno;
vehicles_array[2] = &c_cpy;
cout << endl << "Testing VIRTUAL Move Function on Base Class Pointers" << endl;
for (int i=0; i<3; ++i){
vehicles_array[i]->Move( lla_new );
}
cout << endl << "Testing Insertion operator<< Overload for Base Class Pointers" << endl;
for (int i=0; i<3; ++i){
cout << *vehicles_array[i] << endl;
}
cout << "\n" <<
"////////////////////////////\n" <<
"///// Tests Done /////\n" <<
"////////////////////////////" << endl;
return 0;
}
| 28.036145
| 91
| 0.486034
|
nicky189
|
c49ee7391c8c55d8f56a4d693d874ecd89a8aec6
| 140
|
hpp
|
C++
|
BOB/Source/Library/TableHeaders.hpp
|
Null-LLC/Echo
|
07165b71332fed8e4dd641bd0bdddb38534abdf0
|
[
"MIT"
] | 7
|
2021-08-15T01:35:56.000Z
|
2022-01-11T10:34:35.000Z
|
BOB/Source/Library/TableHeaders.hpp
|
Null-LLC/Echo
|
07165b71332fed8e4dd641bd0bdddb38534abdf0
|
[
"MIT"
] | 1
|
2021-11-06T07:20:31.000Z
|
2021-11-07T10:13:46.000Z
|
BOB/Source/Library/TableHeaders.hpp
|
Null-LLC/Echo
|
07165b71332fed8e4dd641bd0bdddb38534abdf0
|
[
"MIT"
] | 1
|
2021-12-07T07:04:47.000Z
|
2021-12-07T07:04:47.000Z
|
#ifndef TableHeaders
struct TableHeaders {
unsigned long long Signature;
unsigned int Revision, HeaderSize, CRC32, Reserved;
};
#endif
| 17.5
| 53
| 0.771429
|
Null-LLC
|
c4a02034615d3b94732c5150a6f1d534609ec0bb
| 637
|
cpp
|
C++
|
stlport/test/regression/list2.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 86
|
2018-05-24T12:03:44.000Z
|
2022-03-13T03:01:25.000Z
|
stlport/test/regression/list2.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 1
|
2019-05-30T01:38:40.000Z
|
2019-10-26T07:15:01.000Z
|
stlport/test/regression/list2.cpp
|
masscry/dmc
|
c7638f7c524a65bc2af0876c76621d8a11da42bb
|
[
"BSL-1.0"
] | 14
|
2018-07-16T08:29:12.000Z
|
2021-08-23T06:21:30.000Z
|
// STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <iostream>
#include <list>
#ifdef MAIN
#define list2_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int list2_test(int, char**)
{
cout<<"Results of list2_test:"<<endl;
int array1 [] = { 1, 16 };
int array2 [] = { 4, 9 };
list<int> l1(array1, array1 + 2);
list<int> l2(array2, array2 + 2);
std::list<int>::iterator i = l1.begin();
i++;
l1.splice(i, l2, l2.begin(), l2.end());
i = l1.begin();
while(i != l1.end())
cout << *i++ << endl;
return 0;
}
| 21.233333
| 57
| 0.631083
|
masscry
|
c4a046f30eec2de42139330bfb9e93a49a5bc728
| 3,102
|
hpp
|
C++
|
sources/include/nx/nx/callbacks.hpp
|
chybz/nx
|
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
|
[
"MIT"
] | 4
|
2016-11-07T09:50:03.000Z
|
2018-09-25T09:10:06.000Z
|
sources/include/nx/nx/callbacks.hpp
|
chybz/nx
|
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
|
[
"MIT"
] | null | null | null |
sources/include/nx/nx/callbacks.hpp
|
chybz/nx
|
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
|
[
"MIT"
] | 3
|
2016-11-07T09:50:05.000Z
|
2022-01-18T16:51:45.000Z
|
#ifndef __NX_CALLBACKS_H__
#define __NX_CALLBACKS_H__
#include <functional>
#include <tuple>
#include <type_traits>
#include <nx/tuple_utils.hpp>
#include <nx/utils.hpp>
namespace nx {
struct callback_tag {};
template <typename Tag, typename... Args>
class callback
{
public:
static_assert(
std::is_base_of<callback_tag, Tag>::value,
"invalid callback tag"
);
using this_type = callback<Tag, Args...>;
using tag_type = Tag;
using type = std::function<void(Args...)>;
operator bool() const
{ return (bool) cb_; }
operator type() const
{ return cb_; }
bool operator()(Args... args)
{
bool called = false;
if (cb_) {
cb_(std::forward<Args>(args)...);
called = true;
}
return called;
}
void reset()
{ cb_ = nullptr; }
this_type& operator=(const type& cb)
{
cb_ = cb;
return *this;
}
this_type& operator=(type&& cb)
{
cb_ = std::move(cb);
return *this;
}
private:
type cb_;
};
template <typename... Callbacks>
class callbacks
{
public:
using callbacks_type = std::tuple<Callbacks...>;
using tags_type = std::tuple<typename Callbacks::tag_type...>;
void clear()
{
nx::for_each(
cbs_,
[](std::size_t pos, auto& cb) {
cb.reset();
}
);
}
template <typename Tag>
auto&
get(const Tag& tag)
{ return get<Tag>(cbs_); }
template <typename Tag>
bool has(const Tag& tag) const
{ return (bool) get<Tag>(cbs_); }
template <typename Tag, typename... Args>
bool
call(Args&&... args)
{ return get<Tag>(cbs_)(std::forward<Args>(args)...); }
private:
template <typename Tag, typename Functions>
typename nx::tuple_element<
Tag,
Functions,
tags_type
>::type&
get(Functions& functions)
{
using function_type = typename nx::tuple_element<
Tag,
Functions,
tags_type
>::type;
return std::get<function_type>(functions);
}
template <typename Tag, typename Functions>
const typename nx::tuple_element<
Tag,
Functions,
tags_type
>::type&
get(const Functions& functions) const
{
using function_type = typename nx::tuple_element<
Tag,
Functions,
tags_type
>::type;
return std::get<function_type>(functions);
}
callbacks_type cbs_;
};
template <typename Tag, typename Callbacks>
struct callback_element
{
using callbacks_type = typename Callbacks::callbacks_type;
using tags_type = typename Callbacks::tags_type;
using type = typename nx::tuple_element<
Tag,
callbacks_type,
tags_type
>::type;
};
template <typename Tag, typename Class>
struct callback_signature
{
using type = typename callback_element<
Tag,
typename Class::callbacks
>::type::type;
};
} // namespace nx
#endif // __NX_CALLBACKS_H__
| 19.267081
| 66
| 0.579948
|
chybz
|
c4a809ff43a83ca6ff0cad8a8a181958f1e92633
| 3,332
|
hpp
|
C++
|
include/geographic_conversion/fix_converter_component.hpp
|
OUXT-Polaris/geographic_conversion
|
206ceef8bcec86534a88dd42aa47bd5b53f93665
|
[
"Apache-2.0"
] | null | null | null |
include/geographic_conversion/fix_converter_component.hpp
|
OUXT-Polaris/geographic_conversion
|
206ceef8bcec86534a88dd42aa47bd5b53f93665
|
[
"Apache-2.0"
] | 2
|
2019-05-26T23:38:02.000Z
|
2019-05-27T00:40:56.000Z
|
include/geographic_conversion/fix_converter_component.hpp
|
OUXT-Polaris/geographic_conversion
|
206ceef8bcec86534a88dd42aa47bd5b53f93665
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2019 OUXT Polaris
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_
#define GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_
// Headers in ROS
#include <geometry_msgs/msg/point_stamped.hpp>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/nav_sat_fix.hpp>
#include <geodesy/utm.h>
#include <ctype.h>
// Headers in STL
#include <string>
#include <limits>
#include <cmath>
#if __cplusplus
extern "C" {
#endif
// The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from
// demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __attribute__((dllexport))
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT __attribute__((dllimport))
#else
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __declspec(dllexport)
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT __declspec(dllimport)
#endif
#ifdef GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_BUILDING_DLL
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC \
GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT
#else
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC \
GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT
#endif
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC_TYPE \
GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL
#else
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __attribute__((visibility("default")))
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT
#if __GNUC__ >= 4
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC __attribute__((visibility("default")))
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL __attribute__((visibility("hidden")))
#else
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL
#endif
#define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC_TYPE
#endif
#if __cplusplus
} // extern "C"
#endif
namespace geographic_conversion
{
class FixConverterComponent : public rclcpp::Node
{
public:
GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC
explicit FixConverterComponent(const rclcpp::NodeOptions & options);
private:
std::string map_frame_;
std::string input_topic_;
rclcpp::Publisher<geometry_msgs::msg::PointStamped>::SharedPtr point_pub_;
rclcpp::Subscription<sensor_msgs::msg::NavSatFix>::SharedPtr fix_sub_;
void fixCallback(const sensor_msgs::msg::NavSatFix::SharedPtr msg);
};
} // namespace geographic_conversion
#endif // GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_
| 37.438202
| 99
| 0.836735
|
OUXT-Polaris
|
c4af4c8bb16f2782e83ac46ea60b8ad346c3e93c
| 2,427
|
cc
|
C++
|
nodes/PBX/main.cc
|
kgoba/roombreak
|
6936d7003d2541fd3fb44bda0a31bf66439f35dc
|
[
"MIT"
] | 1
|
2021-06-16T07:55:28.000Z
|
2021-06-16T07:55:28.000Z
|
nodes/PBX/main.cc
|
kgoba/roombreak
|
6936d7003d2541fd3fb44bda0a31bf66439f35dc
|
[
"MIT"
] | 3
|
2016-04-04T14:13:42.000Z
|
2016-04-04T15:07:24.000Z
|
nodes/PBX/main.cc
|
kgoba/roombreak
|
6936d7003d2541fd3fb44bda0a31bf66439f35dc
|
[
"MIT"
] | 1
|
2021-06-16T07:55:30.000Z
|
2021-06-16T07:55:30.000Z
|
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include "config.h"
#include <Common/config.h>
#include <Common/task.h>
#include <Common/ws2803s.h>
#include "line.h"
#include "user.h"
using namespace PBXConfig;
#define TICK_FREQ 1000
WS2803S<PIN_SDA, PIN_CLK> ioExpander;
AudioPlayer player1(ioExpander, XPIN_TRSEL0, XPIN_TRSEL1, XPIN_TRSEL2, XPIN_TRSEL3, XPIN_TRSEL4);
PLineConfig config1 = {
.apinSense = PIN_SENSE1, .pinRing = PIN_RING1,
.trackDial = TRACK_DIAL, .trackCall = TRACK_CALL, .trackBusy = TRACK_BUSY
};
PLine line1(player1, config1);
PLineConfig config2 = {
.apinSense = PIN_SENSE2, .pinRing = PIN_RING2,
.trackDial = TRACK_DIAL, .trackCall = TRACK_CALL, .trackBusy = TRACK_BUSY
};
PLine line2(player1, config2);
//PUser user1(line1);
//PUser user2(line2);
//VUser user3(NUMBER_FINISH);
Operator oper(line1, line2);
bool gSolved1;
bool gSolved2;
void taskComplete() {
//
gSolved1 = true;
gSolved2 = true;
}
void taskRestart() {
//
gSolved1 = false;
gSolved2 = false;
}
byte taskIsDone() {
return gSolved1 && gSolved2;
}
byte taskCallback(byte cmd, byte nParams, byte *nResults, byte *busParams)
{
switch (cmd) {
case CMD_DONE1: {
if (nParams > 0) {
gSolved1 = busParams[0];
}
*nResults = 1;
busParams[0] = gSolved1;
break;
}
case CMD_DONE2: {
if (nParams > 0) {
gSolved2 = busParams[0];
}
*nResults = 1;
busParams[0] = gSolved2;
break;
}
}
return 0;
}
void setup()
{
pinMode(PIN_TALK, OUTPUT);
ioExpander.setup();
player1.setup();
line1.setup();
line2.setup();
TIMER0_SETUP(TIMER0_FAST_PWM, TIMER0_PRESCALER(TICK_FREQ));
//TCCR0A = (1 << WGM01) | (1 << WGM00);
//TCCR0B = (1 << CS02) | (1 << CS00) | (1 << WGM02);
TIMSK0 = (1 << TOIE0);
//OCR0A = (byte)(F_CPU / (1024UL * TICK_FREQ)) - 1;
OCR0A = TIMER0_COUNTS(TICK_FREQ) - 1;
//ADCSRA = (1 << ADEN) | (1 << ADPS2); // prescaler 16
ADCSRA = bit_mask2(ADPS2, ADPS0);
bit_set(ADCSRA, ADEN);
adcReference();
taskSetup(BUS_ADDRESS);
taskRestart();
}
void loop()
{
static byte id = 0;
//_delay_ms(50);
if (oper.getLastDialled() == 4) gSolved1 = true;
if (oper.getLastDialled() == 5) gSolved2 = true;
taskLoop();
}
ISR(TIMER0_OVF_vect) {
oper.tick();
}
extern "C" void __cxa_pure_virtual() { while (1); }
| 19.731707
| 97
| 0.634528
|
kgoba
|
c4b34ef60f4cd615d409af1ee6e93208e9607e3b
| 41,346
|
cpp
|
C++
|
Tools/MakeDiscoLights/gk.cpp
|
AbePralle/FGB
|
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
|
[
"MIT"
] | null | null | null |
Tools/MakeDiscoLights/gk.cpp
|
AbePralle/FGB
|
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
|
[
"MIT"
] | null | null | null |
Tools/MakeDiscoLights/gk.cpp
|
AbePralle/FGB
|
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
|
[
"MIT"
] | null | null | null |
#include "gk.h"
#include <stdlib.h>
extern ofstream logFile;
gkTransparencyTable gkBitmap::tranTable;
struct BMP_header{
gkLONG fSize; //54 byte header + 4*numColors (1-8bit) + (w*h*bpp)/8
gkWORD zero1, zero2; //0,0
gkLONG offsetBytes; //should be header (54) plus Palette Size
gkLONG headerSize; //size of remaining header (40)
gkLONG width, height; //w,h in pixels
gkWORD planes, bpp; //plane=1, bpp=1,2,4, or most commonly 8
gkLONG compression, imageSize; //compression to zero, size is w*h(8bit)
gkLONG xpels, ypels, zero3, zero4; //set to 0,0,0,0
};
#ifdef _WIN32
gkFileInputBuffer::gkFileInputBuffer(char *filename){
buffer = 0;
stin = 0;
exists = 0;
HANDLE handle = CreateFile(filename,GENERIC_READ,FILE_SHARE_READ,0,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(handle==INVALID_HANDLE_VALUE) return;
int size = GetFileSize(handle,0);
buffer = new char[size];
unsigned long bytesRead;
ReadFile(handle,buffer,size,&bytesRead,0);
CloseHandle(handle);
stin = new istrstream(buffer,size);
exists = 1;
}
gkFileInputBuffer::~gkFileInputBuffer(){
if(stin){
delete stin;
stin = 0;
}
if(buffer) delete buffer;
buffer = 0;
}
gkFileOutputBuffer::gkFileOutputBuffer(char *filename){
exists = 0;
handle = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,0,
CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
if(handle==INVALID_HANDLE_VALUE){
return;
}
exists = 1;
}
gkFileOutputBuffer::~gkFileOutputBuffer(){
if(handle==INVALID_HANDLE_VALUE) return;
unsigned long written;
WriteFile(handle,stout.str(),stout.tellp(),&written,0);
//unfreeze the ostrstream so it will delete the array
stout.rdbuf()->freeze(0);
CloseHandle(handle);
}
#endif
gkList::gkList(void){
head = tail = 0;
numItems = 0;
}
gkList::~gkList(void){
Reset();
}
void gkList::Reset(){
gkListItem *cur, *next;
for(cur=head; cur; cur=next){
next = cur->NextItem();
delete cur;
}
head = tail = 0;
}
gkListItem *gkList::GetItem(int n){
if(n >= numItems) return 0;
gkListItem *cur;
cur = head;
while(n-- > 0){
cur = cur->NextItem();
}
return cur;
}
void gkList::AddItem(gkListItem *li){
numItems++;
if(!head){
head = tail = li;
}else{
tail->SetNextItem(li);
tail = tail->NextItem();
li->SetNextItem(0);
}
}
void gkList::DeleteItem(gkListItem *item){
gkListItem *cur, *prev;
//is it the head?
if(item==head){
head=head->GetNext();
if(!head) tail = 0;
delete item;
return;
}
//must be in body or tail
prev = 0;
for(cur=head; cur; cur=cur->GetNext()){
if(cur==item){
prev->SetNext(cur->GetNext());
if(cur==tail) tail=prev;
delete cur;
break;
}
prev = cur;
}
}
int gkIO::ReadWord(istream &in){
int retval = in.get() << 8;
return retval | (in.get() & 0xff);
}
int gkIO::ReadLong(istream &in){
int retval = ReadWord(in) << 16;
return retval | (ReadWord(in) & 0xffff);
}
char *gkIO::ReadString(istream &in){
static char st[80];
int len = ReadWord(in);
if(!len) return 0;
in.read(st,len);
st[len] = 0;
return st;
}
char *gkIO::ReadNewString(istream &in){
int len = ReadWord(in);
if(!len) return 0;
char *st = new char[len+1];
in.read(st,len);
st[len] = 0;
return st;
}
void gkIO::WriteLong(ostream &out, int n){
WriteWord(out, n>>16);
WriteWord(out, n);
}
void gkIO::WriteWord(ostream &out, int n){
out << (char) ((n>>8)&0xff);
out << (char) (n&0xff);
}
void gkIO::WriteString(ostream &out, char *st){
WriteWord(out,strlen(st));
out.write(st,strlen(st));
}
int gkRGB::Equals(int _r, int _g, int _b){
return _r==color.bytes.r && _g==color.bytes.g && _b==color.bytes.b;
}
void gkRGB::Combine(gkRGB c2, int alpha){
//mix alpha
color.bytes.r +=
gkBitmap::tranTable.LookupTransparencyOffset(c2.GetR()-GetR(), alpha);
color.bytes.g +=
gkBitmap::tranTable.LookupTransparencyOffset(c2.GetG()-GetG(), alpha);
color.bytes.b +=
gkBitmap::tranTable.LookupTransparencyOffset(c2.GetB()-GetB(), alpha);
}
void gkRGB::SetFromGBColor(int gbColor){
color.bytes.r = (gbColor<<3) & 0xf8;
color.bytes.g = (gbColor>>2) & 0xf8;
color.bytes.b = (gbColor>>7) & 0xf8;
}
gkPalGenItem::gkPalGenItem(gkRGB _color){
color = _color;
occurrences = 1;
nextItem = 0;
}
gkPalGenItem::~gkPalGenItem(){
}
gkRGB gkPalGenItem::GetColor(){
return color;
}
void gkPalGenItem::AddOccurrence(){
occurrences++;
}
int gkPalGenItem::GetOccurrences(){
return occurrences;
}
void gkPalGenItem::SetOccurrences(int n){
occurrences = n;
}
void gkPalGenItem::SetNextItem(gkPalGenItem *item){
nextItem = item;
}
gkPalGenItem *gkPalGenItem::GetNextItem(){
return nextItem;
}
int gkPalGenItem::GetCount(){
gkPalGenItem *cur;
int count = 0;
for(cur=this; cur; cur=cur->nextItem){
if(cur->occurrences) count++;
}
return count;
}
int gkPalGenItem::SortCallback(const void *e1, const void *e2){
gkPalGenItem *i1 = *((gkPalGenItem**) e1);
gkPalGenItem *i2 = *((gkPalGenItem**) e2);
if(i1->occurrences > i2->occurrences) return -1;
if(i1->occurrences == i2->occurrences) return 0;
return 1;
}
gkPaletteGenerator::gkPaletteGenerator(){
int i;
for(i=0; i<52; i++){
colorCube[i] = 0;
}
}
gkPaletteGenerator::~gkPaletteGenerator(){
Reset();
}
void gkPaletteGenerator::Reset(){
int i;
for(i=0; i<52; i++){
if(colorCube[i]){
gkPalGenItem *cur, *next;
for(cur=colorCube[i]; cur; cur=next){
next = cur->GetNextItem();
delete cur;
}
colorCube[i] = 0;
}
}
}
void gkPaletteGenerator::AddColor(gkRGB color){
int i = GetHash(color);
if(!colorCube[i]){
colorCube[i] = new gkPalGenItem(color);
}else{
gkPalGenItem *cur, *prev;
for(cur=colorCube[i]; cur; cur=cur->GetNextItem()){
if((cur->GetColor()) == color){
cur->AddOccurrence(); //Color already in list
break;
}
prev = cur;
}
if(!cur){ //color not in list
prev->SetNextItem(new gkPalGenItem(color));
}
}
}
void gkPaletteGenerator::CreatePalette(gkRGB *palette, int numEntries){
if(numEntries<=0) return;
//Set all entries to black
int i;
for(i=0; i<numEntries; i++) palette[i] = gkRGB(0,0,0);
//1 entry from every this many indices
double scaleFactor = 52.0 / numEntries;
int curEntry = 0;
while(curEntry < numEntries){
//Get first & last array indices for this section
int first = (int) (scaleFactor * (curEntry));
int nextEntry = (int) (scaleFactor * (curEntry+1));
int last = nextEntry - 1;
if(last < first) last = first;
//Count total # of colors in this section
int count = 0;
for(i=first; i<=last; i++){
if(colorCube[i]) count += colorCube[i]->GetCount();
}
while(!count){ //if no colors yet expand area of inclusion
if(first==0 && last==51) return; //no colors anywhere!
if(first>0){
first--;
if(colorCube[first]) count += colorCube[first]->GetCount();
}
if(last<51){
last++;
if(colorCube[last]) count += colorCube[last]->GetCount();
}
}
//Create an array to hold all the colors for sorting purposes
gkPalGenItem **colors = new gkPalGenItem*[count];
gkPalGenItem *cur;
i = 0;
int j;
for(j=first; j<=last; j++){
if(colorCube[j]){
for(cur=colorCube[j]; cur; cur=cur->GetNextItem()){
if(cur->GetOccurrences()) colors[i++] = cur;
}
}
}
//figure out how many colors will come from this section of the cube
int numToGrab = 1;
int tempCurEntry = curEntry;
while(nextEntry==first && tempCurEntry<(52-1)){
tempCurEntry++;
nextEntry = (int) (scaleFactor * (tempCurEntry+1));
numToGrab++;
}
if(numToGrab > count) numToGrab = count;
//sort colors into descending order and pick "num" most frequent
qsort(colors, count, sizeof(gkPalGenItem*), gkPalGenItem::SortCallback);
for(i=0; i<numToGrab; i++){
palette[curEntry++] = colors[i]->GetColor();
colors[i]->SetOccurrences(0);
}
//delete sorting table
delete colors;
}
}
int gkPaletteGenerator::GetNumColors(){
int num = 0, i;
for(i=0; i<52; i++)
if(colorCube[i]) num += colorCube[i]->GetCount();
return num;
}
int gkPaletteGenerator::GetHash(gkRGB color){
int r = color.GetR() >> 6; //rough categories 0-3
int g = color.GetG() >> 6;
int b = color.GetB() >> 6;
int highest = r;
if(g > highest) highest = g;
if(b > highest) highest = b;
int hash;
// r > (g < b)
// r > (g = b)
// r > (g > b)
// g > (r < b)
// g > (r = b)
// g > (r > b)
// b > (r < g)
// b > (r = g)
// b > (r > g)
// (r = b) > g
// (r = g) > b
// (g = b) > r
// (r = g) = b
if(r > g && r > b){ //red high
if(g < b) hash = 0; // r > (g < b)
else if(g==b) hash = 1; // r > (g = b)
else hash = 2; // r > (g > b)
}else if(g > r && g > b){ //green high
if(r < b) hash = 3; // g > (r < b)
else if(r==b) hash = 4; // g > (r = b)
else hash = 5; // g > (r > b)
}else if(b > r && b > g){ //blue high
if(r < g) hash = 6; // b > (r < g)
else if(r==g) hash = 7; // b > (r = g)
else hash = 8; // b > (r > g)
}else if(r==b && b==g){ //r = g = b
hash = 9;
}else if(r==b){ //(r = b) > g
hash = 10;
}else if(r==g){ //(r = g) > b
hash = 11;
}else{ //(g = b) > r
hash = 12;
}
//make room in each category for four levels of intensity (0-3)
hash = hash*4 + highest;
return hash;
}
int gkPaletteGenerator::ColorExists(gkRGB color){
int hash = GetHash(color);
if(!colorCube[hash]) return 0;
gkPalGenItem *cur;
for(cur=colorCube[hash]; cur; cur=cur->GetNextItem()){
if(cur->GetColor()==color) return 1; //found exact color
}
return 0;
}
gkRGB gkPaletteGenerator::MatchColor(gkRGB color){
int hash = GetHash(color);
int r = color.GetR();
int g = color.GetG();
int b = color.GetB();
if(colorCube[hash]){ //near colors; search just this section
gkPalGenItem *cur, *bestMatch;
int bestDiff;
bestMatch = colorCube[hash];
int r2, g2, b2;
r2 = abs(r - bestMatch->GetColor().GetR());
g2 = abs(g - bestMatch->GetColor().GetG());
b2 = abs(b - bestMatch->GetColor().GetB());
bestDiff = r2 + g2 + b2;
for(cur=bestMatch->GetNextItem(); cur; cur=cur->GetNextItem()){
r2 = abs(r - cur->GetColor().GetR());
g2 = abs(g - cur->GetColor().GetG());
b2 = abs(b - cur->GetColor().GetB());
int curDiff = r2 + g2 + b2;
if(curDiff < bestDiff){
bestDiff = curDiff;
bestMatch = cur;
if(!curDiff) return bestMatch->GetColor();
}
}
return bestMatch->GetColor();
}else{
//no colors nearby; expand search
//Get it from ~greyscale if possible
int first, last;
first = last = 36 + (hash % 4);
if(!colorCube[first]){
first = 0; //nothing there either; search everything
last = 51;
/*
first = 36;
last = 39;
//first = hash - (hash%4); //different intensities, same color
//last = first + 3;
if(!colorCube[first] && !colorCube[first+1] && !colorCube[first+2]
&& !colorCube[last]){
first = 0; //nothing there either; search everything
last = 51;
}
*/
}
gkPalGenItem *cur, *bestMatch;
int bestDiff = 0x7fffffff;
bestMatch = 0;
int i;
for(i=first; i<=last; i++){
for(cur=colorCube[i]; cur; cur=cur->GetNextItem()){
int r2 = abs(r - cur->GetColor().GetR());
int g2 = abs(g - cur->GetColor().GetG());
int b2 = abs(b - cur->GetColor().GetB());
int curDiff = r2 + g2 + b2;
if(curDiff < bestDiff){
bestDiff = curDiff;
bestMatch = cur;
if(!curDiff) return bestMatch->GetColor();
}
}
}
if(!bestMatch) return gkRGB(0,0,0);
return bestMatch->GetColor();
}
}
gkTransparencyTable::gkTransparencyTable(){
lookup = new gkBYTE[256*256];
int baseOffset, alpha, i;
i = 0;
for(baseOffset=0; baseOffset<256; baseOffset++){
for(alpha=0; alpha<256; alpha++){
lookup[i++] = (baseOffset * alpha) / 255;
}
}
}
gkTransparencyTable::~gkTransparencyTable(){
if(lookup) delete lookup;
lookup = 0;
}
int gkTransparencyTable::LookupTransparencyOffset(int baseOffset, int alpha){
return (baseOffset>=0) ? lookup[(baseOffset<<8)+alpha]
: (-lookup[((-baseOffset)<<8)+alpha]);
}
gkBitmap::gkBitmap(){
data = 0;
width = height = bpp = 0;
}
gkBitmap::~gkBitmap(){
FreeData();
}
void gkBitmap::FreeData(){
if(data){
delete data;
data = 0;
}
width = height = 0;
}
void gkBitmap::Create(int _width, int _height){
if(_width <= 0 || _height <= 0) return;
FreeData();
width = _width;
height = _height;
//round up width to ensure multiple of 4 pixels
width = (width + 3) & (~3);
int size = (width*height)<<2;
data = new gkBYTE[size];
//data = new gkBYTE[(width*height)<<2];
bpp = 32;
}
void gkBitmap::Cls(){
if(!this->data) return;
gkLONG *dest = (gkLONG*) this->data;
int i = this->width * this->height;
while(i--){
*(dest++) = 0xff000000;
}
}
void gkBitmap::Cls(gkRGB color){
if(!this->data) return;
gkLONG *dest = (gkLONG*) this->data;
int i = this->width * this->height;
while(i--){
*(dest++) = color.GetARGB();
}
}
void gkBitmap::Plot(int x, int y, gkRGB color, int testBoundaries){
if(!data) return;
if(testBoundaries){
if(x<0 || x>=width || y<0 || y>=height) return;
}
gkRGB *dest = (gkRGB*) (data + ((y*width + x) << 2));
*dest = color;
}
gkRGB gkBitmap::Point(int x, int y, int testBoundaries){
if(!data) return gkRGB(0,0,0);
if(testBoundaries){
if(x<0 || x>=width || y<0 || y>=height) return gkRGB(0,0,0);
}
gkRGB *color = (gkRGB*) (data + ((y*width + x) << 2));
return *color;
}
void gkBitmap::Line(int x1, int y1, int x2, int y2, gkRGB color){
int temp;
if(y1==y2){ //straight horizontal line
if(x2 < x1) RectFill(x2,y1,(x1-x2)+1,1,color);
else RectFill(x1,y1,(x2-x1)+1,1,color);
return;
}else if(x1==x2){ //straight vertical line
if(y2 < y1) RectFill(x1,y2,1,(y1-y2)+1,color);
else RectFill(x1,y1,1,(y2-y1)+1,color);
return;
}
//clip line to screen
if(y2 < y1){ //orient line to be drawn from top to
temp = x1; x1 = x2; x2 = temp; //bottom for initial clipping tests
temp = y1; y1 = y2; y2 = temp;
}
if(y2 < 0 || y1 >= height) return;
double xdiff = x2-x1, ydiff = y2-y1;
double slopexy = xdiff / ydiff;
int diff;
//perform vertical clipping
diff = 0 - y1;
if(diff > 0){ //y1 is above top boundary
x1 += (int) (slopexy * diff);
y1 = 0;
}
diff = (y2 - height) + 1;
if(diff > 0){ //y2 is below bottom boundary
x2 -= (int) (slopexy * diff);
y2 = height - 1;
}
//reorient line to be drawn from left to right for horizontal clipping tests
if(x2 < x1){
temp = x1; x1 = x2; x2 = temp;
temp = y1; y1 = y2; y2 = temp;
xdiff = x2-x1;
ydiff = y2-y1;
}
double slopeyx = ydiff / xdiff;
if(x2 < 0 || x1 >= width) return;
diff = 0 - x1;
if(diff > 0){ //x1 is to left of left boundary
y1 += (int) (slopeyx * diff);
x1 = 0;
}
diff = (x2 - width) + 1;
if(diff > 0){ //x2 is to right of right boundary
y2 -= (int) (slopeyx * diff);
x2 = width - 1;
}
//draw the line using Bresenham's
//coordinates are now such that x increment is always positive
int xdist = x2-x1;
int ydist = y2-y1;
int pitch = width;
gkRGB *dest = (gkRGB*) (data + (((y1 * width) + x1) <<2));
if(ydist < 0){
ydist = -ydist;
pitch = -pitch;
}
int err, i;
if(xdist >= ydist){ //loop on x, change y every so often
err = 0;
for(i=xdist; i>=0; i--){
*(dest++) = color;
err += ydist;
if(err >= xdist){
err -= xdist;
dest += pitch;
}
}
}else{ //loop on y, change x every so often
err = 0;
for(i=ydist; i>=0; i--){
*dest = color;
dest += pitch;
err += xdist;
if(err >= ydist){
err -= ydist;
dest++;
}
}
}
}
void gkBitmap::LineAlpha(int x1, int y1, int x2, int y2, gkRGB color,
int alpha){
int temp;
if(y1==y2){ //straight horizontal line
if(x2 < x1) RectFill(x2,y1,(x1-x2)+1,1,color);
else RectFill(x1,y1,(x2-x1)+1,1,color);
return;
}else if(x1==x2){ //straight vertical line
if(y2 < y1) RectFill(x1,y2,1,(y1-y2)+1,color);
else RectFill(x1,y1,1,(y2-y1)+1,color);
return;
}
//clip line to screen
if(y2 < y1){ //orient line to be drawn from top to
temp = x1; x1 = x2; x2 = temp; //bottom for initial clipping tests
temp = y1; y1 = y2; y2 = temp;
}
if(y2 < 0 || y1 >= height) return;
double xdiff = x2-x1, ydiff = y2-y1;
double slopexy = xdiff / ydiff;
int diff;
//perform vertical clipping
diff = 0 - y1;
if(diff > 0){ //y1 is above top boundary
x1 += (int) (slopexy * diff);
y1 = 0;
}
diff = (y2 - height) + 1;
if(diff > 0){ //y2 is below bottom boundary
x2 -= (int) (slopexy * diff);
y2 = height - 1;
}
//reorient line to be drawn from left to right for horizontal clipping tests
if(x2 < x1){
temp = x1; x1 = x2; x2 = temp;
temp = y1; y1 = y2; y2 = temp;
xdiff = x2-x1;
ydiff = y2-y1;
}
double slopeyx = ydiff / xdiff;
if(x2 < 0 || x1 >= width) return;
diff = 0 - x1;
if(diff > 0){ //x1 is to left of left boundary
y1 += (int) (slopeyx * diff);
x1 = 0;
}
diff = (x2 - width) + 1;
if(diff > 0){ //x2 is to right of right boundary
y2 -= (int) (slopeyx * diff);
x2 = width - 1;
}
//draw the line using Bresenham's
//coordinates are now such that x increment is always positive
int xdist = x2-x1;
int ydist = y2-y1;
int pitch = width;
gkRGB *dest = (gkRGB*) (data + (((y1 * width) + x1) <<2));
if(ydist < 0){
ydist = -ydist;
pitch = -pitch;
}
int err, i;
if(xdist >= ydist){ //loop on x, change y every so often
err = 0;
for(i=xdist; i>=0; i--){
dest->Combine(color,alpha);
dest++;
err += ydist;
if(err >= xdist){
err -= xdist;
dest += pitch;
}
}
}else{ //loop on y, change x every so often
err = 0;
for(i=ydist; i>=0; i--){
dest->Combine(color,alpha);
dest += pitch;
err += xdist;
if(err >= ydist){
err -= ydist;
dest++;
}
}
}
}
void gkBitmap::RectFrame(int x, int y, int w, int h, gkRGB color){
int x2 = x + w - 1;
int y2 = y + h - 1;
RectFill(x,y,w,1,color);
RectFill(x,y2,w,1,color);
RectFill(x,y,1,h,color);
RectFill(x2,y,1,h,color);
}
void gkBitmap::RectFill(int x, int y, int w, int h, gkRGB color){
int x2 = (x + w) - 1;
int y2 = (y + h) - 1;
//Clip rectangle
if(x < 0) x = 0;
if(y < 0) y = 0;
if(x2 >= width) x2 = width - 1;
if(y2 >= height) y2 = height - 1;
if(x2 < x || y2 < y) return;
//Set pointers and offsets
gkRGB *destStart = (gkRGB*) (data + (((y * width) + x) <<2));
gkRGB *dest;
int numRows = (y2 - y) + 1;
int rowWidth = (x2 - x) + 1;
//do it
while(numRows--){
dest = destStart;
int i;
for(i=0; i<rowWidth; i++){
*(dest++) = color;
}
destStart += width;
}
}
void gkBitmap::RectFillAlpha(int x, int y, int w, int h, gkRGB color,
int alpha){
int x2 = (x + w) - 1;
int y2 = (y + h) - 1;
//Clip rectangle
if(x < 0) x = 0;
if(y < 0) y = 0;
if(x2 >= width) x2 = width - 1;
if(y2 >= height) y2 = height - 1;
if(x2 < x || y2 < y) return;
//Set pointers and offsets
gkRGB *destStart = (gkRGB*) (data + (((y * width) + x) <<2));
gkRGB *dest;
int numRows = (y2 - y) + 1;
int rowWidth = (x2 - x) + 1;
//do it
while(numRows--){
dest = destStart;
int i;
for(i=0; i<rowWidth; i++){
dest->Combine(color,alpha);
dest++;
}
destStart += width;
}
}
void gkBitmap::RectFillChannel(int x, int y, int w, int h,
gkRGB color, int mask){
int x2 = (x + w) - 1;
int y2 = (y + h) - 1;
//Clip rectangle
if(x < 0) x = 0;
if(y < 0) y = 0;
if(x2 >= width) x2 = width - 1;
if(y2 >= height) y2 = height - 1;
if(x2 < x || y2 < y) return;
//Set pointers and offsets
gkLONG *destStart = (gkLONG*) (data + (((y * width) + x) <<2));
gkLONG *dest;
int numRows = (y2 - y) + 1;
int rowWidth = (x2 - x) + 1;
gkLONG srcColor = color.GetARGB() & mask;
gkLONG destMask = ~mask;
//do it
while(numRows--){
dest = destStart;
int i;
for(i=0; i<rowWidth; i++){
*dest = (*dest & destMask) | (srcColor);
dest++;
}
destStart += width;
}
}
struct gkFillItem{
short int x, y;
gkRGB *pos;
inline gkFillItem(){}
inline gkFillItem(int _x, int _y, gkRGB *_pos){
x = _x;
y = _y;
pos = _pos;
}
};
void gkBitmap::FloodFill(int x, int y, gkRGB color){
gkFillItem queue[16384];
int qHead=0, qTail=0;
//not the color we're filling WITH, the color we're filling ON
gkRGB fillColor = Point(x,y);
if(color==fillColor) return;
//enqueue the starting location
queue[qTail++] = gkFillItem(x,y,(gkRGB *)(data + ((y*width + x) * 4)));
//keep looping, filling current location & adding adjacent locations
//until queue is empty
while(qHead != qTail){
//dequeue an item
gkFillItem cur = queue[qHead++];
qHead &= 16383;
//out of bounds check
if(cur.x<0 || cur.y<0 || cur.x>=width || cur.y>=height) continue;
//filling correct color check
if(!(*(cur.pos)==fillColor)) continue;
//fill color & add adjacent
*(cur.pos) = color;
queue[qTail++] = gkFillItem(cur.x+1,cur.y,cur.pos+1);
qTail &= 16383;
queue[qTail++] = gkFillItem(cur.x-1,cur.y,cur.pos-1);
qTail &= 16383;
queue[qTail++] = gkFillItem(cur.x,cur.y+1,cur.pos+width);
qTail &= 16383;
queue[qTail++] = gkFillItem(cur.x,cur.y-1,cur.pos-width);
qTail &= 16383;
}
}
int gkBitmap::GetNumColors(){
gkPaletteGenerator palGen;
int i = width * height;
gkRGB *src = (gkRGB*) data;
while(i--){
palGen.AddColor(*(src++));
}
return palGen.GetNumColors();
}
void gkBitmap::RemapColor(gkRGB oldColor, gkRGB newColor){
if(!data) return;
gkRGB *src = (gkRGB*) data;
int i, j;
for(j=0; j<height; j++){
for(i=0; i<width; i++){
if(oldColor == (*src)){
*src = newColor;
}
src++;
}
}
}
int gkBitmap::GetPalette(gkRGB *palette, int maxColors){
gkPaletteGenerator palGen;
int i = width * height;
gkRGB *src = (gkRGB*) data;
while(i--){
palGen.AddColor(*(src++));
}
int num = palGen.GetNumColors();
palGen.CreatePalette(palette, maxColors);
return num;
}
void gkBitmap::RemapToPalette(gkRGB *palette, int numColors){
//add palette colors to generator for matching purposes
gkPaletteGenerator generator;
int i = numColors;
gkRGB *src = palette;
while(i--){
generator.AddColor(*(src++));
}
//find color in palette that best matches each pixel
i = width * height;
src = (gkRGB*) data;
while(i--){
*src = generator.MatchColor(*src);
src++;
}
}
void gkBitmap::ReduceColors(int numColors){
gkPaletteGenerator generator;
int i = width * height;
gkRGB *src = (gkRGB*) data;
while(i--){
generator.AddColor(*(src++));
}
//gkRGB palette[256];
gkRGB *palette = new gkRGB[numColors];
generator.CreatePalette(palette, numColors);
RemapToPalette(palette, numColors);
delete palette;
}
void gkBitmap::ExchangeColors(gkRGB c1, gkRGB c2){
if(!data) return;
gkRGB *src = (gkRGB*) data;
int i, j;
for(j=0; j<height; j++){
for(i=0; i<width; i++){
if(c1 == (*src)){
*src = c2;
}else if(c2 == (*src)){
*src = c1;
}
src++;
}
}
}
void gkBitmap::SetAlpha(int alpha){
if(!data) return;
gkRGB *src = (gkRGB*) data;
int i = (width * height);
while(i--){
(src++)->SetA(alpha);
}
}
void gkBitmap::SetColorAlpha(gkRGB color, int alpha){
if(!data) return;
gkRGB *src = (gkRGB*) data;
int i, j;
for(j=0; j<height; j++){
for(i=0; i<width; i++){
if(color == (*src)){
src->SetA(alpha);
}
src++;
}
}
}
void gkBitmap::SetAlphaEdges(float opacity, int iterations){
{ //body in block to prevent recursive memory waste
gkBitmap work;
work.GetBitmap(this);
gkRGB *src = (gkRGB*) work.data;
gkRGB *dest = (gkRGB*) data;
gkRGB alpha;
int i, j;
for(j=0; j<height; j++){
for(i=0; i<width; i++){
if(src->GetA()==255){
int alpha = 0;
int samples = 0;
if(i>0 && j>0){
alpha += work.Point(i-1,j-1).GetA();
samples++;
}
if(i>0 && j<height-1){
alpha += work.Point(i-1,j+1).GetA();
samples++;
}
if(i<width-1 && j>0){
alpha += work.Point(i+1,j-1).GetA();
samples++;
}
if(i<width-1 && j<height-1){
alpha += work.Point(i+1,j+1).GetA();
samples++;
}
if(samples==0) samples=1; //would only happen on 1x1
alpha /= samples;
alpha = (int) (alpha * opacity);
dest->SetA(alpha);
}
dest++;
src++;
}
}
}
if(iterations>0) SetAlphaEdges(opacity, iterations-1);
}
void gkBitmap::MirrorH(){
gkRGB *buffer = new gkRGB[width];
if(!buffer) return;
gkRGB *cur = (gkRGB*) data;
int i,j,i2;
for(j=0; j<height; j++){
for(i=0,i2=width-1; i<width; i++,i2--){
buffer[i2] = cur[i];
}
for(i=0; i<width; i++){
cur[i] = buffer[i];
}
cur += width;
}
delete buffer;
}
int gkBitmap::GetBitmap(gkBitmap *srcBitmap, int x, int y, int w, int h){
if(!srcBitmap || !srcBitmap->data) return 0;
//adjust src rectangle until it fits within source data
if(x<0){
w += x;
x = 0;
}
if(y<0){
h += y;
y = 0;
}
if(x + w > srcBitmap->width){
w = srcBitmap->width - x;
}
if(y + h > srcBitmap->height){
h = srcBitmap->height - y;
}
if(w<=0 || h<=0) return 0;
FreeData();
Create(w, h);
gkBYTE *src = srcBitmap->data + ((y*srcBitmap->width + x)<<2);
gkBYTE *dest = this->data;
int srcSkip = srcBitmap->width << 2; //4 bytes per pixel
w <<= 2; //4 bytes per pixel
while(h--){
memcpy(dest, src, w);
dest += w;
src += srcSkip;
}
return 1;
}
int gkBitmap::GetBitmap(gkBitmap *srcBitmap){
if(this->width != srcBitmap->width || this->height != srcBitmap->height
|| (!this->data) || (!srcBitmap->data)){
//mem needs to be reallocated
FreeData();
memcpy(this, srcBitmap, sizeof(gkBitmap));
data = 0;
if(srcBitmap->data){
data = new gkBYTE[(width * height) << 2];
memcpy(data, srcBitmap->data, (width * height) << 2 );
}
}else{
//already got right size mem, just copy data over
memcpy(data, srcBitmap->data, (width * height) << 2);
fontSpacing = srcBitmap->fontSpacing;
fontKerning = srcBitmap->fontKerning;
x_handle = srcBitmap->x_handle;
y_handle = srcBitmap->y_handle;
}
return data!=0;
}
int gkBitmap::SaveBitmap(char *filename){
ofstream outfile;
outfile.open(filename, ios::out | ios::binary);
if(!outfile) return 0;
int result = SaveBitmap(outfile);
outfile.close();
return result;
}
int gkBitmap::SaveBitmap(ostream &out){
int totalSize = ((width * height) << 2);
out << "SHPE";
int skipSize = totalSize + 20;
gkIO::WriteLong(out, skipSize);
//Write shape header
gkIO::WriteWord(out, 3); //type 3
gkIO::WriteWord(out, width);
gkIO::WriteWord(out, height);
gkIO::WriteWord(out, (bpp==8)?8:32);
out << (char) fontSpacing << (char) fontKerning;
gkIO::WriteWord(out, x_handle);
gkIO::WriteWord(out, y_handle);
gkIO::WriteWord(out, 0); //6 bytes of reserved space
gkIO::WriteLong(out, 0);
//Write data
if(data){
int pitch = width << 2;
gkLONG *src;
gkBYTE *srcStart = data;
int i,j;
for(j=0; j<height; j++){
src = (gkLONG*) srcStart;
for(i=0; i<width; i++){
gkIO::WriteLong(out, *(src++));
}
srcStart += pitch;
}
}
return 1;
}
int gkBitmap::LoadBitmap(char *filename){
ifstream infile(filename,ios::in|ios::binary|ios::nocreate);
if(!infile) return 0;
//gkFileInputBuffer gkInfile(filename);
//if(!gkInfile.Exists()) return 0;
//istream &infile = *gkInfile.GetIStream();
int result = this->LoadBitmap(infile);
infile.close();
return result;
}
int gkBitmap::LoadBitmap(istream &infile){
FreeData();
if(infile.get() != 'S') return 0;
if(infile.get() != 'H') return 0;
if(infile.get() != 'P') return 0;
if(infile.get() != 'E') return 0;
gkIO::ReadLong(infile); //discard skipsize
//Read shape header
if(gkIO::ReadWord(infile) != 2) return 0;
width = gkIO::ReadWord(infile);
height = gkIO::ReadWord(infile);
int filebpp = gkIO::ReadWord(infile);
if(!bpp) bpp = filebpp;
if(width && height){
Create(width,height);
}
fontSpacing = infile.get();
fontKerning = infile.get();
x_handle = gkIO::ReadWord(infile);
y_handle = gkIO::ReadWord(infile);
gkIO::ReadWord(infile);
gkIO::ReadLong(infile); //discard reserved space
if(!width || !height) return 1; //nothing to load, null shape
int pitch = width << 2;
gkBYTE *destStart = data;
gkLONG *dest;
int x,y;
for(y=0; y<height; y++){
dest = (gkLONG*) destStart;
for(x=0; x<width; x++){
*(dest++) = gkIO::ReadLong(infile);
}
destStart += pitch;
}
return 1;
}
int gkBitmap::LoadBMP(char *filename){
ifstream infile(filename,ios::in|ios::binary|ios::nocreate);
if(!infile) return 0;
//gkFileInputBuffer gkInfile(filename);
//if(!gkInfile.Exists()) return 0;
//istream &infile = *gkInfile.GetIStream();
int result = this->LoadBMP(infile);
infile.close();
return result;
}
int gkBitmap::LoadBMP(istream &infile){
BMP_header header;
if(gkIO::ReadWord(infile)!=0x424d){ //check for "BM"
return 0;
}
infile.read((char*)&header, sizeof(BMP_header));
if(header.bpp != 24){
cout << "LoadBMP can only handle 24-bit files" << endl;
return 0;
}
FreeData();
width = header.width;
height = header.height;
bpp = (char) header.bpp;
Create(width,height);
// load graphics, coverting every three (B,R,G) bytes to one ARGB value.
// lines padded to even multiple of 4 bytes
int srcPitch = ((header.width * 3) + 3) & (~3);
gkBYTE *buffer = new gkBYTE[srcPitch * height];
gkBYTE *nextBuffPtr = buffer + ((height-1) * srcPitch);
gkBYTE *buffPtr;
infile.read(buffer, srcPitch * height);
gkBYTE *nextDest = data;
gkRGB *dest;
int destPitch = (width << 2);
int i, j;
j = height;
while(j--){
buffPtr = nextBuffPtr;
nextBuffPtr -= srcPitch;
dest = (gkRGB*) nextDest;
nextDest += destPitch;
i = header.width;
while(i--){
dest->SetB(*(buffPtr++));
dest->SetG(*(buffPtr++));
dest->SetR(*(buffPtr++));
dest->SetA(0xff);
dest++;
}
for(i=header.width; i<width; i++){
dest->SetARGB(0);
dest++;
}
}
delete buffer;
return 1;
}
int gkBitmap::SaveBMP(char *filename){
if(!data) return 0;
if(!filename) return 0;
//open file
ofstream outfile;
outfile.open(filename, ios::out | ios::binary);
if(!outfile) return 0;
outfile << 'B' << 'M'; //"BM" (file type)
BMP_header header;
memset(&header,0,sizeof(header)); //clear everything to zero
header.width = width;
header.height = height;
header.bpp = 24;
header.planes = 1;
header.imageSize = (header.width * header.height * header.bpp) / 8;
header.headerSize = 40;
header.offsetBytes = 54; //header + palette size
header.fSize = 54 + header.imageSize;
outfile.write((char*)&header, sizeof(BMP_header));
// save graphics as bottom-to-top, left-to-right //
int y = height - 1;
int pitch = width*4;
gkBYTE *src = data + (y * pitch); //find bottom of buffer
gkBYTE *d;
//write brg bytes out
int i;
for(; y>=0; y--){
d = src;
for(i=0; i<width; i++){
int r,g,b;
b = *(d++); g = *(d++); r = *d;
outfile << (char) b << (char) g << (char) r;
d+=2;
}
src -= pitch;
}
outfile.close();
return 1;
}
void gkBitmap::Blit(gkBitmap *destBitmap, int x, int y, int flags){
if(!data || !destBitmap || !destBitmap->data) return;
gkBYTE *src = 0;
int srcWidth = this->width;
int srcSkip = this->width;
int lines = this->height;
//clip left side
if(x < 0){
src += -x; //times 4 later
srcWidth -= -x;
x = 0;
}
//clip right side
int diff = (x + srcWidth) - destBitmap->width;
if(diff > 0){
srcWidth -= diff;
}
if(srcWidth <= 0) return;
//clip top
if(y<0){
src += (-y * this->width); //times 4 later
lines += y; //lines -= (-y)
y = 0;
}
//clip bottom
diff = (y + lines) - destBitmap->height;
if(diff > 0){
lines -= diff;
}
if(lines <= 0) return;
int destSkip = destBitmap->width;
gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2);
src = this->data + ((int)src << 2);
srcWidth <<= 2;
srcSkip <<= 2;
destSkip <<= 2;
if(flags & GKBLT_TRANSPARENT){
//blit using alpha 0 as fully transparent
while(lines--){
MemCpyTrans(dest, src, srcWidth);
src += srcSkip;
dest += destSkip;
}
}else{
//blit without a transparent color
while(lines--){
memcpy(dest, src, srcWidth);
src += srcSkip;
dest += destSkip;
}
}
}
//////////////////////////////////////////////////////////////////////
// Method: BlitColorToAlpha
// Description: Converts this bitmap's colors into alpha values on
// the destination bitmap. Black becomes transparent,
// white fully opaque.
//////////////////////////////////////////////////////////////////////
void gkBitmap::BlitColorToAlpha(gkBitmap *destBitmap, int x, int y){
if(!data || !destBitmap || !destBitmap->data) return;
gkBYTE *src = 0;
int srcWidth = this->width;
int srcSkip = this->width;
int lines = this->height;
//clip left side
if(x < 0){
src += -x; //times 4 later
srcWidth -= -x;
x = 0;
}
//clip right side
int diff = (x + srcWidth) - destBitmap->width;
if(diff > 0){
srcWidth -= diff;
}
if(srcWidth <= 0) return;
//clip top
if(y<0){
src += (-y * this->width); //times 4 later
lines += y; //lines -= (-y)
y = 0;
}
//clip bottom
diff = (y + lines) - destBitmap->height;
if(diff > 0){
lines -= diff;
}
if(lines <= 0) return;
int destSkip = destBitmap->width;
gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2);
src = this->data + ((int)src << 2);
srcWidth <<= 2;
srcSkip <<= 2;
destSkip <<= 2;
//blit converting color(B) to alpha.
while(lines--){
MemCpyColorToAlpha(dest, src, srcWidth);
src += srcSkip;
dest += destSkip;
}
}
//////////////////////////////////////////////////////////////////////
// Function: BlitScale
// Arguments: destBitmap
// x
// y
// flags
// scale - number of source pixels for every one
// dest pixel, stored in 24:8 fixed point.
// $100=100%, $200=200% (mag x2), $80=50%
//////////////////////////////////////////////////////////////////////
void gkBitmap::BlitScale(gkBitmap *destBitmap, int x, int y,
int scale, int flags){
if(!data || !destBitmap || !destBitmap->data || !scale) return;
gkBYTE *src = 0;
int srcSkip = this->width;
int srcWidth = (this->width * scale) >> 8;
int lines = (this->height * scale) >> 8;
//clip left side
if(x < 0){
src += (-x << 8) / scale;
srcWidth -= -x;
x = 0;
}
//clip right side
int diff = (x + srcWidth) - destBitmap->width;
if(diff > 0){
srcWidth -= diff;
}
if(srcWidth <= 0) return;
//clip top
if(y<0){
src += ((-y * this->width) << 8) / scale;
lines += y; //lines -= (-y)
y = 0;
}
//clip bottom
diff = (y + lines) - destBitmap->height;
if(diff > 0){
lines -= diff;
}
if(lines <= 0) return;
int destSkip = destBitmap->width;
gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2);
src = this->data + ((int)src << 2);
srcSkip <<= 2;
destSkip <<= 2;
int ratio = (int) ((1.0f / (((float) scale) / 256.0f)) * 256.0f);
int lineError = 0;
while(lines--){
BlitLineScale(dest, src, srcWidth, ratio);
lineError += ratio;
src += srcSkip * (lineError >> 8);
lineError &= 0xff;
dest += destSkip;
}
/*
if(flags & GKBLT_TRANSPARENT){
//blit using alpha 0 as fully transparent
while(lines--){
MemCpyTrans(dest, src, srcWidth);
src += srcSkip;
dest += destSkip;
}
}else{
//blit without a transparent color
while(lines--){
memcpy(dest, src, srcWidth);
src += srcSkip;
dest += destSkip;
}
}
*/
}
void gkBitmap::BlitScale(gkBitmap *destBitmap, int x, int y,
float scale, int flags){
BlitScale(destBitmap,x,y,flags,(int) (256.0f * scale));
}
void gkBitmap::BlitChannel(gkBitmap *destBitmap, int x, int y, int mask){
if(!data || !destBitmap || !destBitmap->data) return;
gkBYTE *src = 0;
int srcWidth = this->width;
int srcSkip = this->width;
int lines = this->height;
//clip left side
if(x < 0){
src += -x;
srcWidth -= -x;
x = 0;
}
//clip right side
int diff = (x + srcWidth) - destBitmap->width;
if(diff > 0){
srcWidth -= diff;
}
if(srcWidth <= 0) return;
//clip top
if(y<0){
src += (-y * this->width);
lines += y; //lines -= (-y)
y = 0;
}
//clip bottom
diff = (y + lines) - destBitmap->height;
if(diff > 0){
lines -= diff;
}
if(lines <= 0) return;
int destSkip = destBitmap->width;
gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2);
src = this->data + ((int)src << 2);
srcSkip <<= 2;
destSkip <<= 2;
int inverseMask = ~mask;
while(lines--){
gkLONG *curSrc = (gkLONG*) src;
gkLONG *curDest = (gkLONG*) dest;
int pixels = srcWidth;
while(pixels--){
*curDest = (*curSrc & mask) | (*curDest & inverseMask);
curSrc++;
curDest++;
}
src += srcSkip;
dest += destSkip;
}
}
void gkBitmap::MemCpyTrans(gkBYTE *dest, gkBYTE *src,
int numBytes){
//copies colors using the Alpha for transparency
gkRGB *destColor = (gkRGB*) dest;
gkRGB *srcColor = (gkRGB*) src;
int numColors = numBytes >> 2;
int c1;
while(numColors--){
int alpha;
switch(alpha = (srcColor->GetA())){
case 0: break;
case 255: //Straight copy
*destColor = *srcColor;
break;
default: //mix alpha
c1 = destColor->GetR();
c1 += tranTable.LookupTransparencyOffset(
srcColor->GetR()-c1, alpha);
destColor->SetR(c1);
c1 = destColor->GetG();
c1 += tranTable.LookupTransparencyOffset(
srcColor->GetG()-c1, alpha);
destColor->SetG(c1);
c1 = destColor->GetB();
c1 += tranTable.LookupTransparencyOffset(
srcColor->GetB()-c1, alpha);
destColor->SetB(c1);
break;
}
srcColor++;
destColor++;
}
}
void gkBitmap::MemCpyColorToAlpha(gkBYTE *dest, gkBYTE *src,
int numBytes){
//converts blue to alpha during copy
gkRGB *destColor = (gkRGB*) dest;
gkRGB *srcColor = (gkRGB*) src;
int numColors = numBytes >> 2;
while(numColors--){
destColor->SetA(srcColor->GetB());
srcColor++;
destColor++;
}
}
void gkBitmap::BlitLineScale(gkBYTE *dest,gkBYTE *src,int pixels,int ratio){
gkRGB *srcRGB = (gkRGB*) src;
gkRGB *destRGB = (gkRGB*) dest;
int error = 0;
while(pixels--){
*(destRGB++) = *srcRGB;
error += ratio;
srcRGB += error >> 8;
error &= 0xff;
}
}
| 23.653318
| 80
| 0.551541
|
AbePralle
|
c4b50bedc3bb54bfbb59187ee501a5282bf48997
| 9,085
|
cpp
|
C++
|
src/stream/analysis/RtCurrentActivation.cpp
|
cdla/murfi2
|
45dba5eb90e7f573f01706a50e584265f0f8ffa7
|
[
"Apache-2.0"
] | 7
|
2015-02-10T17:00:49.000Z
|
2021-07-27T22:09:43.000Z
|
src/stream/analysis/RtCurrentActivation.cpp
|
cdla/murfi2
|
45dba5eb90e7f573f01706a50e584265f0f8ffa7
|
[
"Apache-2.0"
] | 11
|
2015-02-22T19:15:53.000Z
|
2021-08-04T17:26:18.000Z
|
src/stream/analysis/RtCurrentActivation.cpp
|
cdla/murfi2
|
45dba5eb90e7f573f01706a50e584265f0f8ffa7
|
[
"Apache-2.0"
] | 8
|
2015-07-06T22:31:51.000Z
|
2019-04-22T21:22:07.000Z
|
/*=========================================================================
* RtCurrentActivation.cpp is the implementation of a class
*
* ****************************************************************************/
#include "RtDesignMatrix.h"
#include"RtCurrentActivation.h"
#include"RtMRIImage.h"
#include"RtActivation.h"
#include"RtDataIDs.h"
#include"RtExperiment.h"
#include"RtElementAccess.h"
#include"util/timer/timer.h"
#include"debug_levels.h"
string RtCurrentActivation::moduleString(ID_CURRENTACTIVATION);
// default constructor
RtCurrentActivation::RtCurrentActivation() : RtStreamComponent() {
componentID = moduleString;
steadyStateResidual = NULL;
numDataPointsForErrEst = std::numeric_limits<unsigned int>::max();
}
// destructor
RtCurrentActivation::~RtCurrentActivation() {
}
// initialize the estimation algorithm for a particular image size
void RtCurrentActivation::initEstimation(RtMRIImage &dat, RtMaskImage *mask) {
}
// process an option in name of the option to process val text of the option
// node
bool RtCurrentActivation::processOption(const string &name, const string &text,
const map<string, string> &attrMap) {
// look for known options
if (name == "modelFitModuleID") {
modelFitModuleID = text;
return true;
}
if (name == "modelFitRoiID") {
modelFitRoiID = text;
return true;
}
if (name == "numDataPointsForErrEst") {
return RtConfigVal::convert<unsigned int>(numDataPointsForErrEst, text);
}
if (name == "saveResult") {
return RtConfigVal::convert<bool>(saveResult, text);
}
return RtStreamComponent::processOption(name, text, attrMap);
}
// validate the configuration
bool RtCurrentActivation::validateComponentConfig() {
bool result = true;
if (modelFitModuleID.empty()) {
cerr << "RtCurrentActivation::process: modelFitModuleID is empty" << endl;
result = false;
}
if (modelFitRoiID.empty()) {
cerr << "RtCurrentActivation::process: modelFitRoiID is empty" << endl;
result = false;
}
return result;
}
// process a single acquisition
int RtCurrentActivation::process(ACE_Message_Block *mb) {
ACE_TRACE(("RtCurrentActivation::process"));
timer tim;
if(printTiming) {
tim.start();
}
// get pointer to message
RtStreamMessage *msg = (RtStreamMessage*) mb->rd_ptr();
// get the current image to operate on
RtMRIImage *dat = (RtMRIImage*) msg->getCurrentData();
// check for validity of data
if (dat == NULL) {
cerr << "RtCurrentActivation::process: data passed is NULL" << endl;
if(logOutput) {
stringstream logs("");
logs << "RtCurrentActivation::process: data passed is NULL" << endl;
log(logs);
}
return 0;
}
// get mask from msg
RtMaskImage *mask = getMaskFromMessage(*msg);
// check validity of mask
if (mask == NULL) {
cerr << "RtCurrentActivation::process: mask is NULL" << endl;
if(logOutput) {
stringstream logs("");
logs << "RtCurrentActivation::process: mask is NULL at tr "
<< dat->getDataID().getTimePoint() << endl;
log(logs);
}
return 0;
}
// initialize the computation if necessary
if (needsInit) {
initEstimation(*dat, mask);
}
// get design
// TODO this may not work if there are more than one design matrix
RtDataID tempDataID;
tempDataID.setDataName(NAME_DESIGN);
// debug
// getDataStore().getAvailableData();
RtDesignMatrix *design = static_cast<RtDesignMatrix*>(
getDataStore().getData(tempDataID));
if(design == NULL) {
cerr << "error: could not find design matrix in datastore!" << endl;
cerr << "searched for design matrix id: " << tempDataID << endl;
return 0;
}
// allocate a new data image for the stats
RtActivation *currentActivation = new RtActivation(*dat);
// setup the data id
currentActivation->getDataID().setFromInputData(*dat, *this);
currentActivation->getDataID().setDataName(NAME_ACTIVATION);
currentActivation->getDataID().setRoiID(modelFitRoiID);
currentActivation->initToNans();
// get the residual and the beta images for discounting nuissance
// signals
// find the betas
RtActivation **betas = new RtActivation*[design->getNumColumns()];
for(unsigned int j = 0; j < design->getNumColumns(); j++) {
betas[j] = (RtActivation*) msg->getData(modelFitModuleID,
string(NAME_BETA)
+ "_" +
design->getColumnName(j),
modelFitRoiID);
// check for found
if (betas[j] == NULL) {
cerr << "RtCurrentActivation:process: beta " << j << " is null" << endl;
if(logOutput) {
stringstream logs("");
logs << "RtCurrentActivation::process: beta " << j
<< " is NULL at tr "
<< dat->getDataID().getTimePoint() << endl;
log(logs);
}
return 0;
}
}
// get residual from message if timepoint is less than
// numDataPointsForErrEst otherwise use the steady state
// residual value
RtActivation *residual;
if (dat->getDataID().getTimePoint() < numDataPointsForErrEst) {
// get residual off of msg
residual = (RtActivation *) msg->getData(modelFitModuleID,
NAME_RESIDUAL_MSE,
modelFitRoiID);
// save off residual
steadyStateResidual = residual;
}
else {
// post-numDataPointsForErrEst, use saved residual
residual = steadyStateResidual;
}
// check that residual is not null
if (residual == NULL) {
cerr << "RtCurrentActivation:process: residual is null" << endl;
if(logOutput) {
stringstream logs("");
logs << "RtCurrentActivation::process: residual is NULL at tr "
<< dat->getDataID().getTimePoint() << endl;
log(logs);
}
return 0;
}
// get this design matrix row
vnl_vector<double> Xrow = design->getRow(dat->getDataID().getTimePoint()-1);
// include this timepoint for each voxel
RtElementAccess datAc(dat, mask);
RtElementAccess resAc(residual, mask);
vector<unsigned int> inds = datAc.getElementIndices();
for(vector<unsigned int>::iterator it = inds.begin();
it != inds.end(); it++) {
// get voxel intensity
double y = datAc.getDoubleElement(*it);
double *betavals = new double[Xrow.size()];
// compute error
double err = y;
for (unsigned int j = 0; j < Xrow.size(); j++) {
if (!design->isColumnOfInterest(j)) {
double beta = betas[j]->getPixel(*it);
err -= beta * Xrow[j];
betavals[j] = beta;
}
else { // for debug output
betavals[j] = betas[j]->getPixel(*it);
}
}
// compute the dev and current activation (magic happens here)
double dev = sqrt(resAc.getDoubleElement(*it)
/ (residual->getDataID().getTimePoint()));
currentActivation->setPixel(*it, err / dev);
if (dumpAlgoVars && dat->getDataID().getTimePoint() > 2) {
dumpFile
<< dat->getDataID().getTimePoint() << " "
<< *it << " "
<< y << " "
<< err << " "
<< Xrow[0] << " "
<< residual->getPixel(*it) << " "
<< dev << " "
<< currentActivation->getPixel(*it) << " ";
for (unsigned int b = 0; b < design->getNumColumns(); b++) {
dumpFile << betavals[b] << " ";
}
dumpFile << endl;
}
delete [] betavals;
}
setResult(msg, currentActivation);
setResult(msg, residual);
delete [] betas;
if(printTiming) {
tim.stop();
cout << "RtCurrentActivation process at tr "
<< dat->getDataID().getTimePoint()
<< " elapsed time: " << tim.elapsed_time()*1000 << "ms" << endl;
}
if(print) {
cout << "RtCurrentActivation: done at tr "
<< dat->getDataID().getTimePoint() << endl;
}
if(logOutput) {
stringstream logs("");
logs << "RtCurrentActivation: done at tr "
<< dat->getDataID().getTimePoint() << endl;
log(logs);
}
if(saveResult) {
string fn = getExperimentConfig().getVolFilename(
dat->getDataID().getSeriesNum(),
dat->getDataID().getTimePoint());
string stem = getExperimentConfig().get("study:volumeFileStem").str();
currentActivation->setFilename(fn.replace(fn.rfind(stem), stem.size(),
"curact"));
currentActivation->save();
}
return 0;
}
// start a logfile
void RtCurrentActivation::startDumpAlgoVarsFile() {
dumpFile << "started at ";
printNow(dumpFile);
dumpFile << endl
<< "time_point "
<< "voxel_index "
<< "voxel_intensity "
<< "activation_signal "
<< "condition "
<< "residual "
<< "dev "
<< "current_activation "; // aka feedback
for (int b = 0; b < 3; b++) {
dumpFile << "beta[" << b << "] ";
}
dumpFile << "end" << endl;
}
| 28.126935
| 80
| 0.597248
|
cdla
|
c4bcd09ca73577998542021179cf2f89915ab43c
| 2,579
|
hpp
|
C++
|
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright 2020-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_IR_GRAPH_TUNABLE_OP_HPP
#define BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_IR_GRAPH_TUNABLE_OP_HPP
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <compiler/ir/graph/graph.hpp>
#include <compiler/ir/graph/trait/configurable.hpp>
#include <compiler/ir/graph/traits.hpp>
#include <ops/body_generator.hpp>
#include <util/utils.hpp>
namespace sc {
class SC_INTERNAL_API tunable_op_t : public sc_op,
public op_traits::copyable_t,
public op_traits::may_quantize_t,
public op_traits::post_fusion_acceptable_t,
public op_traits::configurable_t {
public:
tunable_op_t(const std::string &op_name,
const std::vector<graph_tensor_ptr> &ins,
const std::vector<graph_tensor_ptr> &outs, const any_map_t &attrs);
sc_op_ptr copy(const std::vector<graph_tensor_ptr> &ins,
const std::vector<graph_tensor_ptr> &outs,
sc_graph_t &mgr) override;
bool is_valid(const context_ptr &) override;
ir_module_ptr get_func(context_ptr ctx,
const std::shared_ptr<fusion_manager> &fuse_mgr,
const std::string &func_name) override {
throw std::runtime_error("unimplemented");
}
ir_module_ptr get_func(context_ptr ctx) override;
config_ptr get_config() override { return config_data_; }
void set_config(const config_ptr &config) override;
void set_config_if_empty(context_ptr ctx, body_generator_base_t *p);
config_ptr get_default_config(context_ptr ctx) override;
virtual body_generator_ptr create_generator() = 0;
protected:
config_ptr config_data_;
};
} // namespace sc
#endif
| 36.842857
| 81
| 0.659558
|
wuxun-zhang
|
c4bff15003d2c1ed21acb480e4e4e50165c28f2d
| 5,568
|
cpp
|
C++
|
wallet/unittests/util.cpp
|
akhavr/beam
|
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
|
[
"Apache-2.0"
] | null | null | null |
wallet/unittests/util.cpp
|
akhavr/beam
|
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
|
[
"Apache-2.0"
] | null | null | null |
wallet/unittests/util.cpp
|
akhavr/beam
|
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
|
[
"Apache-2.0"
] | null | null | null |
#include "util.h"
#include "wallet/wallet.h"
#include "core/ecc_native.h"
#include "core/serialization_adapters.h"
#include "utility/logger.h"
#include <boost/filesystem.hpp>
#include <iterator>
#include <future>
using namespace std;
using namespace beam;
using namespace ECC;
namespace beam {
struct TreasuryBlockGenerator
{
std::string m_sPath;
IKeyChain* m_pKeyChain;
std::vector<Block::Body> m_vBlocks;
ECC::Scalar::Native m_Offset;
std::vector<Coin> m_Coins;
std::vector<std::pair<Height, ECC::Scalar::Native> > m_vIncubationAndKeys;
std::mutex m_Mutex;
std::vector<std::thread> m_vThreads;
Block::Body& get_WriteBlock();
void FinishLastBlock();
int Generate(uint32_t nCount, Height dh);
private:
void Proceed(uint32_t i);
};
bool ReadTreasury(std::vector<Block::Body>& vBlocks, const string& sPath)
{
if (sPath.empty())
return false;
std::FStream f;
if (!f.Open(sPath.c_str(), true))
return false;
yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(f);
arc & vBlocks;
return true;
}
int TreasuryBlockGenerator::Generate(uint32_t nCount, Height dh)
{
if (m_sPath.empty())
{
LOG_ERROR() << "Treasury block path not specified";
return -1;
}
boost::filesystem::path path{ m_sPath };
boost::filesystem::path dir = path.parent_path();
if (!dir.empty() && !boost::filesystem::exists(dir) && !boost::filesystem::create_directory(dir))
{
LOG_ERROR() << "Failed to create directory: " << dir.c_str();
return -1;
}
if (ReadTreasury(m_vBlocks, m_sPath))
LOG_INFO() << "Treasury already contains " << m_vBlocks.size() << " blocks, appending.";
if (!m_vBlocks.empty())
{
m_Offset = m_vBlocks.back().m_Offset;
m_Offset = -m_Offset;
}
LOG_INFO() << "Generating coins...";
m_Coins.resize(nCount);
m_vIncubationAndKeys.resize(nCount);
Height h = 0;
for (uint32_t i = 0; i < nCount; i++, h += dh)
{
Coin& coin = m_Coins[i];
coin.m_key_type = KeyType::Regular;
coin.m_amount = Rules::Coin * 10;
coin.m_status = Coin::Unconfirmed;
coin.m_createHeight = h + Rules::HeightGenesis;
m_vIncubationAndKeys[i].first = h;
}
m_pKeyChain->store(m_Coins); // we get coin id only after store
for (uint32_t i = 0; i < nCount; ++i)
m_vIncubationAndKeys[i].second = m_pKeyChain->calcKey(m_Coins[i]);
m_vThreads.resize(std::thread::hardware_concurrency());
assert(!m_vThreads.empty());
for (uint32_t i = 0; i < m_vThreads.size(); i++)
m_vThreads[i] = std::thread(&TreasuryBlockGenerator::Proceed, this, i);
for (uint32_t i = 0; i < m_vThreads.size(); i++)
m_vThreads[i].join();
// at least 1 kernel
{
Coin dummy; // not a coin actually
dummy.m_key_type = KeyType::Kernel;
dummy.m_status = Coin::Unconfirmed;
ECC::Scalar::Native k = m_pKeyChain->calcKey(dummy);
TxKernel::Ptr pKrn(new TxKernel);
pKrn->m_Excess = ECC::Point::Native(Context::get().G * k);
Merkle::Hash hv;
pKrn->get_Hash(hv);
pKrn->m_Signature.Sign(hv, k);
get_WriteBlock().m_vKernelsOutput.push_back(std::move(pKrn));
m_Offset += k;
}
FinishLastBlock();
for (auto i = 0u; i < m_vBlocks.size(); i++)
{
m_vBlocks[i].Sort();
m_vBlocks[i].DeleteIntermediateOutputs();
}
std::FStream f;
f.Open(m_sPath.c_str(), false, true);
yas::binary_oarchive<std::FStream, SERIALIZE_OPTIONS> arc(f);
arc & m_vBlocks;
f.Flush();
/*
for (auto i = 0; i < m_vBlocks.size(); i++)
m_vBlocks[i].IsValid(i + 1, true);
*/
LOG_INFO() << "Done";
return 0;
}
void TreasuryBlockGenerator::FinishLastBlock()
{
m_Offset = -m_Offset;
m_vBlocks.back().m_Offset = m_Offset;
}
Block::Body& TreasuryBlockGenerator::get_WriteBlock()
{
if (m_vBlocks.empty() || m_vBlocks.back().m_vOutputs.size() >= 1000)
{
if (!m_vBlocks.empty())
FinishLastBlock();
m_vBlocks.resize(m_vBlocks.size() + 1);
m_vBlocks.back().ZeroInit();
m_Offset = Zero;
}
return m_vBlocks.back();
}
void TreasuryBlockGenerator::Proceed(uint32_t i0)
{
std::vector<Output::Ptr> vOut;
for (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size())
{
const Coin& coin = m_Coins[i];
Output::Ptr pOutp(new Output);
pOutp->m_Incubation = m_vIncubationAndKeys[i].first;
const ECC::Scalar::Native& k = m_vIncubationAndKeys[i].second;
pOutp->Create(k, coin.m_amount);
vOut.push_back(std::move(pOutp));
//offset += k;
//subBlock.m_Subsidy += coin.m_amount;
}
std::unique_lock<std::mutex> scope(m_Mutex);
uint32_t iOutp = 0;
for (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size(), iOutp++)
{
Block::Body& block = get_WriteBlock();
block.m_vOutputs.push_back(std::move(vOut[iOutp]));
block.m_Subsidy += m_Coins[i].m_amount;
m_Offset += m_vIncubationAndKeys[i].second;
}
}
IKeyChain::Ptr init_keychain(const std::string& path, uintBig* walletSeed) {
static const std::string TEST_PASSWORD("12321");
if (boost::filesystem::exists(path)) boost::filesystem::remove_all(path);
std::string password(TEST_PASSWORD);
password += path;
NoLeak<uintBig> seed;
Hash::Value hv;
Hash::Processor() << password.c_str() >> hv;
seed.V = hv;
auto keychain = Keychain::init(path, password, seed);
if (walletSeed) {
TreasuryBlockGenerator tbg;
tbg.m_sPath = path + "_";
tbg.m_pKeyChain = keychain.get();
Height dh = 1;
uint32_t nCount = 10;
tbg.Generate(nCount, dh);
*walletSeed = seed.V;
}
return keychain;
}
} //namespace
std::ostream& operator<<(std::ostream& os, const ECC::Scalar::Native& sn) {
Scalar s;
sn.Export(s);
os << s.m_Value;
return os;
}
| 22.91358
| 98
| 0.670079
|
akhavr
|
c4c0b522503bdaa8f32bdc1d1d27962a548fc734
| 1,470
|
cc
|
C++
|
grey_level_histogram.cc
|
jkloe/pageDistanceBasedContourGenerator
|
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
|
[
"MIT"
] | 6
|
2019-03-06T23:54:01.000Z
|
2020-08-24T09:18:33.000Z
|
grey_level_histogram.cc
|
jkloe/pageDistanceBasedContourGenerator
|
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
|
[
"MIT"
] | 6
|
2019-03-07T00:31:48.000Z
|
2021-01-10T13:28:41.000Z
|
grey_level_histogram.cc
|
jkloe/pageDistanceBasedContourGenerator
|
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
|
[
"MIT"
] | 8
|
2019-03-07T00:08:43.000Z
|
2021-05-13T12:14:08.000Z
|
#include "grey_level_histogram.hpp"
namespace prhlt{
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace boost;
Grey_Level_Histogram::Grey_Level_Histogram(){
this->logger = Logger::getLogger("PRHLT.Grey_Level_Histogram");
}
Grey_Level_Histogram::Grey_Level_Histogram(cv::Mat &ex_image){
this->logger = Logger::getLogger("PRHLT.Grey_Level_Histogram");
this->image = ex_image;
}
Grey_Level_Histogram::~Grey_Level_Histogram(){
this->image.release();
this->histogram.clear();
}
void Grey_Level_Histogram::set_image(cv::Mat &ex_image){
this->image = ex_image;
}
float Grey_Level_Histogram::run(){
return calculate_grey_level_histogram();
}
float Grey_Level_Histogram::calculate_grey_level_histogram(){
this->histogram_sum = 0.0;
for (int r=0; r < this->image.rows; r++)
for (int c=0; c < this->image.cols; c++)
this->histogram[this->image.at<uchar>(r,c)]+=1.0;
int num_pixels = this->image.rows * this->image.cols;
BOOST_FOREACH(sparse_histogram::value_type i, this->histogram){
this->histogram[i.first]= i.second/num_pixels;
}
BOOST_FOREACH(sparse_histogram::value_type i, this->histogram){
this->histogram_sum+= i.first * i.second;
}
return this->histogram_sum;
}
}
| 31.956522
| 71
| 0.619048
|
jkloe
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.