hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01d72abac4cfe9609df0fbda7140cbaf0a1f800f
| 2,528
|
cpp
|
C++
|
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | 1
|
2019-12-26T21:07:22.000Z
|
2019-12-26T21:07:22.000Z
|
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | null | null | null |
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | 1
|
2020-01-02T01:27:42.000Z
|
2020-01-02T01:27:42.000Z
|
#include "AsyncFileReader.h"
#include <sys/epoll.h>
#include <unistd.h>
#include <stdio.h>
AsyncFileReader::AsyncFileReader()
: epoll_fd_(epoll_create1(0)),
stopped_(false)
{
static_assert(EVENT_BUFFER_SIZE > 0, "EVENT_BUFFER_SIZE must be greater than 0");
static_assert(READ_BUFFER_SIZE > 0, "READ_BUFFER_SIZE must be greater than 0");
}
AsyncFileReader::~AsyncFileReader()
{
close(epoll_fd_);
}
void AsyncFileReader::addFileDescriptor(const int fd)
{
struct epoll_event epoll_event;
epoll_event.events = EPOLLIN;
epoll_event.data.fd = fd;
epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &epoll_event);
}
void AsyncFileReader::removeFileDescriptor(const int fd)
{
struct epoll_event epoll_event; // For the sake of compatibility with older versions of Linux, this struct must exist (pointer to struct cannot be nullptr).
epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &epoll_event);
}
void AsyncFileReader::runAsyncLoop()
{
struct epoll_event epoll_event_buffer[EVENT_BUFFER_SIZE];
while(!stopped_)
{
// Call epoll_wait with a timeout of 1000 milliseconds.
const int fds_ready = epoll_wait(epoll_fd_, epoll_event_buffer, EVENT_BUFFER_SIZE, 1000);
// Function epoll_wait returned.
if(-1 == fds_ready)
{
// An error occured.
stopped_ = true;
continue;
}
// Handle any file descriptors with events.
for(int i = 0; i < fds_ready; i++)
{
const struct epoll_event& epoll_event = epoll_event_buffer[i];
/* To use multiple CPUs, you could execute the handlers on (multiple) worker threads. For the sake of simplicity, polling and handling is done on the same thread now. */
handleEventOnFile(epoll_event);
}
}
}
void AsyncFileReader::stopAsyncLoop()
{
stopped_ = true;
}
bool AsyncFileReader::hasStopped()
{
return stopped_;
}
void AsyncFileReader::handleEventOnFile(const struct epoll_event& epoll_event)
{
const uint32_t events = epoll_event.events;
const int fd = epoll_event.data.fd;
if(EPOLLERR & events)
{
// An error occured on the file descriptor. Try to close it.
removeFileDescriptor(fd);
close(fd);
}
else if(EPOLLIN & events)
{
// Read is available, read in from the file descriptor and print the message.
int read_result = read(fd, read_buffer_, READ_BUFFER_SIZE-1);
if(-1 == read_result)
{
// An error occured while reading.
removeFileDescriptor(fd);
close(fd);
return;
}
// Successfully read in some bytes.
read_buffer_[read_result] = '\0';
printf("Read %d bytes\n", read_result);
printf("%s", read_buffer_);
}
}
| 24.07619
| 172
| 0.730222
|
daank94
|
01daf20c9fab3925dd7c843fd491b5cfa35042df
| 977
|
cpp
|
C++
|
uva/chapter_3/10341.cpp
|
metaflow/contests
|
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
|
[
"MIT"
] | 1
|
2019-05-12T23:41:00.000Z
|
2019-05-12T23:41:00.000Z
|
uva/chapter_3/10341.cpp
|
metaflow/contests
|
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
|
[
"MIT"
] | null | null | null |
uva/chapter_3/10341.cpp
|
metaflow/contests
|
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <stdio.h>
#include <iostream>
using namespace std;
int p, q, r, s, t, u;
double f(double x) {
return p * exp(-x) + q * sin(x) + r * cos(x) + s * tan(x) + t * x * x + u;
}
double fd(double x){ // the derivative of function f
return -p*exp(-x) + q*cos(x) - r*sin(x) + s/(cos(x)*cos(x)) + 2*t*x;
}
int loops = 0;
const double EPS = 1e-7;
double newton(){
if (f(0)==0) return 0;
for (double x=0.5; ;){ // initial guess x = 0.5
loops++;
double x1 = x - f(x)/fd(x); // x1 = next guess
if (round(x1 * 10000) == round(x * 10000)) return x;
x = x1;
}
}
int main() {
while (scanf("%d%d%d%d%d%d", &p, &q, &r, &s, &t, &u) == 6) {
double r = 1.0d;
double l = 0.0d;
double lv = f(l);
double rv = f(r);
if (lv * rv > 0) {
printf("No solution\n");
continue;
}
printf("%.4lf\n", newton());
}
cerr << loops;
return 0;
}
| 21.23913
| 78
| 0.468782
|
metaflow
|
01dd7017a5734ed0acb9fa4079335c1f4ed723f2
| 1,504
|
cpp
|
C++
|
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | null | null | null |
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | 6
|
2019-03-14T11:57:03.000Z
|
2019-06-07T10:42:18.000Z
|
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | null | null | null |
#include <QtWebEngineCore>
#include <QApplication>
#include <QWebEngineView>
#include <QVBoxLayout>
#include <QPushButton>
#include <QWidget>
QUrl commandLineUrlArgument()
{
const QStringList args = QCoreApplication::arguments();
for (const QString &arg : args.mid(1)) {
if (!arg.startsWith(QLatin1Char('-')))
return QUrl::fromUserInput(arg);
}
return QUrl(QStringLiteral("http://iip.sogang.ac.kr"));
}
int main(int argc, char *argv[])
{
QCoreApplication::addLibraryPath("../lib");
QCoreApplication::setOrganizationName("QtExamples");
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QWidget widget_main;
QVBoxLayout layout_main;
QPushButton btn_scroll("scroll to bottom");
QWebEngineView view_main;
widget_main.setLayout(&layout_main);
layout_main.addWidget(&btn_scroll);
layout_main.addWidget(&view_main);
view_main.setUrl(commandLineUrlArgument());
view_main.resize(1024, 750);
widget_main.show();
QObject::connect(&btn_scroll, &QPushButton::clicked,
[&](){
/*
view_main.page()->runJavaScript("\
var scrollingElement = (document.scrollingElement || document.body);\
scrollingElement.scrollTop = scrollingElement.scrollHeight;\
");
*/
view_main.page()->runJavaScript(" window.scrollTo(0,document.body.scrollHeight);");
// view_main.page()->runJavaScript( "window.scrollTo(500, 500);");
}
);
app.exec();
return 0;
}
| 24.258065
| 89
| 0.692154
|
kooBH
|
01e23ec8197e816ffb8957afcc85f7b9973b60ef
| 3,163
|
hpp
|
C++
|
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef PHYSICS_HPP
#define PHYSICS_HPP
#include "cloth.hpp"
#include "obstacle.hpp"
#include "geometry.hpp"
#include "simulation.hpp"
#include "taucs.hpp"
#include <vector>
using torch::Tensor;
template <Space s>
Tensor internal_energy (const Cloth &cloth);
Tensor constraint_energy (const std::vector<Constraint*> &cons);
Tensor external_energy (const Cloth &cloth, const Tensor &gravity,
const Wind &wind);
// A += dt^2 dF/dx; b += dt F + dt^2 dF/dx v
// also adds damping terms
// if dt == 0, just does A += dF/dx; b += F instead, no damping
template <Space s>
void add_internal_forces (const Cloth &cloth, SpMat &A,
Tensor &b, Tensor dt);
void add_constraint_forces (const Cloth &cloth,
const std::vector<Constraint*> &cons,
SpMat &A, Tensor &b, Tensor dt);
void add_external_forces (const Cloth &cloth, const Tensor &gravity,
const Wind &wind, Tensor &fext,
Tensor &Jext);
void obs_add_external_forces (const Obstacle &obstacle, const Tensor &gravity,
const Wind &wind, Tensor &fext,
Tensor &Jext);
void add_morph_forces (const Cloth &cloth, const Morph &morph, Tensor t,
Tensor dt,
Tensor &fext, Tensor &Jext);
void implicit_update (Cloth &cloth, const Tensor &fext,
const Tensor &Jext,
const std::vector<Constraint*> &cons, Tensor dt,
bool update_positions=true);
void obs_implicit_update (Obstacle &obstacle, const vector<Mesh*> &obs_meshes, const Tensor &fext,
const Tensor &Jext,
const vector<Constraint*> &cons, Tensor dt,
bool update_positions);
#endif
| 39.5375
| 98
| 0.669617
|
priyasundaresan
|
01e2fc1419df585b6bbda0d311ec4e0ead3faa7e
| 2,287
|
cpp
|
C++
|
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | 1
|
2021-09-26T14:15:33.000Z
|
2021-09-26T15:40:32.000Z
|
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | null | null | null |
#include <benchmark/benchmark.h>
#include <cstdlib>
#include <ctime>
#include <memory>
#include "abu/mem.h"
namespace {
static void BM_shared_ptr_int_lifetime(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = std::make_shared<int>(v);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_int_lifetime);
static void BM_shared_ptr_int_access(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = std::make_shared<int>(v);
int u = *tmp;
benchmark::DoNotOptimize(u);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_int_access);
static void BM_ref_counted_int_lifetime(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = abu::mem::make_ref_counted<int>(v);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_int_lifetime);
static void BM_ref_counted_int_access(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = abu::mem::make_ref_counted<int>(v);
int u = *tmp;
benchmark::DoNotOptimize(u);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_int_access);
static void BM_shared_ptr_obj_lifetime(benchmark::State& state) {
struct ObjType {};
for (auto _ : state) {
auto tmp = std::make_shared<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_obj_lifetime);
static void BM_ref_counted_obj_lifetime(benchmark::State& state) {
struct ObjType {};
for (auto _ : state) {
auto tmp = abu::mem::make_ref_counted<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_obj_lifetime);
static void BM_ref_counted_intrusive_obj_lifetime(benchmark::State& state) {
struct ObjType : public abu::mem::ref_counted {};
for (auto _ : state) {
auto tmp = abu::mem::make_ref_counted<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_intrusive_obj_lifetime);
} // namespace
BENCHMARK_MAIN();
| 25.131868
| 77
| 0.663314
|
abu-lib
|
01e399aae29a026843f9751f0769d04e8ba7dc2f
| 52,394
|
cpp
|
C++
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | 10
|
2020-11-08T13:40:44.000Z
|
2021-05-19T09:40:53.000Z
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | 2
|
2021-01-18T13:56:08.000Z
|
2021-03-11T13:45:05.000Z
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | null | null | null |
#include "equation.h"
#include "sprites.h"
#include "text.h"
#include "colors.h"
#include <algorithm>
#include <cmath>
static const Number E_VAL(std::exp(1.0));
static const Number PI_VAL(M_PI);
static const Number I_VAL(0.0, 1.0);
Equation::Equation() : parts(3)
{
parts[0].meta.assoc = 2;
parts[0].meta.special = Part::Specialty::Equation;
parts[0].meta.position = Part::Position::Start;
parts[0].meta.next = 1;
parts[2].meta.assoc = 0;
parts[2].meta.special = Part::Specialty::Equation;
parts[2].meta.position = Part::Position::End;
parts[2].meta.before = 1;
parts[1].meta.before = 0;
parts[1].meta.next = 2;
}
struct RenderInfo {
int current_x;
const int min_x, max_x, center_y;
const int height;
const int editing_part;
const int editing_char;
bool can_draw(const int vertical_offset) const
{
const bool x_correct = (min_x - (13 -1)) <= current_x && current_x < max_x;
const bool y_correct = -(height/2 + 24/2) < (vertical_offset - center_y) && (vertical_offset - center_y) <= (height/2 + 24);
return x_correct && y_correct;
}
int get_x() const
{
return current_x - min_x;
}
int get_y(const int vertical_offset) const
{
return center_y - vertical_offset + height/2 - 24/2;
}
};
struct RenderPart {
int data{};
// in deviation from the previous, counted in half parts
int middle_change{};
// in number of half parts, from the middle
int y_start{}; // positive, up
int y_end{}; // negative, down
// only used for special parts
int associated{};
int content_width{};
int content_middle_high{};
int paren_y_start{};
int paren_y_end{};
};
static void find_part_sizes(const std::vector<Part>& parts, std::vector<RenderPart>& part_sizes)
{
static std::vector<int> id_stack;
const auto pop_id = []() -> int {
const int i = id_stack.back();
id_stack.pop_back();
return i;
};
enum CareAbout : int {
CA_Width = 1,
CA_HeightBelow = 2,
CA_HeightAbove = 4,
CA_All = 1 | 2 | 4,
};
const auto add_content_info = [&](const RenderPart& ps, const CareAbout care = CA_All) -> void {
if(!id_stack.empty())
{
auto& container_size = part_sizes[id_stack.back()];
if(care & CA_Width)
{
container_size.content_width += ps.content_width;
}
if(care & (CA_HeightAbove | CA_HeightBelow))
{
if(care & CA_HeightAbove)
{
container_size.y_start = std::max(container_size.y_start, ps.y_start + ps.middle_change);
container_size.paren_y_start = std::max(container_size.paren_y_start, container_size.y_start);
container_size.paren_y_start = std::max(container_size.paren_y_start, ps.paren_y_start);
}
if(care & CA_HeightBelow)
{
container_size.y_end = std::min(container_size.y_end, ps.y_end + ps.middle_change);
container_size.paren_y_end = std::min(container_size.paren_y_end, container_size.y_end);
container_size.paren_y_end = std::min(container_size.paren_y_end, ps.paren_y_end);
}
container_size.content_middle_high = std::max(container_size.content_middle_high, ps.middle_change + ps.content_middle_high);
}
}
};
const auto do_part_basic = [&](const int idx) -> void {
const auto& p = parts[idx];
auto& ps = part_sizes[idx];
ps.data = [&]() -> int {;
if(p.meta.special == Part::Specialty::TempParen)
{
return 1;
}
else if(p.value.empty())
{
const auto& prev_meta = parts[p.meta.before].meta;
const auto& next_meta = parts[p.meta.next].meta;
const bool sandwiched = (check_pos_is(prev_meta.position, Part::Position::Start) && check_pos_is(next_meta.position, Part::Position::End)) && prev_meta.special == next_meta.special;
if(
(sandwiched && (
prev_meta.special == Part::Specialty::Equation ||
prev_meta.special == Part::Specialty::Paren ||
prev_meta.special == Part::Specialty::Absolute
))
||
(!sandwiched && (prev_meta.special == Part::Specialty::TempParen
|| next_meta.special != Part::Specialty::Exponent
|| (next_meta.special == Part::Specialty::Exponent && next_meta.position != Part::Position::Start)
|| (next_meta.special == Part::Specialty::Exponent && prev_meta.special == Part::Specialty::Paren && prev_meta.position == Part::Position::End)
))
)
{
return 0;
}
return 1;
}
else
{
return p.value.size();
}
}();
ps.content_width = ps.data;
ps.y_start = 1;
ps.y_end = -1;
ps.paren_y_start = 1;
ps.paren_y_end = -1;
add_content_info(ps);
};
int current_idx = 0;
while(current_idx != -1)
{
const auto& part = parts[current_idx];
if(part.meta.special == Part::Specialty::None || part.meta.special == Part::Specialty::TempParen)
{
do_part_basic(current_idx);
}
else if(part.meta.special != Part::Specialty::Equation)
{
if(check_pos_is(part.meta.position, Part::Position::End))
{
const int associated_id = pop_id();
const auto& ap = parts[associated_id];
auto& aps = part_sizes[associated_id];
auto& ps = part_sizes[current_idx];
if(part.meta.special == Part::Specialty::Exponent)
{
const int delta = (aps.y_start - aps.content_middle_high) - aps.y_end;
aps.middle_change = delta;
ps.middle_change = -delta;
aps.associated = current_idx;
ps.associated = associated_id;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Fraction)
{
if(check_pos_is(ap.meta.position, Part::Position::End)) // ending bottom part
{
ps.middle_change = aps.y_start + 1;
aps.middle_change += -ps.middle_change; // middle
aps.associated = current_idx; // middle.associated points to end
ps.associated = associated_id; // end.associated points to middle
RenderPart cp = aps;
cp.content_width = std::max(aps.content_width, aps.data);
cp.middle_change = -ps.middle_change;
add_content_info(cp, CareAbout(CA_HeightBelow | CA_Width));
}
else // ending top part
{
aps.middle_change = 2 + (-aps.y_end - 1); // start
ps.middle_change = -aps.middle_change;
aps.associated = current_idx; // start.associated points to middle
ps.data = aps.content_width; // middle.data is start.content_width
add_content_info(aps, CA_HeightAbove);
}
}
else if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute)
{
aps.associated = current_idx;
ps.associated = associated_id;
ps.paren_y_start = aps.paren_y_start;
ps.paren_y_end = aps.paren_y_end;
aps.content_width += 2;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Root)
{
aps.associated = current_idx;
ps.associated = associated_id;
ps.paren_y_start = aps.paren_y_start + 1;
ps.paren_y_end = aps.paren_y_end;
aps.content_width += 2;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Conjugate)
{
aps.associated = current_idx;
ps.associated = associated_id;
aps.y_start += 1;
ps.y_start = aps.y_start;
aps.paren_y_start = aps.y_start;
ps.paren_y_start = aps.paren_y_start;
ps.paren_y_end = aps.paren_y_end;
add_content_info(aps, CA_All);
}
}
if(check_pos_is(part.meta.position, Part::Position::Start))
{
id_stack.push_back(current_idx);
}
}
current_idx = part.meta.next;
}
id_stack.clear();
}
static void render_parts(const std::vector<Part>& parts, RenderInfo& info, Equation::RenderResult& out, PartPos* screen, C2D_SpriteSheet sprites)
{
static std::vector<RenderPart> part_sizes;
part_sizes.resize(parts.size());
find_part_sizes(parts, part_sizes);
int selected_multi_id = -1;
int selected_multi_assoc = -1;
if(info.editing_char == 0)
{
if(const auto& part_before = parts[parts[info.editing_part].meta.before]; part_before.meta.special == Part::Specialty::Paren || part_before.meta.special == Part::Specialty::Absolute)
{
selected_multi_id = parts[info.editing_part].meta.before;
selected_multi_assoc = part_before.meta.assoc;
}
}
int current_idx = 0;
C2D_Image empty_img = C2D_SpriteSheetGetImage(sprites, sprites_empty_but_clickable_idx);
C2D_Image lpa_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_lparen_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_lparen_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_lparen_end_idx),
};
C2D_Image rpa_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_rparen_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_rparen_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_rparen_end_idx),
};
C2D_Image abs_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_abs_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_abs_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_abs_end_idx),
};
C2D_Image sqrt_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_end_idx),
};
C2D_ImageTint text_tint;
C2D_PlainImageTint(&text_tint, COLOR_BLACK, 1.0f);
C2D_ImageTint temp_tint;
C2D_PlainImageTint(&temp_tint, COLOR_GRAY, 1.0f);
C2D_ImageTint paren_selected_tint;
C2D_PlainImageTint(&paren_selected_tint, COLOR_BLUE, 1.0f);
const auto draw_paren = [&](const C2D_Image* sprites, const int vertical_offset, const int y_start, const int y_end, const C2D_ImageTint* tnt) -> void {
const int span = (y_start - y_end) - 2;
const int span_pixels = (span * 24 / 4) + 1;
const int pixel_y = info.get_y(vertical_offset) - ((y_start - 1) * 24 / 4);
const int x = info.get_x();
C2D_DrawImageAt(sprites[0], x, pixel_y, 0.0f, tnt);
const int middle_y = pixel_y + sprites[0].subtex->height;
C2D_DrawImageAt(sprites[1], x, middle_y, 0.0f, tnt, 1.0f, span_pixels);
const int bottom_y = middle_y + span_pixels;
C2D_DrawImageAt(sprites[2], x, bottom_y, 0.0f, tnt);
};
const auto set_cursor = [&](const int y) -> void {
out.cursor_x = info.get_x();
out.cursor_y = y;
if(!(out.cursor_x <= -2 || out.cursor_x >= (320 - 2) || out.cursor_y <= (-24) || out.cursor_y >= EQU_REGION_HEIGHT))
{
out.cursor_visible = true;
}
};
int vertical_offset = 0;
int min_vert = 0;
int max_vert = 0;
PartPos pos;
while(current_idx != -1)
{
const auto& part = parts[current_idx];
const auto& part_size = part_sizes[current_idx];
if(part.meta.special == Part::Specialty::None)
{
pos.part = current_idx;
if(part.value.empty())
{
if(part_size.data != 0 && info.can_draw(vertical_offset))
{
const auto& img = empty_img;
C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint);
if(screen)
{
pos.pos = 0;
for(int y = 0; y < 24; y++)
{
const int actual_y = info.get_y(vertical_offset) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
}
if(info.editing_part == current_idx && info.editing_char == 0)
{
set_cursor(info.get_y(vertical_offset));
}
if(part_size.data != 0) info.current_x += 13;
}
else
{
int char_idx = 0;
for(const char c : part.value)
{
if(info.can_draw(vertical_offset))
{
const auto img = TextMap::char_to_sprite->equ.at(std::string_view(&c, 1));
C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint);
if(screen)
{
pos.pos = char_idx + 1;
for(int y = 0; y < 24; y++)
{
const int actual_y = info.get_y(vertical_offset) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
}
if(info.editing_part == current_idx && info.editing_char == char_idx)
{
set_cursor(info.get_y(vertical_offset));
}
info.current_x += 13;;
char_idx += 1;
}
if(info.editing_part == current_idx && info.editing_char == char_idx)
{
set_cursor(info.get_y(vertical_offset));
}
}
}
else if(part.meta.special != Part::Specialty::Equation)
{
if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::TempParen || part.meta.special == Part::Specialty::Absolute)
{
pos.part = part.meta.next;
const C2D_Image* sprs = nullptr;
if(part.meta.special == Part::Specialty::Absolute)
{
sprs = abs_sprites;
}
else if(part.meta.position == Part::Position::Start)
{
sprs = lpa_sprites;
}
else if(part.meta.position == Part::Position::End)
{
sprs = rpa_sprites;
}
const C2D_ImageTint* tnt = &temp_tint;
if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute)
{
if(current_idx == selected_multi_id || current_idx == selected_multi_assoc)
{
tnt = &paren_selected_tint;
}
else
{
tnt = &text_tint;
}
}
draw_paren(sprs, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, tnt);
if(screen)
{
const int h = ((part_size.paren_y_start - part_size.paren_y_end) * 24 / 2) + 1;
for(int y = 0; y < h; y++)
{
const int actual_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 2) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
info.current_x += 13;
}
else if(part.meta.special == Part::Specialty::Root)
{
if(part.meta.position == Part::Position::Start)
{
draw_paren(sqrt_sprites, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, &text_tint);
const int pixel_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4);
const int bar_x = info.get_x() + 10;
const int bar_w = (part_size.content_width - 2) * 13 + 10;
const int notch_x = bar_x + bar_w;
C2D_DrawRectSolid(bar_x, pixel_y, 0.125f, bar_w, 2, COLOR_BLACK);
C2D_DrawRectSolid(notch_x, pixel_y, 0.125f, 2, 10, COLOR_BLACK);
}
info.current_x += 13;
}
else if(part.meta.special == Part::Specialty::Conjugate)
{
if(part.meta.position == Part::Position::Start)
{
C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4), 0.125f, part_size.content_width * 13, 2, COLOR_BLACK);
}
}
else if(part.meta.special == Part::Specialty::Fraction)
{
if(part.meta.position == Part::Position::Start)
{
const auto& middle_size = part_sizes[part_size.associated];
const int max_width = std::max(middle_size.content_width, part_size.content_width);
C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) + 24 / 2 - 1, 0.0f, max_width * 13, 2.0f, COLOR_BLACK);
info.current_x += ((max_width - part_size.content_width) * 13)/2; // top align
}
else if(part.meta.position == Part::Position::Middle)
{
const int max_width = std::max(part_size.content_width, part_size.data);
info.current_x -= (part_size.data * 13); // top size
info.current_x -= ((max_width - part_size.data) * 13)/2; // top align
info.current_x += ((max_width - part_size.content_width) * 13)/2; // bottom align
}
else if(part.meta.position == Part::Position::End)
{
const auto& middle_size = part_sizes[part_size.associated];
const int max_width = std::max(middle_size.content_width, middle_size.data);
info.current_x -= (middle_size.content_width * 13); // bottom size
info.current_x -= ((max_width - middle_size.content_width) * 13)/2; // bottom align
info.current_x += max_width * 13; // full size
}
}
vertical_offset += (part_size.middle_change * 24) / 4;
max_vert = std::max(max_vert, vertical_offset);
min_vert = std::min(min_vert, vertical_offset);
}
current_idx = part.meta.next;
}
out.w = info.current_x;
out.min_y = min_vert - 24 / 2;
out.max_y = max_vert + 24 / 2;
part_sizes.clear();
}
Equation::RenderResult Equation::render_main(const int x, const int y, const int editing_part, const int editing_char, C2D_SpriteSheet sprites, PartPos* screen)
{
RenderResult out{0,0,0,-1,-1, false};
RenderInfo info{
0,
x, x + 320, y,
EQU_REGION_HEIGHT,
editing_part,
editing_char,
};
render_parts(parts, info, out, screen, sprites);
return out;
}
Equation::RenderResult Equation::render_memory(const int x, const int y, C2D_SpriteSheet sprites)
{
RenderResult out{0,0,0,-1,-1, false};
RenderInfo info{
0,
x, x + 400, y,
EQU_REGION_HEIGHT,
-1,
-1,
};
render_parts(parts, info, out, nullptr, sprites);
return out;
}
void Equation::optimize()
{
std::vector<Part> tmp;
tmp.push_back(std::move(parts[0]));
int prev_id = 0;
int next_id_parts = tmp.back().meta.next;
while(next_id_parts != -1)
{
int next_id_tmp = tmp.size();
tmp.back().meta.next = next_id_tmp;
tmp.push_back(std::move(parts[next_id_parts]));
next_id_parts = tmp.back().meta.next;
tmp.back().meta.before = prev_id;
prev_id = next_id_tmp;
}
parts = std::move(tmp);
}
std::pair<Number, bool> Equation::calculate(std::map<std::string, Number>& variables, int& error_part, int& error_position)
{
#define ERROR_AT(part, pos) { error_part = part; error_position = pos; return {}; }
struct Token {
enum class Type {
Number,
Variable,
Function,
Operator,
ParenOpen,
ParenClose,
};
std::string_view value;
int part, position;
Type type;
};
const auto base_tokens = [&, this]() -> std::vector<Token> {
std::vector<Token> toks;
int start = 0;
int len = 0;
int tmp_is_num = -1;
int current_idx = 0;
while(current_idx != -1)
{
const auto& p = parts[current_idx];
if(p.meta.special != Part::Specialty::None)
{
if(p.meta.special == Part::Specialty::TempParen)
{
ERROR_AT(p.meta.next, 0);
}
else if(p.meta.special == Part::Specialty::Absolute)
{
if(p.meta.position == Part::Position::Start)
{
toks.push_back(Token{"abs", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Root)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{"sqrt", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Conjugate)
{
if(p.meta.position == Part::Position::Start)
{
toks.push_back(Token{"conj", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Paren)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Exponent)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() >= 1)
{
if(const auto b = toks.back(); b.value == "e" && b.type == Token::Type::Variable)
{
toks.pop_back();
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{"exp", b.part, b.position, Token::Type::Function});
}
else
toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator});
}
else
toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Fraction)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else if(p.meta.position == Part::Position::Middle)
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
toks.push_back(Token{"/", p.meta.next, 0, Token::Type::Operator});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
}
else
{
int pos = 0;
const char* beg = p.value.c_str();
for(const char c : p.value)
{
if(('0' <= c && c <= '9') || c == '.')
{
if(tmp_is_num == 1)
{
++len;
}
else
{
if(len != 0)
{
if(toks.size() && toks.back().type == Token::Type::ParenClose)
{
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
start = pos;
len = 1;
tmp_is_num = 1;
}
}
else if(('a' <= c && c <= 'z') || c == 'P')
{
if(tmp_is_num == 0)
{
++len;
}
else
{
if(len != 0)
{
if(toks.size() && toks.back().type == Token::Type::ParenClose)
{
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
start = pos;
len = 1;
tmp_is_num = 0;
}
}
else
{
if(len != 0)
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, tmp_is_num ? Token::Type::Number : Token::Type::Variable});
}
start = 0;
len = 0;
tmp_is_num = -1;
toks.push_back(Token{{beg + pos, 1}, current_idx, pos, Token::Type::Operator});
}
++pos;
}
if(tmp_is_num == 0)
{
if(const auto& pn = parts[p.meta.next].meta; pn.position == Part::Position::Start && pn.special == Part::Specialty::Paren)
{
if(len == 1 || std::string_view{beg + start, size_t(len)} == "ans") // 1 letter names can only be variables
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
else
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Function});
}
}
else
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
}
}
else if(tmp_is_num == 1)
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number});
}
start = 0;
len = 0;
tmp_is_num = -1;
}
current_idx = p.meta.next;
}
return toks;
}();
if(base_tokens.empty()) return std::make_pair(Number{}, true);
const auto final_rpn = [&]() -> std::vector<const Token*> {
std::vector<const Token*> postfix;
std::vector<const Token*> opstack;
const auto get_prec = [](std::string_view op) -> int {
switch(op.front())
{
case '^': return 4;
case '*': return 3;
case '/': return 3;
case '+': return 2;
case '-': return 2;
case '>': return 1;
default: return 0;
}
};
const auto get_assoc = [](std::string_view op) -> bool {
return op.front() == '^';
};
for(const Token& tok : base_tokens)
{
if(tok.type == Token::Type::Variable || tok.type == Token::Type::Number)
{
postfix.push_back(&tok);
}
else if(tok.type == Token::Type::ParenOpen)
{
opstack.push_back(&tok);
}
else if(tok.type == Token::Type::ParenClose)
{
while(opstack.size() && opstack.back()->type != Token::Type::ParenOpen)
{
postfix.push_back(opstack.back());
opstack.pop_back();
}
opstack.pop_back(); // open paren (mismatch cannot happen)
}
else if(tok.type == Token::Type::Function)
{
opstack.push_back(&tok);
}
else if(tok.type == Token::Type::Operator)
{
auto prec = get_prec(tok.value);
while(opstack.size())
{
if(const Token* op = opstack.back();
op->type != Token::Type::ParenOpen && (
op->type == Token::Type::Function ||
get_prec(op->value) >= prec ||
(get_prec(op->value) == prec && get_assoc(op->value))
)
)
{
postfix.push_back(op);
opstack.pop_back();
}
else
break;
}
opstack.push_back(&tok);
}
}
while(opstack.size())
{
postfix.push_back(opstack.back());
opstack.pop_back();
}
return postfix;
}();
if(final_rpn.empty()) std::make_pair(Number{}, true);
#undef ERROR_AT
#define ERROR_AT(part, pos) { error_part = part; error_position = pos; return std::make_pair(Number{}, true); }
struct Value {
Number val;
std::string_view assoc_variable;
Value(std::string_view v) : val(v) { }
Value(const Number& v) : val(v) { }
Value(const Number& v, std::string_view a) : val(v), assoc_variable(a) { }
};
const auto get_var = [&](std::string_view name) -> Value {
if(auto it = variables.find(std::string(name)); it != variables.end())
{
return {it->second, name};
}
return {{}, name};
};
#define MK_WRAPPER_FN(fname, fn) {#fname, [](std::vector<Value>& vals) { \
vals.back() = Value(std::fn(vals.back().val.value)); \
}}
#define MK_WRAPPER(fname) MK_WRAPPER_FN(fname, fname)
const std::map<std::string_view, void(*)(std::vector<Value>&)> function_handlers{
MK_WRAPPER(abs),
MK_WRAPPER(sqrt),
MK_WRAPPER(conj),
MK_WRAPPER(cos),
MK_WRAPPER(sin),
MK_WRAPPER(tan),
MK_WRAPPER(acos),
MK_WRAPPER(asin),
MK_WRAPPER(atan),
MK_WRAPPER(cosh),
MK_WRAPPER(sinh),
MK_WRAPPER(tanh),
MK_WRAPPER(acosh),
MK_WRAPPER(asinh),
MK_WRAPPER(atanh),
MK_WRAPPER(exp),
MK_WRAPPER_FN(ln, log),
MK_WRAPPER_FN(log, log10),
};
std::vector<Value> value_stack;
for(const Token* tok : final_rpn)
{
if(tok->type == Token::Type::Number)
{
if(tok->value.front() == '.' || tok->value.back() == '.')
{
ERROR_AT(tok->part, tok->position);
}
else
{
value_stack.emplace_back(tok->value);
}
}
else if(tok->type == Token::Type::Variable)
{
if(tok->value == "P")
{
value_stack.emplace_back(PI_VAL);
}
else if(tok->value == "e")
{
value_stack.emplace_back(E_VAL);
}
else if(tok->value == "i")
{
value_stack.emplace_back(I_VAL);
}
else
{
value_stack.push_back(get_var(tok->value));
}
}
else if(tok->type == Token::Type::Operator)
{
#define OP_CASE(op) case #op[0] : { \
const Value left = value_stack.back(); \
value_stack.pop_back(); \
const Value right = value_stack.back(); \
value_stack.pop_back(); \
value_stack.emplace_back(right.val.value op left.val.value); \
} break;
switch(tok->value.front())
{
OP_CASE(+)
OP_CASE(-)
OP_CASE(*)
OP_CASE(/)
case '^':
{
const Value left = value_stack.back();
value_stack.pop_back();
const Value right = value_stack.back();
value_stack.pop_back();
value_stack.emplace_back(std::pow(right.val.value, left.val.value));
}
break;
case '>':
{
const Value left = value_stack.back();
value_stack.pop_back();
const Value right = value_stack.back();
value_stack.pop_back();
variables.insert_or_assign(std::string(left.assoc_variable), right.val.value);
value_stack.push_back(right);
}
break;
}
}
else if(tok->type == Token::Type::Function)
{
if(auto it = function_handlers.find(tok->value); it != function_handlers.end())
{
it->second(value_stack);
}
}
}
return {value_stack.back().val, false};
#undef ERROR_AT
}
int Equation::set_special(const int current_part_id, const int at_position, const Part::Specialty special)
{
if(static_cast<size_t>(at_position) != parts[current_part_id].value.size()) return 0;
const int next_id = parts[current_part_id].meta.next;
if(next_id == -1) return 0;
auto& p = parts[next_id];
if(p.meta.special != Part::Specialty::Paren || p.meta.position != Part::Position::Start) return 0;
p.meta.special = special;
parts[p.meta.assoc].meta.special = special;
return 1;
}
void Equation::find_matching_tmp_paren(const int original_pos)
{
using HelperType = int(*)(Equation&, const int);
const auto do_find = [](Equation& e, const int original_pos, int inc_on_start, HelperType get_following) {
int current_count = 0;
int prev_pos = original_pos;
const Part::Position searching_for = !e.parts[original_pos].meta.position;
int pos = get_following(e, prev_pos);
while(current_count >= 0 /* && pos != -1 */) // second test redundant, since we have the Equation start and end chunks
{
if(current_count == 0 && e.parts[pos].meta.special == Part::Specialty::TempParen && e.parts[pos].meta.position == searching_for)
{
e.parts[pos].meta.special = Part::Specialty::Paren;
e.parts[pos].meta.assoc = original_pos;
e.parts[original_pos].meta.special = Part::Specialty::Paren;
e.parts[original_pos].meta.assoc = pos;
break;
}
if(check_pos_is(e.parts[pos].meta.position, Part::Position::End) && e.parts[pos].meta.special != Part::Specialty::TempParen)
{
current_count -= inc_on_start;
}
if(check_pos_is(e.parts[pos].meta.position, Part::Position::Start) && e.parts[pos].meta.special != Part::Specialty::TempParen)
{
current_count += inc_on_start;
}
prev_pos = pos;
pos = get_following(e, pos);
}
};
if(parts[original_pos].meta.position == Part::Position::Start)
{
// go forward
do_find(*this, original_pos, +1,
[](Equation& e, const int pos) -> int {
return e.parts[pos].meta.next;
}
);
}
else if(parts[original_pos].meta.position == Part::Position::End)
{
// go backwards
do_find(*this, original_pos, -1,
[](Equation& e, const int pos) -> int {
return e.parts[pos].meta.before;
}
);
}
}
std::pair<bool, bool> Equation::add_part_at(int& current_part_id, int& at_position, const Part::Specialty special, const Part::Position position, const int assoc)
{
std::string before_val = parts[current_part_id].value.substr(0, at_position);
std::string after_val = parts[current_part_id].value.substr(at_position);
const bool after_val_empty = after_val.empty();
const bool before_val_empty = before_val.empty();
const int new_part_id = parts.size();
if(after_val_empty)
{
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part_id;
new_part.meta.next = current_part.meta.next;
parts[new_part.meta.next].meta.before = new_part_id;
current_part.meta.next = new_part_id;
}
else if(before_val_empty)
{
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part.meta.before;
new_part.meta.next = current_part_id;
parts[new_part.meta.before].meta.next = new_part_id;
current_part.meta.before = new_part_id;
}
else
{
parts.emplace_back();
const int after_part_id = parts.size();
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
auto& after_part = parts[after_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part_id;
new_part.meta.next = after_part_id;
after_part.meta.before = new_part_id;
after_part.meta.next = current_part.meta.next;
current_part.meta.next = new_part_id;
current_part.value = std::move(before_val);
after_part.value = std::move(after_val);
}
current_part_id = new_part_id;
at_position = 0;
const auto& new_part = parts[new_part_id];
return {parts[new_part.meta.before].meta.special == Part::Specialty::None, parts[new_part.meta.next].meta.special == Part::Specialty::None};
}
bool Equation::remove_at(int& current_part_id, int& at_position)
{
if(at_position == 0)
{
const auto merge_single_part = [this](Part::Meta single_meta) -> std::pair<int, int> {
const int before_part_start_id = single_meta.before;
const int after_part_start_id = single_meta.next;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
/*
* equ_start -> A -> single -> B -> equ_end
* append B to A
* make A's next into B's next
* make B's next's before into A
* equ_start -> AB -> equ_end
*/
Part::Meta after_start_meta = parts[after_part_start_id].meta;
parts[before_part_start_id].value.append(parts[after_part_start_id].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
return {part_id, at_char};
};
const auto merge_parts = [this](Part::Meta start_meta, Part::Meta end_meta) -> std::pair<int, int> {
const int before_part_start_id = start_meta.before;
const int after_part_start_id = start_meta.next;
const int before_part_end_id = end_meta.before;
const int after_part_end_id = end_meta.next;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
/*
* if after_part_start_id != before_part_end_id:
* equ_start -> A -> start -> B -> ... -> C -> end -> D -> equ_end
* append D to C
* make C's next into D's next
* make C's new next's before into C
* equ_start -> A -> start -> B -> ... -> CD -> equ_end
* append B to A
* make A's next into B's next
* make CD's next's before into C
* equ_start -> A -> start -> B -> ... -> CD -> equ_end
*/
/*
* if after_part_start_id == before_part_end_id:
* equ_start -> A -> start -> B -> end -> C -> equ_end
* append C to B
* make B's next into C's next
* make B's new next's before into B
* equ_start -> A -> start -> BC -> equ_end
* append BC to A
* make A's next into BC's next
* make A's next's before into A
* equ_start -> ABC -> equ_end
*/
Part::Meta after_end_meta = parts[after_part_end_id].meta;
parts[before_part_end_id].value.append(parts[after_part_end_id].value);
parts[before_part_end_id].meta.next = after_end_meta.next;
parts[after_end_meta.next].meta.before = before_part_end_id;
Part::Meta after_start_meta = parts[after_part_start_id].meta;
parts[before_part_start_id].value.append(parts[after_part_start_id].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
return {part_id, at_char};
};
Part::Meta start_meta = parts[parts[current_part_id].meta.before].meta; // select the special chunk before the writing area we're in
// Don't allow deleting the first chunk or chunks we're after the end of. chunks have to be deleted from the front of the inside
if((!(start_meta.special == Part::Specialty::Paren || start_meta.special == Part::Specialty::TempParen) && check_pos_is(start_meta.position, Part::Position::End)) || start_meta.special == Part::Specialty::Equation) return false;
if(start_meta.special == Part::Specialty::Fraction)
{
Part::Meta middle_meta = parts[start_meta.assoc].meta;
Part::Meta end_meta = parts[middle_meta.assoc].meta;
merge_parts(middle_meta, end_meta);
const int before_part_start_id = start_meta.before;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
Part::Meta after_start_meta = parts[start_meta.next].meta;
parts[before_part_start_id].value.append(parts[start_meta.next].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
current_part_id = part_id;
at_position = at_char;
return true;
}
else if(start_meta.special == Part::Specialty::Paren)
{
parts[start_meta.assoc].meta.assoc = -1;
parts[start_meta.assoc].meta.special = Part::Specialty::TempParen;
std::tie(current_part_id, at_position) = merge_single_part(start_meta);
return true;
}
else if(start_meta.special == Part::Specialty::TempParen)
{
std::tie(current_part_id, at_position) = merge_single_part(start_meta);
return true;
}
else
{
std::tie(current_part_id, at_position) = merge_parts(start_meta, parts[start_meta.assoc].meta);
return true;
}
}
else
{
at_position -= 1;
parts[current_part_id].value.erase(at_position, 1);
return true;
}
}
bool Equation::left_of(int& current_part_id, int& at_position)
{
if(at_position != 0)
{
at_position--;
return true;
}
if(parts[parts[current_part_id].meta.before].meta.special != Part::Specialty::Equation)
{
do {
current_part_id = parts[current_part_id].meta.before;
} while(parts[current_part_id].meta.special != Part::Specialty::None);
at_position = parts[current_part_id].value.size();
return true;
}
return false;
}
bool Equation::right_of(int& current_part_id, int& at_position)
{
if(static_cast<size_t>(at_position) != parts[current_part_id].value.size())
{
at_position++;
return true;
}
if(parts[parts[current_part_id].meta.next].meta.special != Part::Specialty::Equation)
{
do {
current_part_id = parts[current_part_id].meta.next;
} while(parts[current_part_id].meta.special != Part::Specialty::None);
at_position = 0;
return true;
}
return false;
}
| 38.83914
| 236
| 0.492881
|
LiquidFenrir
|
01e39ce818b54c879e1b196b68ac199bd3856752
| 2,133
|
cpp
|
C++
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#pragma once
#include "Frustum.hh"
#include <glm/glm.hpp>
namespace AGE
{
void Frustum::buildPlanes()
{
_planes[PLANE_NEAR].setCoefficients(
_viewProj[0][2] + _viewProj[0][3],
_viewProj[1][2] + _viewProj[1][3],
_viewProj[2][2] + _viewProj[2][3],
_viewProj[3][2] + _viewProj[3][3]);
_planes[PLANE_FAR].setCoefficients(
-_viewProj[0][2] + _viewProj[0][3],
-_viewProj[1][2] + _viewProj[1][3],
-_viewProj[2][2] + _viewProj[2][3],
-_viewProj[3][2] + _viewProj[3][3]);
_planes[PLANE_BOTTOM].setCoefficients(
_viewProj[0][1] + _viewProj[0][3],
_viewProj[1][1] + _viewProj[1][3],
_viewProj[2][1] + _viewProj[2][3],
_viewProj[3][1] + _viewProj[3][3]);
_planes[PLANE_TOP].setCoefficients(
-_viewProj[0][1] + _viewProj[0][3],
-_viewProj[1][1] + _viewProj[1][3],
-_viewProj[2][1] + _viewProj[2][3],
-_viewProj[3][1] + _viewProj[3][3]);
_planes[PLANE_LEFT].setCoefficients(
_viewProj[0][0] + _viewProj[0][3],
_viewProj[1][0] + _viewProj[1][3],
_viewProj[2][0] + _viewProj[2][3],
_viewProj[3][0] + _viewProj[3][3]);
_planes[PLANE_RIGHT].setCoefficients(
-_viewProj[0][0] + _viewProj[0][3],
-_viewProj[1][0] + _viewProj[1][3],
-_viewProj[2][0] + _viewProj[2][3],
-_viewProj[3][0] + _viewProj[3][3]);
}
void Frustum::setMatrix(const glm::mat4 &viewProj)
{
if (_viewProj != viewProj)
{
_viewProj = viewProj;
buildPlanes();
}
}
bool Frustum::checkCollision(AABoundingBox const &aabb) const
{
for (int i = 0; i < PLANE_END; i++)
{
if (_planes[i].getPointDistance(aabb.getPositivePoint(_planes[i].getNormal())) < 0)
return (false);
}
return (true);
}
bool Frustum::checkCollision(Sphere const &sphere) const
{
assert(!"Not implemented");
return (false);
}
bool Frustum::checkCollision(glm::vec4 const &sphere) const
{
for (int i = 0; i < PLANE_END; i++)
{
float dist = _planes[i].getPointDistance(glm::vec3(sphere));
if (dist + sphere.w < 0)
return (false);
}
return (true);
}
bool Frustum::checkCollision(Frustum const &frustum) const
{
assert(!"Not implemented");
return (false);
}
}
| 23.966292
| 86
| 0.631036
|
Another-Game-Engine
|
01e7355d0093d04bd17cd74177abaa99133bd59e
| 20,259
|
cpp
|
C++
|
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | 3
|
2018-02-26T19:53:10.000Z
|
2020-01-16T14:30:02.000Z
|
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | null | null | null |
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stdlib.h>
#include <stdio.h>
#include "setupglew.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glxew.h>
//#include <GL/glx.h> //for Nvida Framelock code
#include <GL/glut.h>
#include "JSharedMemory.h"
#include "JSequencer.h"
#include "JDisplayState.h"
#include "RIP.h"
#include "UI.h"
#include "flyRender.h"
#include "holoren.h"
#include <sys/time.h>
//headers for 3d mouse
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include "xdrvlib.h"
#include <stdio.h> /* for printf and NULL */
#include <stdlib.h> /* for exit */
#include <string.h>
#include <GL/gl.h> // The GL Header File
#include <GL/glut.h> // The GL Utility Toolkit (Glut) Header
//#include <GL/glx.h>
//end 3d mouse headers
static HoloRenderParams *holoRenParams = NULL;
static HoloRenderParams *holoRenParams2 = NULL;
static RIPHologram *ripParams = NULL;
static RIPHologram *ripParams2 = NULL;
//static int attributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None }; //JB: The only use of this was if'd out of Tyler's old code.
static Display *dpy;
//static Window win;
//static XVisualInfo *vi; //not used
//static XSetWindowAttributes swa; //not used
static GLXContext cx;
static JDisplayState statecopy;
static JSharedMemory *sharedstate;
float MASTER_GAIN = 0.7; //this is overridden by the external UI
double MagellanSensitivity = 1.0;
Display *dsp;
Window root, drw;
XEvent report;
MagellanFloatEvent MagellanEvent;
int fringeToUse = 0;
bool freeSpin = false; // should object be sipinning for demo?
static bool ismaster = false; // is this instance the one that has keyboard/mouse? For now, pick based on screen number & make sure 0 is opened last.
static JSharedMemory* sharedFilename;
static JSharedMemory* sharedDepthA;
static JSharedMemory* sharedDepthB;
static JSequencer* sequencer = NULL;
//#define FILENAME_KEY 6624
//#define DEPTH_A_KEY 6625
//#define DEPTH_B_KEY 6626
void spaceball()
{
if(!dsp) return;
XEvent report;
report.type = 0;
if(XPending(dsp) <= 0) return;
XNextEvent( dsp, &report ); //BLOCKING. BOO. Hopefully checking for pending events above keeps this from blocking
if (!XCheckTypedEvent(dsp, ClientMessage, &report))
{
//no event
return;
}
switch( report.type )
{
case ClientMessage :
switch( MagellanTranslateEvent( dsp, &report, &MagellanEvent, 1.0, 1.0 ) )
{
case MagellanInputMotionEvent :
MagellanRemoveMotionEvents( dsp );
printf(
"x=%+5.0lf y=%+5.0lf z=%+5.0lf a=%+5.0lf b=%+5.0lf c=%+5.0lf \n",
MagellanEvent.MagellanData[ MagellanX ],
MagellanEvent.MagellanData[ MagellanY ],
MagellanEvent.MagellanData[ MagellanZ ],
MagellanEvent.MagellanData[ MagellanA ],
MagellanEvent.MagellanData[ MagellanB ],
MagellanEvent.MagellanData[ MagellanC ] );
ripParams->m_render->motion(MagellanEvent.MagellanData[ MagellanX ], -MagellanEvent.MagellanData[ MagellanZ ]);
ripParams->m_render->spin(MagellanEvent.MagellanData[ MagellanA ]/100.0, MagellanEvent.MagellanData[ MagellanB ]/100.0);
// XClearWindow( drw, drw );
// XDrawString( drw, drw, wingc, 10,40,
//MagellanBuffer, (int)strlen(MagellanBuffer) );
// XFlush( display );
//tz= MagellanEvent.MagellanData[ MagellanZ];
break;
switch( MagellanEvent.MagellanButton )
{
case 5:
MagellanSensitivity = MagellanSensitivity <= 1.0/32.0 ? 1.0/32.0 : MagellanSensitivity/2.0; break;
case 6:
MagellanSensitivity = MagellanSensitivity >= 32.0 ? 32.0 : MagellanSensitivity*2.0; break;
}
default : // another ClientMessage event
break;
};
break;
};
}
void loadModelIfChanged(char* newname)
{
if(strncmp(newname, ripParams2->m_render->loadedFile, 1024))
{
ripParams2->m_render->config(newname);
ripParams2->m_render->init();
//load the new configuration!
//TODO: verify that this doesn't blow anything up.
}
}
void display(void)
{
struct timeval tp;
struct timezone tz;
//uncomment to restore spaceball rotation (flaky?)
//spaceball();
//JB: window gets reset somehow. Let's try fixing before we draw
//if ((holoRenParams->m_framebufferNumber % 2) == 0) {
// glutPositionWindow(0,hit);
//}
//glutReshapeWindow(wid,hit);
#ifdef SCREEN_SIZE_DIAGNOSTICS
//Some JB Diagnostics:
{
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("At top of display function,\n");
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
}
#endif
#ifdef XSCREENDUMP
static int framect = 0;
system("xwd -display localhost:0.0 -root -screen -silent | xwdtopnm 2>/dev/null | pnmtopng > ~/screendump.png");
printf("dumped screen to screendump.png\n");
if (framect++ == 5) exit(0);
#endif
//**** get current state from shared memory
//get state from UI & update model
#ifndef IGNORE_GUI
sharedstate->getDataCopy(&statecopy);
MASTER_GAIN = statecopy.gain;
if(ripParams)
{
ripParams->m_render->models->orient->rotate[0] = statecopy.xrot;
ripParams->m_render->models->orient->rotate[1] = statecopy.yrot;
ripParams->m_render->models->orient->rotate[2] = statecopy.zrot;
ripParams->m_render->models->orient->translate[0] = statecopy.xpos;
ripParams->m_render->models->orient->translate[1] = statecopy.ypos;
ripParams->m_render->models->orient->translate[2] = statecopy.zpos;
if(ripParams->m_flatrender != statecopy.rendermode1)
{
ripParams->m_flatrender = statecopy.rendermode1;
if(ripParams->m_flatrender == 0) //switch to RIP Method
{
ripParams->m_projectionPlaneDist = RIP_PROJ_PLANE;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
else //switch to planar method
{
ripParams->m_projectionPlaneDist = statecopy.flatdepth1;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
}
if(ripParams->m_flatrender && (statecopy.flatdepth1 != ripParams->m_projectionPlaneDist))
{
ripParams->m_projectionPlaneDist = statecopy.flatdepth1;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
}
if(ripParams2)
{
ripParams2->m_render->models->orient->rotate[0] = statecopy.xrot;
ripParams2->m_render->models->orient->rotate[1] = statecopy.yrot;
ripParams2->m_render->models->orient->rotate[2] = statecopy.zrot;
//ripParams2->m_render->models->orient->translate[0] = statecopy.xpos;
//ripParams2->m_render->models->orient->translate[1] = statecopy.ypos;
//ripParams2->m_render->models->orient->translate[2] = statecopy.zpos;
if(ripParams2->m_flatrender != statecopy.rendermode2)
{
ripParams2->m_flatrender = statecopy.rendermode2;
if(ripParams2->m_flatrender == 0) //switch to RIP Method
{
ripParams2->m_projectionPlaneDist = RIP_PROJ_PLANE;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
else //switch to planar method
{
ripParams2->m_projectionPlaneDist = statecopy.flatdepth2;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
}
if(ripParams2->m_flatrender && (statecopy.flatdepth2 != ripParams2->m_projectionPlaneDist))
{
ripParams2->m_projectionPlaneDist = statecopy.flatdepth2;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
}
#endif
/*char newname[1024];
if(sharedFilename->getDataCopyIfUnlocked(newname))
{
loadModelIfChanged(newname);
}
float newdepthA;
float newdepthB;
sharedDepthA->getDataCopyIfUnlocked(&newdepthA);
if(newdepthA != ripParams->m_projectionPlaneDist)
{
ripParams->m_projectionPlaneDist = newdepthA;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
sharedDepthB->getDataCopyIfUnlocked(&newdepthB);
if(newdepthB != ripParams2->m_projectionPlaneDist)
{
ripParams2->m_projectionPlaneDist = newdepthB;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
*/
//**** render
//black the color buffer
glClearColor(0.0,0.0,0.0,0.0);
glClear (GL_COLOR_BUFFER_BIT);
sequencer->update();
if(ripParams2 != NULL)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
ripParams2->DisplayRIPHologramSingleFramebuffer(holoRenParams2);
glPopAttrib();
}
glPushAttrib(GL_ALL_ATTRIB_BITS);
// calls RIPHologram::DisplayRIPHologramSingleFramebuffer (in RIP.cpp)
ripParams->DisplayRIPHologramSingleFramebuffer(holoRenParams);
glPopAttrib();
glFlush();
glutSwapBuffers();
//JB: Make it move
#ifdef SPIN_OBJECT_HACK
if(freeSpin)
{
if(ripParams) ripParams->m_render->spin(2, 0);
if(ripParams2) ripParams2->m_render->spin(-1.5,0);
}
#endif
//warp pointer back to center of screen if it isn't already there.
int cx, cy;
#ifndef LOCKED_UI
cx = glutGet(GLUT_WINDOW_WIDTH)/2;
cy = glutGet(GLUT_WINDOW_HEIGHT)/2;
if(ripParams->m_render->mLX != cx || ripParams->m_render->mLY != cy)
{
glutWarpPointer(cx,cy);
ripParams->m_render->mLX = cx;
ripParams->m_render->mLY = cy;
}
#endif
glutPostRedisplay(); //JB: This causes glut to continue to repeatedly execute display()
#ifdef TIMING_DIAGNOSTICS
{
gettimeofday(&tp, &tz);
printf("time now is: %ld sec %ld usec \n", tp.tv_sec, tp.tv_usec);
printf("time now is: (tp.tv_sec*100000)/100000)\n");
}
#endif
#ifdef SCREEN_SIZE_DIAGNOSTICS
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("After buffer swap,\n");
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
#endif
#ifdef WRITE_FB_TO_FILE
unsigned char *pic;
unsigned char *bptr;
FILE *fp;
int allocfail = 0;
printf("attempting to write framebuffer to file");
if ((pic = (unsigned char*)malloc(screenWidth*screenHeight*3 * sizeof(unsigned char))) == NULL) {
printf("couldn't allocate memory for framebuffer dump.\n");
allocfail = 1;
}
if ( !allocfail) {
char fname[255];
glReadBuffer(GL_FRONT);
bptr = pic;
glReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pic);
printf("saving %dx%dx3 to file...\n", screenWidth,screenHeight);
sprintf(fname, "FBcontents%d.raw", holoRenParams->m_framebufferNumber);
if ( (fp = fopen (fname, "w")) == NULL) {
printf("failure opening file.\n");
exit(0);
}
else {
if (fwrite (pic, 1, 3*screenWidth*screenHeight, fp) != screenWidth*screenHeight*3) {
printf("failure writing file.\n");
//exit(0);
}
fclose (fp);
}
free (pic);
}
exit(1);
#endif
}
//called by GLUT on mouseup and mousedown
void mouse(int button, int state, int x, int y)
{
// calls holoConf::mouse which sets cursor state and mousebutton state
ripParams->m_render->mouse(button, state, x, y);
}
//called by GLUT on mouse move (buttons up only)
//keep mouse at middle of screen
void passiveMotion(int x, int y)
{
//TODO: check for recursive events? Dead zone?
#ifndef LOCKED_UI
glutWarpPointer(holoRenParams->m_xRes/2,holoRenParams->m_yRes);
#endif
}
//called by GLUT on drag
void motion(int x, int y)
{
// calls holoConf::motion() which appears to
// translate the scene based on mouse movement.
ripParams->m_render->motion(x, y);
}
void keyboard(unsigned char key, int x, int y) {
printf("got key \"%c\" on screen %d\n", key, holoRenParams->m_framebufferNumber);
sequencer->keypress(key);
#ifndef LOCKED_UI
switch(key) {
case 'q':
case 'Q':
exit(0);
break;
case 'a':
fringeToUse ++;
if(fringeToUse >= NUM_PRECOMPUTED_FRINGES)
fringeToUse = NUM_PRECOMPUTED_FRINGES-1;
printf("using fringe %d\n", fringeToUse);
ripParams->m_fringeToUse = fringeToUse;
glutPostRedisplay();
break;
case 'A':
fringeToUse--;
if(fringeToUse < 0)
fringeToUse = 0;
printf("using fringe %d\n", fringeToUse);
ripParams->m_fringeToUse = fringeToUse;
glutPostRedisplay();
break;
case ' ':
freeSpin = !freeSpin;
glutPostRedisplay();
break;
case 'd':
ripParams->m_projectionPlaneDist += 1.0;
printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist);
ripParams->recomputeGeometry(ripParams->m_holorenparams);
break;
case 'D':
ripParams->m_projectionPlaneDist -= 1.0;
printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist);
ripParams->recomputeGeometry(ripParams->m_holorenparams);
break;
case 'l' :
//if(ismaster)
{
char fname[1024] = "/models/letters/SLOAN/C.xml";
sharedFilename->write(fname);
loadModelIfChanged(fname);
}
break;
case 'k' :
//if(ismaster)
{
char fname[1024] = "/models/letters/SLOAN/K.xml";
sharedFilename->write(fname);
loadModelIfChanged(fname);
}
break;
};
// calls holoConf::keyboard() which adds other commands:
// + = +ztranlate
// - = -ztranslate
// 4 = -xtranslate
// 6 = +xtranslate
// 8 = -ytranslate
// 2 = +ytranslate
ripParams->m_render->keyboard(key, x, y);
#endif
}
//JB: for testing on desktop display:
void reshape(int w, int h) {
glViewport(0,0,(GLsizei)w, (GLsizei)h);
glutPostRedisplay();
}
// setup UI
// uses structs holoRenParams.
void InitGL(int &argc, char **&argv, HoloRenderParams *hrP, RIPHologram *ripP, HoloRenderParams *hrP2, RIPHologram *ripP2)
{
holoRenParams = hrP;
ripParams = ripP;
holoRenParams2 = hrP2;
ripParams2 = ripP2;
printf("initializing GL\n");
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL | GLUT_ACCUM);
//instance on framebuffer 0 gets to interact with keyboard & send events to other instances.
if(holoRenParams->m_framebufferNumber == 0)
{
ismaster = true;
}
else
{
ismaster = false;
}
//state for slaving to separate UI
sharedstate = new JSharedMemory(sizeof(JDisplayState),ALL_STATE_KEY);
sharedstate->getDataCopy(&statecopy);
/*
sharedFilename = new JSharedMemory(1024,FILENAME_KEY);
sharedDepthA = new JSharedMemory(sizeof(float),DEPTH_A_KEY);
sharedDepthB = new JSharedMemory(sizeof(float),DEPTH_B_KEY);
*/
/*
char f[1024] = "/models/blankframe.xml";
sharedFilename->write(f);
//initalize z-distance to first & second hologram.
float pdA = 10;
float pdB = 128;
sharedDepthA->write(&pdA);
sharedDepthB->write(&pdB);
*/
//TODO: get subject ID!
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
//glutInitDisplayString("xvisual=250");//doesn't seem to work
//glutInitDisplayString("depth=>1 rgba>1");//doesn't seem to work
// set up window size to be (these are hardcoded in RIP.h) 2048x(2*1780)
//(2 vertically stacked "framebuffers" worth per window)
glutInitWindowSize(holoRenParams->m_xRes,holoRenParams->m_yRes*2);
//glutInitWindowSize(2048,holoRenParams->m_yRes*2);
// TODO: Update block comment for version 3.0.
// Bottom line: each PC has 2 framebuffers, one window.
// PCnumber = floor(framebufferNumber/2) has one window, with framebuffer
// number PCnumber*2+1 on top and PCnumber*2 on bottom half of screen.
// previously, we had one window per framebuffer, but the two windows on the
// same video card liked to fight.
// WJP's note from pre-3.0 version:
// In holocomputation, we assume that hololines are apportioned
// in logical order in FB0, FB1, FB2, FB3, FB4 and FB5, and comments
// throughout the code reflect this. FB0 gets hololines 0,1,2, 18,19,20,...
// and FB1 gets hololines 3,4,5, 21,22,23... and so on. And the
// scripts: /home/holovideox/local/framebuffer1 and framebuffer2 return
// 0 and 1 on holovideo1, 2 and 3 on holovideo2, and 4 and 5 on holovideo3
// respectively.
// Here's what we've learned about the way framebuffers on
// holovideo1, holovideo2, holovideo3 map to holoLines.
// on holovideo1, framebufferNumber 1 has the top 3 hololines.
// framebufferNumber 0 has the next 3 hololines.
// on holovideo2, framebufferNumber 3 has the next 3 hololines.
// framebufferNumber 2 has the next three lines.
// on holovideo3, framebufferNumber 5 has the next three lines, and
// framebufferNumber 4 has the bottom three lines.
// our software assumes that lines are arranged from top to bottom
// in framebufferNumber 0 - 5. So, we swap the position of the output
// windows for FBs (0and1) (2and3) (4and5) in UI.cpp,
// so that FB0's output window is at (0,m_viewYRes) and FB1's is at (0,0).
// I hope this is understandable.
//JB removed for version 3.0
//if((hrP->m_framebufferNumber % 2) == 1)
//{
glutInitWindowPosition(0, 0);
//} else {
// glutInitWindowPosition(0, hrP->m_yRes);
//}
// specifies display, keyboard, mouse, motion callacks,
// configures window and turns OFF the cursor!
int winnum = glutCreateWindow("HoloLoadExec"); //title is hint to window manager to not decorate window
GLenum glewerr = glewInit();
if(GLEW_OK != glewerr)
{
printf("Glew Init Failed! (%s) \n", glewGetErrorString(glewerr));
}
glutDisplayFunc(display);
GLuint numgroups,numbars;
int ret;
#ifdef USE_HARDWARE_GENLOCK
//Code block to turn on buffer swap syncronization using genlock hardware
ret = glXQueryMaxSwapGroupsNV(dsp,drw,&numgroups, &numbars);
if (!ret) printf("Couldn't query swap group info\n");
ret = glXJoinSwapGroupNV(dsp,drw,1);//Make our drawable part of framelock group zero
if (!ret) printf("Failed to start swap group\n");
ret = glXBindSwapBarrierNV(dsp,1,1);//make framelock group zero part of barrier zero
if (!ret) printf("Failed to start swap barrier\n");
printf("System supports %d groups and %d barriers\n", numgroups, numbars);
#endif
#ifdef WORKSTATION_DEBUG
glutReshapeFunc(reshape);
#endif
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutPassiveMotionFunc(passiveMotion);
//glutFullScreen();
glutSetCursor(GLUT_CURSOR_NONE);
//TODO: This will probably need to change with three wimultaneous windows...
glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH)/2, glutGet(GLUT_WINDOW_HEIGHT)/2); // move mouse to center of display
//Set up Spaceball/SpaceNavigator support
GLXDrawable drw = glXGetCurrentDrawable();
dsp = glXGetCurrentDisplay();
if ( !MagellanInit( dsp, drw ) )
{
fprintf( stderr, "Can't find the spaceball driver. try running:\n sudo /etc/3DxWare/daemon/3dxsrv -d usb \n" );
}
//testing GLX capabilities...
int vid = glutGet(GLUT_WINDOW_FORMAT_ID);
printf("Using openGL visual #%d. See visualinfo for more information\n", vid);
XVisualInfo* newVisual = NULL;
int visattrib[] = {GLX_RGBA, GLX_RED_SIZE, 64};
newVisual = glXChooseVisual(dsp, 0, visattrib);
sequencer = new JSequencer("HoloLayerLetter", 0, holoRenParams->m_framebufferNumber, hrP, ripP, hrP2, ripP2);
//Some JB Diagnostics:
#ifdef SCREEN_SIZE_DIAGNOSTICS
{
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("Before starting main loop,\n");
printf("glutCreateWindow returned window ID %d\n", winnum);
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
printf("swapped buffers: you should SEE something on the display now...\n");
}
#endif
}
//I don't think this ever gets called (JB);
void CloseGL()
{
// glXDestroyContext(dpy, cx);
// XDestroyWindow(dpy, win);
// XCloseDisplay(dpy);
}
| 27.982044
| 149
| 0.710203
|
itsermo
|
543527a510cb32554b395028916e54e8d894c42f
| 775
|
cpp
|
C++
|
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
BaderEddineOuaich/xtd
|
6f28634c7949a541d183879d2de18d824ec3c8b1
|
[
"MIT"
] | 1
|
2022-02-25T16:53:06.000Z
|
2022-02-25T16:53:06.000Z
|
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
leanid/xtd
|
2e1ea6537218788ca08901faf8915d4100990b53
|
[
"MIT"
] | null | null | null |
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
leanid/xtd
|
2e1ea6537218788ca08901faf8915d4100990b53
|
[
"MIT"
] | null | null | null |
#include "../../../include/xtd/reflection/assembly_title_attribute.h"
using namespace std;
using namespace xtd;
using namespace xtd::reflection;
assembly_title_attribute::assembly_title_attribute(const ustring& title) : title_(title) {
}
assembly_title_attribute::assembly_title_attribute(const ustring& title, const object& executing_assembly) : title_(title) {
__assembly_title_attribute__() = make_shared<xtd::reflection::assembly_title_attribute>(title);
}
shared_ptr<object> assembly_title_attribute::get_type_id() const {
return xtd::guid::new_guid().memberwise_clone<xtd::guid>();
}
shared_ptr<xtd::reflection::assembly_title_attribute>& __assembly_title_attribute__() {
static shared_ptr<xtd::reflection::assembly_title_attribute> title;
return title;
}
| 35.227273
| 124
| 0.79871
|
BaderEddineOuaich
|
543567ad7d0c1ef880e252e10dc15d03a3e809d8
| 29,672
|
cpp
|
C++
|
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
|
schinmayee/nimbus
|
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
|
[
"BSD-3-Clause"
] | 20
|
2017-07-03T19:09:09.000Z
|
2021-09-10T02:53:56.000Z
|
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
|
schinmayee/nimbus
|
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
|
[
"BSD-3-Clause"
] | null | null | null |
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.cpp
|
schinmayee/nimbus
|
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
|
[
"BSD-3-Clause"
] | 9
|
2017-09-17T02:05:06.000Z
|
2020-01-31T00:12:01.000Z
|
//#####################################################################
// Copyright 2004-2007, Ron Fedkiw, Eran Guendelman, Nipun Kwatra, Frank Losasso, Andrew Selle, Tamar Shinar, Jonathan Su, Jerry Talton.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Arrays_Computations/MAGNITUDE.h>
#include <PhysBAM_Tools/Grids_Dyadic/OCTREE_GRID.h>
#include <PhysBAM_Tools/Grids_Dyadic/QUADTREE_GRID.h>
#include <PhysBAM_Tools/Grids_Uniform/GRID.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h>
#include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_NODE.h>
#include <PhysBAM_Tools/Grids_Uniform_Arrays/FACE_ARRAYS.h>
#include <PhysBAM_Tools/Grids_Uniform_Boundaries/BOUNDARY_UNIFORM.h>
#include <PhysBAM_Tools/Krylov_Solvers/IMPLICIT_SOLVE_PARAMETERS.h>
#include <PhysBAM_Tools/Log/LOG.h>
#include <PhysBAM_Tools/Math_Tools/RANGE.h>
#include <PhysBAM_Tools/Matrices/MATRIX_4X4.h>
#include <PhysBAM_Tools/Parsing/PARSE_ARGS.h>
#include <PhysBAM_Tools/Read_Write/Grids_Uniform/READ_WRITE_GRID.h>
#include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_ARRAYS.h>
#include <PhysBAM_Tools/Read_Write/Grids_Uniform_Arrays/READ_WRITE_FACE_ARRAYS.h>
#include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_MATRIX_1X1.h>
#include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_SYMMETRIC_MATRIX_2X2.h>
#include <PhysBAM_Tools/Read_Write/Matrices_And_Vectors/READ_WRITE_SYMMETRIC_MATRIX_3X3.h>
#include <PhysBAM_Tools/Read_Write/Point_Clouds/READ_WRITE_POINT_CLOUD.h>
#include <PhysBAM_Geometry/Basic_Geometry/CYLINDER.h>
#include <PhysBAM_Geometry/Basic_Geometry/SPHERE.h>
#include <PhysBAM_Geometry/Collisions/RIGID_COLLISION_GEOMETRY.h>
#include <PhysBAM_Geometry/Grids_Dyadic_Level_Sets/LEVELSET_OCTREE.h>
#include <PhysBAM_Geometry/Grids_Dyadic_Level_Sets/LEVELSET_QUADTREE.h>
#include <PhysBAM_Geometry/Grids_RLE_Level_Sets/LEVELSET_RLE.h>
#include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_CELL_UNIFORM.h>
#include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_FACE_BINARY_UNIFORM.h>
#include <PhysBAM_Geometry/Grids_Uniform_Advection_Collidable/ADVECTION_SEMI_LAGRANGIAN_COLLIDABLE_FACE_UNIFORM.h>
#include <PhysBAM_Geometry/Grids_Uniform_Collisions/GRID_BASED_COLLISION_GEOMETRY_UNIFORM.h>
#include <PhysBAM_Geometry/Grids_Uniform_Level_Sets/FAST_LEVELSET.h>
#include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_FAST_LEVELSET.h>
#include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_1D.h>
#include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_2D.h>
#include <PhysBAM_Geometry/Read_Write/Grids_Uniform_Level_Sets/READ_WRITE_LEVELSET_3D.h>
#include <PhysBAM_Geometry/Read_Write/Implicit_Objects_Uniform/READ_WRITE_LEVELSET_IMPLICIT_OBJECT.h>
#include <PhysBAM_Geometry/Topology_Based_Geometry/TRIANGULATED_SURFACE.h>
#include <PhysBAM_Solids/PhysBAM_Deformables/Collisions_And_Interactions/TRIANGLE_COLLISION_PARAMETERS.h>
#include <PhysBAM_Solids/PhysBAM_Deformables/Deformable_Objects/DEFORMABLE_BODY_COLLECTION.h>
#include <PhysBAM_Solids/PhysBAM_Rigids/Rigid_Bodies/RIGID_BODY.h>
#include <PhysBAM_Solids/PhysBAM_Rigids/Rigid_Bodies/RIGID_BODY_EVOLUTION_PARAMETERS.h>
#include <PhysBAM_Solids/PhysBAM_Solids/Solids/SOLID_BODY_COLLECTION.h>
#include <PhysBAM_Solids/PhysBAM_Solids/Solids/SOLIDS_PARAMETERS.h>
#include <PhysBAM_Solids/PhysBAM_Solids/Solids_Evolution/NEWMARK_EVOLUTION.h>
#include <PhysBAM_Fluids/PhysBAM_Compressible/Euler_Equations/EULER_LAPLACE.h>
#include <PhysBAM_Fluids/PhysBAM_Compressible/Euler_Equations/EULER_UNIFORM.h>
#include <PhysBAM_Fluids/PhysBAM_Fluids/Coupled_Evolution/COMPRESSIBLE_INCOMPRESSIBLE_COUPLING_UTILITIES.h>
#include <PhysBAM_Fluids/PhysBAM_Incompressible/Collisions_And_Interactions/DEFORMABLE_OBJECT_FLUID_COLLISIONS.h>
#include <PhysBAM_Fluids/PhysBAM_Incompressible/Collisions_And_Interactions/FLUID_COLLISION_BODY_INACCURATE_UNION.h>
#include <PhysBAM_Dynamics/Coupled_Driver/PLS_FSI_EXAMPLE.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_COMPRESSIBLE_FLUID_COUPLING_UTILITIES.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_FLUID_COUPLED_EVOLUTION.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/SOLID_FLUID_COUPLED_EVOLUTION_SLIP.h>
#include <PhysBAM_Dynamics/Coupled_Evolution/UNIFORM_COLLISION_AWARE_ITERATOR_FACE_INFO.h>
#include <PhysBAM_Dynamics/Forces_And_Torques/EULER_FLUID_FORCES.h>
#include <PhysBAM_Dynamics/Geometry/GENERAL_GEOMETRY_FORWARD.h>
#include <PhysBAM_Dynamics/Incompressible_Flows/INCOMPRESSIBLE_MULTIPHASE_UNIFORM.h>
#include <PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_EVOLUTION_MULTIPLE_UNIFORM.h>
#include <PhysBAM_Dynamics/Particles/PARTICLES_FORWARD.h>
#include <PhysBAM_Dynamics/Solids_And_Fluids/SOLIDS_FLUIDS_PARAMETERS.h>
#include <stdexcept>
using namespace PhysBAM;
//#####################################################################
// Constructor
//#####################################################################
template<class TV_PFE> PLS_FSI_EXAMPLE<TV_PFE>::
PLS_FSI_EXAMPLE(const STREAM_TYPE stream_type,const int number_of_regions)
:BASE((Initialize_Particles(),stream_type)),solids_parameters(*new SOLIDS_PARAMETERS<TV_PFE>),solids_fluids_parameters(*new SOLIDS_FLUIDS_PARAMETERS<TV_PFE>(this)),
solid_body_collection(*new SOLID_BODY_COLLECTION<TV_PFE>(this,0)),solids_evolution(new NEWMARK_EVOLUTION<TV_PFE>(solids_parameters,solid_body_collection)),
fluids_parameters(number_of_regions,fluids_parameters.WATER,incompressible_fluid_container),resolution(0),convection_order(1),use_pls_evolution_for_structure(false),
two_phase(false)
{
Initialize_Read_Write_General_Structures();
Set_Minimum_Collision_Thickness();
Set_Write_Substeps_Level(-1);
}
//#####################################################################
// Destructor
//#####################################################################
template<class TV_PFE> PLS_FSI_EXAMPLE<TV_PFE>::
~PLS_FSI_EXAMPLE()
{
fluids_parameters.projection=0;
delete solids_evolution;
delete &solid_body_collection;
delete &solids_parameters;
delete &solids_fluids_parameters;
}
//#####################################################################
// Function Register_Options
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Register_Options()
{
if(!parse_args) return;
BASE::Register_Options();
parse_args->Add_String_Argument("-params","","parameter file");
parse_args->Add_Double_Argument("-solidscfl",.9,"solids CFL");
parse_args->Add_Option_Argument("-solidscg","Use CG for time integration");
parse_args->Add_Option_Argument("-solidscr","Use CONJUGATE_RESIDUAL for time integration");
parse_args->Add_Option_Argument("-solidssymmqmr","Use SYMMQMR for time integration");
parse_args->Add_Double_Argument("-rigidcfl",.5,"rigid CFL");
parse_args->Add_Option_Argument("-skip_debug_data","turn off file io for debug data");
parse_args->Add_Integer_Argument("-resolution",1);
}
//#####################################################################
// Function Parse_Options
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Parse_Options()
{
BASE::Parse_Options();
if(parse_args->Is_Value_Set("-skip_debug_data")) fluids_parameters.write_debug_data=false;
resolution=parse_args->Get_Integer_Value("-resolution");
}
//#####################################################################
// Function Add_Volumetric_Body_To_Fluid_Simulation
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Add_Volumetric_Body_To_Fluid_Simulation(RIGID_BODY<TV_PFE>& rigid_body,bool add_collision,bool add_coupling)
{
RIGID_COLLISION_GEOMETRY<TV_PFE>* collision_geometry=new RIGID_COLLISION_GEOMETRY<TV_PFE>(rigid_body);
if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(collision_geometry,rigid_body.particle_index,true);
if(add_coupling)
if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution))
coupled_evolution->iterator_info.coupling_bodies.Append(collision_geometry);
if(rigid_body.simplicial_object) rigid_body.simplicial_object->Initialize_Hierarchy();
}
//#####################################################################
// Function Add_Thin_Shell_To_Fluid_Simulation
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Add_Thin_Shell_To_Fluid_Simulation(RIGID_BODY<TV_PFE>& rigid_body,bool add_collision,bool add_coupling)
{
RIGID_COLLISION_GEOMETRY<TV_PFE>* collision_geometry=new RIGID_COLLISION_GEOMETRY<TV_PFE>(rigid_body);
if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(collision_geometry,rigid_body.particle_index,true);
if(add_coupling)
if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution))
coupled_evolution->iterator_info.coupling_bodies.Append(collision_geometry);
rigid_body.thin_shell=true;
if(collision_geometry->collision_thickness<minimum_collision_thickness) collision_geometry->Set_Collision_Thickness(minimum_collision_thickness);
if(rigid_body.simplicial_object) rigid_body.simplicial_object->Initialize_Hierarchy();
}
//#####################################################################
// Function Add_To_Fluid_Simulation
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Add_To_Fluid_Simulation(DEFORMABLE_OBJECT_FLUID_COLLISIONS<TV_PFE>& deformable_collisions,bool add_collision,bool add_coupling)
{
if(add_collision) fluids_parameters.collision_bodies_affecting_fluid->collision_geometry_collection.Add_Body(&deformable_collisions,0,false);
if(add_coupling)
if(SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>* coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>*>(solids_evolution))
coupled_evolution->iterator_info.coupling_bodies.Append(&deformable_collisions);
if(deformable_collisions.collision_thickness<minimum_collision_thickness) deformable_collisions.Set_Collision_Thickness(minimum_collision_thickness);
deformable_collisions.Initialize_For_Thin_Shells_Fluid_Coupling();
}
//#####################################################################
// Function Get_Source_Velocities
//#####################################################################
template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>::
Get_Source_Velocities(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source,const TV_PFE& constant_source_velocity)
{
for(UNIFORM_GRID_ITERATOR_FACE<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()) if(source.Lazy_Inside(world_to_source.Homogeneous_Times(iterator.Location()))){
int axis=iterator.Axis();fluids_parameters.incompressible->projection.elliptic_solver->psi_N.Component(axis)(iterator.Face_Index())=true;
incompressible_fluid_container.face_velocities.Component(axis)(iterator.Face_Index())=constant_source_velocity[axis];}
}
//#####################################################################
// Function Get_Source_Velocities
//#####################################################################
template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>::
Get_Source_Velocities(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source,const TV_PFE& constant_source_velocity,const ARRAY<bool,FACE_INDEX<TV_PFE::m> >& invalid_mask)
{
for(UNIFORM_GRID_ITERATOR_FACE<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){const int axis=iterator.Axis();const TV_INT face_index=iterator.Face_Index();
if(!invalid_mask(axis,face_index) && source.Lazy_Inside(world_to_source.Homogeneous_Times(iterator.Location()))){
fluids_parameters.incompressible->projection.elliptic_solver->psi_N.Component(axis)(face_index)=true;
incompressible_fluid_container.face_velocities.Component(axis)(face_index)=constant_source_velocity[axis];}}
}
//#####################################################################
// Function Adjust_Phi_With_Source
//#####################################################################
template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>::
Adjust_Phi_With_Source(const GEOMETRY& source,const T_TRANSFORMATION_MATRIX& world_to_source)
{
for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){TV_PFE source_X=world_to_source.Homogeneous_Times(iterator.Location());
if(source.Lazy_Inside(source_X))
fluids_parameters.particle_levelset_evolution->phi(iterator.Cell_Index())=min(fluids_parameters.particle_levelset_evolution->phi(iterator.Cell_Index()),
source.Signed_Distance(source_X));}
}
//#####################################################################
// Function Adjust_Phi_With_Source
//#####################################################################
template<class TV_PFE> template<class GEOMETRY> void PLS_FSI_EXAMPLE<TV_PFE>::
Adjust_Phi_With_Source(const GEOMETRY& source,const int region,const T_TRANSFORMATION_MATRIX& world_to_source)
{
T bandwidth=3*fluids_parameters.grid->Minimum_Edge_Length();
ARRAY<ARRAY<T,TV_INT> >& phis=fluids_parameters.particle_levelset_evolution_multiple->phis;
for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(*fluids_parameters.grid);iterator.Valid();iterator.Next()){
TV_PFE source_X=world_to_source.Homogeneous_Times(iterator.Location());
if(source.Inside(source_X,-bandwidth)){
T source_signed_distance=source.Signed_Distance(source_X);
for(int i=1;i<=fluids_parameters.number_of_regions;i++){
if(i==region) phis(i)(iterator.Cell_Index())=min(phis(i)(iterator.Cell_Index()),source_signed_distance);
else phis(i)(iterator.Cell_Index())=max(phis(i)(iterator.Cell_Index()),-source_signed_distance);}}}
}
//#####################################################################
// Function Revalidate_Fluid_Scalars
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Revalidate_Fluid_Scalars()
{
T_FAST_LEVELSET& levelset=fluids_parameters.particle_levelset_evolution->Levelset(1);
T_FAST_LEVELSET_ADVECTION& levelset_advection=fluids_parameters.particle_levelset_evolution->Levelset_Advection(1);
if(levelset_advection.nested_semi_lagrangian_collidable)
levelset_advection.nested_semi_lagrangian_collidable->Average_To_Invalidated_Cells(*fluids_parameters.grid,fluids_parameters.collidable_phi_replacement_value,levelset.phi);
}
//#####################################################################
// Function Revalidate_Phi_After_Modify_Levelset
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Revalidate_Phi_After_Modify_Levelset()
{
T_FAST_LEVELSET& levelset=fluids_parameters.particle_levelset_evolution->Levelset(1);
T_FAST_LEVELSET_ADVECTION& levelset_advection=fluids_parameters.particle_levelset_evolution->Levelset_Advection(1);
if(levelset_advection.nested_semi_lagrangian_collidable){
levelset_advection.nested_semi_lagrangian_collidable->cell_valid_points_current=levelset_advection.nested_semi_lagrangian_collidable->cell_valid_points_next;
levelset_advection.nested_semi_lagrangian_collidable->Average_To_Invalidated_Cells(*fluids_parameters.grid,fluids_parameters.collidable_phi_replacement_value,levelset.phi);}
}
//#####################################################################
// Function Revalidate_Fluid_Velocity
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Revalidate_Fluid_Velocity(ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities)
{
if(fluids_parameters.incompressible->nested_semi_lagrangian_collidable)
fluids_parameters.incompressible->nested_semi_lagrangian_collidable->Average_To_Invalidated_Face(*fluids_parameters.grid,face_velocities);
}
//#####################################################################
// Function Get_Object_Velocities
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Get_Object_Velocities(LAPLACE_UNIFORM<GRID<TV_PFE> >* elliptic_solver,ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities,const T dt,const T time)
{
if(fluids_parameters.solid_affects_fluid && (fluids_parameters.fluid_affects_solid || fluids_parameters.use_slip)){
if(!fluids_parameters.use_slip){
SOLID_FLUID_COUPLED_EVOLUTION<TV_PFE>& coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION<TV_PFE>&>(*solids_evolution);
coupled_evolution.Apply_Solid_Boundary_Conditions(time,false,face_velocities);}
else{
SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>& coupled_evolution=dynamic_cast<SOLID_FLUID_COUPLED_EVOLUTION_SLIP<TV_PFE>&>(*solids_evolution);
coupled_evolution.Get_Coupled_Faces_And_Interpolated_Solid_Velocities(time,elliptic_solver->psi_N,face_velocities);}}
else fluids_parameters.collision_bodies_affecting_fluid->Compute_Psi_N(elliptic_solver->psi_N,&face_velocities);
}
//#####################################################################
// Function Get_Levelset_Velocity
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Get_Levelset_Velocity(const GRID<TV_PFE>& grid,LEVELSET_MULTIPLE_UNIFORM<GRID<TV_PFE> >& levelset_multiple,ARRAY<T,FACE_INDEX<TV_PFE::m> >& V_levelset,const T time) const
{
ARRAY<T,FACE_INDEX<TV_PFE::m> >::Put(incompressible_fluid_container.face_velocities,V_levelset);
}
//#####################################################################
// Function Initialize_Swept_Occupied_Blocks_For_Advection
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Initialize_Swept_Occupied_Blocks_For_Advection(const T dt,const T time,const ARRAY<T,FACE_INDEX<TV_PFE::m> >& face_velocities)
{
GRID<TV_PFE>& grid=*fluids_parameters.grid;
T maximum_fluid_speed=face_velocities.Maxabs().Max(),maximum_particle_speed=0;
PARTICLE_LEVELSET_UNIFORM<GRID<TV_PFE> >& particle_levelset=fluids_parameters.particle_levelset_evolution->Particle_Levelset(1);
if(particle_levelset.use_removed_negative_particles) for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(particle_levelset.levelset.grid);iterator.Valid();iterator.Next()){
PARTICLE_LEVELSET_REMOVED_PARTICLES<TV_PFE>* particles=particle_levelset.removed_negative_particles(iterator.Cell_Index());
if(particles) maximum_particle_speed=max(maximum_particle_speed,ARRAYS_COMPUTATIONS::Maximum_Magnitude(particles->V));}
if(particle_levelset.use_removed_positive_particles) for(UNIFORM_GRID_ITERATOR_CELL<TV_PFE> iterator(particle_levelset.levelset.grid);iterator.Valid();iterator.Next()){
PARTICLE_LEVELSET_REMOVED_PARTICLES<TV_PFE>* particles=particle_levelset.removed_positive_particles(iterator.Cell_Index());
if(particles) maximum_particle_speed=max(maximum_particle_speed,ARRAYS_COMPUTATIONS::Maximum_Magnitude(particles->V));}
T max_particle_collision_distance=0;
max_particle_collision_distance=max(max_particle_collision_distance,fluids_parameters.particle_levelset_evolution->Particle_Levelset(1).max_collision_distance_factor*grid.dX.Max());
fluids_parameters.collision_bodies_affecting_fluid->Compute_Occupied_Blocks(true,
dt*max(maximum_fluid_speed,maximum_particle_speed)+2*max_particle_collision_distance+(T).5*fluids_parameters.p_grid.dX.Max(),10);
}
//#####################################################################
// Function Delete_Particles_Inside_Objects
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Delete_Particles_Inside_Objects(PARTICLE_LEVELSET_PARTICLES<TV_PFE>& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T time)
{}
//#####################################################################
// Function Read_Output_Files_Fluids
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Read_Output_Files_Fluids(const int frame)
{
fluids_parameters.Read_Output_Files(stream_type,output_directory,frame);
incompressible_fluid_container.Read_Output_Files(stream_type,output_directory,frame);
std::string f=STRING_UTILITIES::string_sprintf("%d",frame);
}
//#####################################################################
// Function Write_Output_Files
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Write_Output_Files(const int frame) const
{
FILE_UTILITIES::Create_Directory(output_directory);
std::string f=STRING_UTILITIES::string_sprintf("%d",frame);
FILE_UTILITIES::Create_Directory(output_directory+"/"+f);
FILE_UTILITIES::Create_Directory(output_directory+"/common");
Write_Frame_Title(frame);
solid_body_collection.Write(stream_type,output_directory,frame,first_frame,solids_parameters.write_static_variables_every_frame,
solids_parameters.rigid_body_evolution_parameters.write_rigid_bodies,solids_parameters.write_deformable_body,solids_parameters.write_from_every_process,
solids_parameters.triangle_collision_parameters.output_interaction_pairs);
if(NEWMARK_EVOLUTION<TV_PFE>* newmark=dynamic_cast<NEWMARK_EVOLUTION<TV_PFE>*>(solids_evolution))
newmark->Write_Position_Update_Projection_Data(stream_type,output_directory+"/"+f+"/");
fluids_parameters.Write_Output_Files(stream_type,output_directory,first_frame,frame);
incompressible_fluid_container.Write_Output_Files(stream_type,output_directory,frame);
}
//#####################################################################
// Function Log_Parameters
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Log_Parameters() const
{
LOG::SCOPE scope("PLS_FSI_EXAMPLE parameters");
BASE::Log_Parameters();
std::stringstream ss;
ss<<"minimum_collision_thickness="<<minimum_collision_thickness<<std::endl;
LOG::filecout(ss.str());
fluids_parameters.Log_Parameters();
}
//#####################################################################
// Function Read_Output_Files_Solids
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Read_Output_Files_Solids(const int frame)
{
solid_body_collection.Read(stream_type,output_directory,frame,frame,solids_parameters.write_static_variables_every_frame,solids_parameters.rigid_body_evolution_parameters.write_rigid_bodies,
solids_parameters.write_deformable_body,solids_parameters.write_from_every_process);
std::string f=STRING_UTILITIES::string_sprintf("%d",frame);
//if(NEWMARK_EVOLUTION<TV_PFE>* newmark=dynamic_cast<NEWMARK_EVOLUTION<TV_PFE>*>(solids_evolution))
// newmark->Read_Position_Update_Projection_Data(stream_type,output_directory+"/"+f+"/");
}
//#####################################################################
// Function Parse_Late_Options
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Parse_Late_Options()
{
if(!parse_args) return;
BASE::Parse_Late_Options();
if(parse_args->Is_Value_Set("-solidscfl")) solids_parameters.cfl=(T)parse_args->Get_Double_Value("-solidscfl");
if(parse_args->Is_Value_Set("-rigidcfl")) solids_parameters.rigid_body_evolution_parameters.rigid_cfl=(T)parse_args->Get_Double_Value("-rigidcfl");
if(parse_args->Is_Value_Set("-solidscg")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_cg;
if(parse_args->Is_Value_Set("-solidscr")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_cr;
if(parse_args->Is_Value_Set("-solidssymmqmr")) solids_parameters.implicit_solve_parameters.evolution_solver_type=krylov_solver_symmqmr;
}
//#####################################################################
// Function Adjust_Particle_For_Domain_Boundaries
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Adjust_Particle_For_Domain_Boundaries(PARTICLE_LEVELSET_PARTICLES<TV_PFE>& particles,const int index,TV_PFE& V,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time)
{
// remove this for speed - don't call the function for the other particles
if(particle_type==PARTICLE_LEVELSET_POSITIVE || particle_type==PARTICLE_LEVELSET_REMOVED_POSITIVE) return;
TV_PFE& X=particles.X(index);TV_PFE X_new=X+dt*V;
T max_collision_distance=fluids_parameters.particle_levelset_evolution->particle_levelset.Particle_Collision_Distance(particles.quantized_collision_distance(index));
T min_collision_distance=fluids_parameters.particle_levelset_evolution->particle_levelset.min_collision_distance_factor*max_collision_distance;
TV_PFE min_corner=fluids_parameters.grid->domain.Minimum_Corner(),max_corner=fluids_parameters.grid->domain.Maximum_Corner();
for(int axis=1;axis<=TV_PFE::m;axis++){
if(fluids_parameters.domain_walls[axis][1] && X_new[axis]<min_corner[axis]+max_collision_distance){
T collision_distance=X[axis]-min_corner[axis];
if(collision_distance>max_collision_distance)collision_distance=X_new[axis]-min_corner[axis];
collision_distance=max(min_collision_distance,collision_distance);
X_new[axis]+=max((T)0,min_corner[axis]-X_new[axis]+collision_distance);
V[axis]=max((T)0,V[axis]);X=X_new-dt*V;}
if(fluids_parameters.domain_walls[axis][2] && X_new[axis]>max_corner[axis]-max_collision_distance){
T collision_distance=max_corner[axis]-X[axis];
if(collision_distance>max_collision_distance) collision_distance=max_corner[axis]-X_new[axis];
collision_distance=max(min_collision_distance,collision_distance);
X_new[axis]-=max((T)0,X_new[axis]-max_corner[axis]+collision_distance);
V[axis]=min((T)0,V[axis]);X=X_new-dt*V;}}
}
//#####################################################################
// Function Update_Fluid_Parameters
//#####################################################################
template<class TV_PFE> void PLS_FSI_EXAMPLE<TV_PFE>::
Update_Fluid_Parameters(const T dt,const T time)
{
fluids_parameters.incompressible->Set_Gravity(fluids_parameters.gravity,fluids_parameters.gravity_direction);
fluids_parameters.incompressible->Set_Body_Force(fluids_parameters.use_body_force);
fluids_parameters.incompressible->projection.Use_Non_Zero_Divergence(fluids_parameters.use_non_zero_divergence);
fluids_parameters.incompressible->projection.elliptic_solver->Solve_Neumann_Regions(fluids_parameters.solve_neumann_regions);
fluids_parameters.incompressible->projection.elliptic_solver->solve_single_cell_neumann_regions=fluids_parameters.solve_single_cell_neumann_regions;
fluids_parameters.incompressible->Use_Explicit_Part_Of_Implicit_Viscosity(fluids_parameters.use_explicit_part_of_implicit_viscosity);
if(fluids_parameters.implicit_viscosity && fluids_parameters.implicit_viscosity_iterations)
fluids_parameters.incompressible->Set_Maximum_Implicit_Viscosity_Iterations(fluids_parameters.implicit_viscosity_iterations);
fluids_parameters.incompressible->Use_Variable_Vorticity_Confinement(fluids_parameters.use_variable_vorticity_confinement);
fluids_parameters.incompressible->Set_Surface_Tension(fluids_parameters.surface_tension);
fluids_parameters.incompressible->Set_Variable_Surface_Tension(fluids_parameters.variable_surface_tension);
fluids_parameters.incompressible->Set_Viscosity(fluids_parameters.viscosity);
fluids_parameters.incompressible->Set_Variable_Viscosity(fluids_parameters.variable_viscosity);
fluids_parameters.incompressible->projection.Set_Density(fluids_parameters.density);
}
//#####################################################################
template class PLS_FSI_EXAMPLE<VECTOR<float,1> >;
template class PLS_FSI_EXAMPLE<VECTOR<float,2> >;
template class PLS_FSI_EXAMPLE<VECTOR<float,3> >;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class PLS_FSI_EXAMPLE<VECTOR<double,1> >;
template class PLS_FSI_EXAMPLE<VECTOR<double,2> >;
template class PLS_FSI_EXAMPLE<VECTOR<double,3> >;
#endif
| 71.155875
| 194
| 0.722365
|
schinmayee
|
54358998b03fceb71efcc8fb2e66032bb7240d54
| 857
|
cpp
|
C++
|
CodeForces/1624/B_Make_AP.cpp
|
sungmen/Acmicpc_Solve
|
0298a6aec84993a4d8767bd2c00490b7201e06a4
|
[
"MIT"
] | null | null | null |
CodeForces/1624/B_Make_AP.cpp
|
sungmen/Acmicpc_Solve
|
0298a6aec84993a4d8767bd2c00490b7201e06a4
|
[
"MIT"
] | null | null | null |
CodeForces/1624/B_Make_AP.cpp
|
sungmen/Acmicpc_Solve
|
0298a6aec84993a4d8767bd2c00490b7201e06a4
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
// freopen("input.in", "r", stdin);
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int t; cin >> t;
while(t--) {
int a, b, c; cin >> a >> b >> c;
if (a > c) swap(a, c);
int ret = c - a;
int d = (c-a)/2;
int p = c - b;
int p2 = b - a;
if (p == p2) {
cout << "YES\n";continue;
}
if (!((a+c)%(2*b))) {
cout << "YES\n";
continue;
}
int f = b - c;
int g = b + f;
if (g > 0 && !(g%a)) {
cout << "YES\n";
continue;
}
f = b - a;
g = b + f;
if (g > 0 && !(g%c)) {
cout << "YES\n";
continue;
}
cout << "NO\n";
}
return 0;
}
| 23.162162
| 74
| 0.347725
|
sungmen
|
543614d4379119294edb2d06606b2e4da4f4ceee
| 755
|
cpp
|
C++
|
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | 1
|
2019-10-07T05:00:21.000Z
|
2019-10-07T05:00:21.000Z
|
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | null | null | null |
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> res(n);
stack<int> st;
int preTime = 0;
for (int i = 0; i < logs.size(); ++i) {
int pos = logs[i].find(':');
int id = atoi(logs[i].substr(0, pos).c_str());
pos = logs[i].find(':', pos+1);
int curTime = atoi(logs[i].substr(pos+1).c_str());
if (!st.empty())
res[st.top()] += curTime - preTime;
preTime = curTime;
if (logs[i][pos-1] == 't')
st.push(id);
else {
++res[st.top()];
st.pop();
++preTime;
}
}
return res;
}
};
| 23.59375
| 62
| 0.403974
|
suzyz
|
543fa89656496c552e0840f549271c1541df4c4e
| 865
|
cpp
|
C++
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | 1
|
2019-10-14T05:41:58.000Z
|
2019-10-14T05:41:58.000Z
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | 1
|
2019-09-15T17:57:43.000Z
|
2019-09-16T06:36:19.000Z
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | null | null | null |
#include "state_vector.h"
#include "omp.h"
#include <iostream>
#include <stdlib.h>
StateVector::StateVector(int num_qubits)
{
this->num_qubits = num_qubits;
this->num_amps = 1L << num_qubits;
// Allocate the required memory for the state vector
std::size_t bytes = num_amps * sizeof(complex);
state = (complex *)malloc(bytes);
// Initialize the state vector
state[0] = complex(1);
#pragma omp parallel for
for (std::size_t i = 1; i < num_amps; i++)
{
state[i] = complex(0);
}
}
void StateVector::print()
{
for (std::size_t i = 0; i < num_amps; i++)
{
complex amp = state[i];
std::cout
<< i << ": "
<< std::real(amp)
<< (std::imag(amp) >= 0.0 ? " + " : " - ")
<< std::abs(std::imag(amp))
<< "i"
<< std::endl;
}
}
| 22.179487
| 56
| 0.523699
|
libtangle
|
5440b08301628ef96e197bf93542acbaa63f2f0f
| 1,490
|
hpp
|
C++
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 14
|
2020-04-14T17:00:56.000Z
|
2021-08-30T08:29:26.000Z
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 27
|
2020-12-27T16:00:44.000Z
|
2021-08-01T13:12:14.000Z
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 1
|
2020-05-29T18:33:37.000Z
|
2020-05-29T18:33:37.000Z
|
#pragma once
#include "prog/expr/node.hpp"
#include "prog/sym/const_decl_table.hpp"
#include "prog/sym/func_decl_table.hpp"
#include <vector>
namespace prog::sym {
// Function definition. Contains the body of a user-function.
class FuncDef final {
friend class FuncDefTable;
public:
enum class Flags : unsigned int {
None = 0U,
NoInline = 1U << 0U, // Hint to the optmizer that it should not inline this function.
};
FuncDef() = delete;
FuncDef(const FuncDef& rhs) = delete;
FuncDef(FuncDef&& rhs) = default;
~FuncDef() = default;
auto operator=(const FuncDef& rhs) -> FuncDef& = delete;
auto operator=(FuncDef&& rhs) noexcept -> FuncDef& = delete;
[[nodiscard]] auto getId() const noexcept -> const FuncId&;
[[nodiscard]] auto getFlags() const noexcept -> Flags;
[[nodiscard]] auto hasFlags(Flags flags) const noexcept -> bool;
[[nodiscard]] auto getConsts() const noexcept -> const sym::ConstDeclTable&;
[[nodiscard]] auto getBody() const noexcept -> const expr::Node&;
[[nodiscard]] auto getOptArgInitializer(unsigned int i) const -> expr::NodePtr;
private:
sym::FuncId m_id;
sym::ConstDeclTable m_consts;
expr::NodePtr m_body;
std::vector<expr::NodePtr> m_optArgInitializers;
Flags m_flags;
FuncDef(
sym::FuncId id,
sym::ConstDeclTable consts,
expr::NodePtr body,
std::vector<expr::NodePtr> optArgInitializers,
Flags flags);
};
} // namespace prog::sym
| 29.8
| 89
| 0.672483
|
BastianBlokland
|
5445fbb01d0b541ba8265c0941408dadaf0ef837
| 226
|
hpp
|
C++
|
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <cassert>
#define OS Windows
#define __likely(c) (c)
#define __unlikely(c) (c)
#define __unreachable __assume(0)
#define nodefault default: { __unreachable; }
#define xassert(c) assert(c)
| 17.384615
| 46
| 0.69469
|
ameisen
|
5446676bcffd729b260e4aba4e25c442da814dc9
| 2,705
|
cxx
|
C++
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 56
|
2015-02-28T08:19:58.000Z
|
2021-11-04T16:46:17.000Z
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 40
|
2015-04-08T14:58:42.000Z
|
2017-11-17T20:57:26.000Z
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 17
|
2015-04-03T00:57:43.000Z
|
2018-03-30T20:46:14.000Z
|
namespace CTF_int{
double seq_tsr_spctr_cst_off_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_off_k2_init[] = {-2.1996E-04, 3.1883E-09, 3.8743E-11};
double seq_tsr_spctr_off_k0_init[] = {8.6970E-06, 4.5598E-11, 1.1544E-09};
double seq_tsr_spctr_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_off_k2_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k2_init[] = {-8.8459E-08, 8.1207E-10, -2.8486E-12};
double seq_tsr_spctr_cst_k3_init[] = {1.8504E-08, 2.9154E-11, 2.1973E-11};
double seq_tsr_spctr_cst_k4_init[] = {2.0948E-05, 1.2294E-09, 8.0037E-10};
double seq_tsr_spctr_k0_init[] = {2.2620E-08, -5.7494E-10, 2.2146E-09};
double seq_tsr_spctr_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_k2_init[] = {3.0917E-08, 5.2181E-11, 4.1634E-12};
double seq_tsr_spctr_k3_init[] = {7.2456E-08, 1.5128E-10, -1.5528E-12};
double seq_tsr_spctr_k4_init[] = {1.6880E-07, 4.9411E-10, 9.2847E-13};
double pin_keys_mdl_init[] = {3.1189E-09, 6.6717E-08};
double seq_tsr_ctr_mdl_cst_init[] = {5.1626E-06, -6.3215E-11, 3.9638E-09};
double seq_tsr_ctr_mdl_ref_init[] = {4.9138E-08, 5.8290E-10, 4.8575E-11};
double seq_tsr_ctr_mdl_inr_init[] = {2.0647E-08, 1.9721E-10, 2.9948E-11};
double seq_tsr_ctr_mdl_off_init[] = {6.2925E-05, 1.7449E-11, 1.7211E-12};
double seq_tsr_ctr_mdl_cst_inr_init[] = {1.3863E-04, 2.0119E-10, 9.8820E-09};
double seq_tsr_ctr_mdl_cst_off_init[] = {8.4844E-04, -5.9246E-11, 3.5247E-10};
double long_contig_transp_mdl_init[] = {2.9158E-10, 3.0501E-09};
double shrt_contig_transp_mdl_init[] = {1.3427E-08, 4.3168E-09};
double non_contig_transp_mdl_init[] = {4.0475E-08, 4.0463E-09};
double dgtog_res_mdl_init[] = {2.9786E-05, 2.4335E-04, 1.0845E-08};
double blres_mdl_init[] = {1.0598E-05, 7.2741E-08};
double alltoall_mdl_init[] = {1.0000E-06, 1.0000E-06, 5.0000E-10};
double alltoallv_mdl_init[] = {2.7437E-06, 2.2416E-05, 1.0469E-08};
double red_mdl_init[] = {6.2935E-07, 4.6276E-06, 9.2245E-10};
double red_mdl_cst_init[] = {5.7302E-07, 4.7347E-06, 6.0191E-10};
double allred_mdl_init[] = {8.4416E-07, 6.8651E-06, 3.5845E-08};
double allred_mdl_cst_init[] = {-3.3754E-04, 2.1343E-04, 3.0801E-09};
double bcast_mdl_init[] = {1.5045E-06, 1.4485E-05, 3.2876E-09};
double spredist_mdl_init[] = {1.2744E-04, 1.0278E-03, 7.6837E-08};
double csrred_mdl_init[] = {3.7005E-05, 1.1854E-04, 5.5165E-09};
double csrred_mdl_cst_init[] = {-1.8323E-04, 1.3076E-04, 2.8732E-09};
}
| 65.97561
| 79
| 0.721257
|
solomonik
|
54480537ce43bf919f9db44aa9af3ca8e5844ec5
| 1,009
|
cpp
|
C++
|
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
|
paulmoon/csc460
|
a432cfccef97fca5820cb0fc006112bb773cda0f
|
[
"MIT"
] | null | null | null |
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
|
paulmoon/csc460
|
a432cfccef97fca5820cb0fc006112bb773cda0f
|
[
"MIT"
] | null | null | null |
Project2/GccApplication3/GccApplication3/tests/test012_service_rr.cpp
|
paulmoon/csc460
|
a432cfccef97fca5820cb0fc006112bb773cda0f
|
[
"MIT"
] | null | null | null |
#ifdef USE_TEST_012
/*
Testing RR tasks subscribing to another RR publisher.
Desired Trace:
T012;0;0;1;1;2;2;3;3;4;4;5;5;6;6;7;7;8;8;9;9;
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "os.h"
#include "uart/uart.h"
#include "trace/trace.h"
#include "../profiler.h"
#include "../error_code.h"
SERVICE* services[3];
int g_count = 0;
void r(){
int16_t v;
while( g_count < 20){
Service_Subscribe(services[0], &v);
add_to_trace(v);
g_count += 1;
}
}
void r2(){
int16_t count = 0;
for(;;){
Service_Publish(services[0],count++);
Task_Next();
if( g_count >= 20){
print_trace();
}
}
}
extern int r_main(){
uart_init();
set_trace_test(12);
services[0] = Service_Init();
Task_Create_RR(r,0);
Task_Create_RR(r,0);
Task_Create_RR(r2,0);
Task_Terminate();
return 0;
}
#endif
| 18.017857
| 54
| 0.54113
|
paulmoon
|
544d01213eb9ec71ae3a48c1140790d960edc11c
| 6,585
|
cpp
|
C++
|
src/maglev/MagLevNull.cpp
|
mindpowered/maglev-cpp
|
8383ed7576202d6d61fcdfb6723a2baa74b8e010
|
[
"MIT"
] | null | null | null |
src/maglev/MagLevNull.cpp
|
mindpowered/maglev-cpp
|
8383ed7576202d6d61fcdfb6723a2baa74b8e010
|
[
"MIT"
] | null | null | null |
src/maglev/MagLevNull.cpp
|
mindpowered/maglev-cpp
|
8383ed7576202d6d61fcdfb6723a2baa74b8e010
|
[
"MIT"
] | null | null | null |
// Generated by Haxe 4.1.1
#include <hxcpp.h>
#ifndef INCLUDED_maglev_MagLevAny
#include <maglev/MagLevAny.h>
#endif
#ifndef INCLUDED_maglev_MagLevNull
#include <maglev/MagLevNull.h>
#endif
#ifndef INCLUDED_maglev_MagLevString
#include <maglev/MagLevString.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_25586abe6b76e172_662_new,"maglev.MagLevNull","new",0xb2260507,"maglev.MagLevNull.new","maglev/MagLev.hx",662,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_665_getType,"maglev.MagLevNull","getType",0x2072b697,"maglev.MagLevNull.getType","maglev/MagLev.hx",665,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_671_isEqual,"maglev.MagLevNull","isEqual",0x0fef8791,"maglev.MagLevNull.isEqual","maglev/MagLev.hx",671,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_679_toJson,"maglev.MagLevNull","toJson",0x070a9afc,"maglev.MagLevNull.toJson","maglev/MagLev.hx",679,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_659_create,"maglev.MagLevNull","create",0x06f854b5,"maglev.MagLevNull.create","maglev/MagLev.hx",659,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_668_getStaticType,"maglev.MagLevNull","getStaticType",0x365a7225,"maglev.MagLevNull.getStaticType","maglev/MagLev.hx",668,0x5b19476f)
HX_LOCAL_STACK_FRAME(_hx_pos_25586abe6b76e172_682_wrap,"maglev.MagLevNull","wrap",0x351b1743,"maglev.MagLevNull.wrap","maglev/MagLev.hx",682,0x5b19476f)
namespace maglev{
void MagLevNull_obj::__construct(){
HX_STACKFRAME(&_hx_pos_25586abe6b76e172_662_new)
HXDLIN( 662) super::__construct();
}
Dynamic MagLevNull_obj::__CreateEmpty() { return new MagLevNull_obj; }
void *MagLevNull_obj::_hx_vtable = 0;
Dynamic MagLevNull_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< MagLevNull_obj > _hx_result = new MagLevNull_obj();
_hx_result->__construct();
return _hx_result;
}
bool MagLevNull_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x7cdfae7b) {
return inClassId==(int)0x00000001 || inClassId==(int)0x7cdfae7b;
} else {
return inClassId==(int)0x7fdb9bc4;
}
}
int MagLevNull_obj::getType(){
HX_STACKFRAME(&_hx_pos_25586abe6b76e172_665_getType)
HXDLIN( 665) return 1;
}
bool MagLevNull_obj::isEqual( ::maglev::MagLevAny other){
HX_STACKFRAME(&_hx_pos_25586abe6b76e172_671_isEqual)
HXDLIN( 671) int _hx_tmp = other->getType();
HXDLIN( 671) if ((_hx_tmp == this->getType())) {
HXLINE( 672) return true;
}
else {
HXLINE( 675) return false;
}
HXLINE( 671) return false;
}
::maglev::MagLevString MagLevNull_obj::toJson(){
HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_679_toJson)
HXDLIN( 679) return ::maglev::MagLevString_obj::__alloc( HX_CTX ,HX_("null",87,9e,0e,49));
}
::maglev::MagLevNull MagLevNull_obj::create(){
HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_659_create)
HXDLIN( 659) return ::maglev::MagLevNull_obj::__alloc( HX_CTX );
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(MagLevNull_obj,create,return )
int MagLevNull_obj::getStaticType(){
HX_STACKFRAME(&_hx_pos_25586abe6b76e172_668_getStaticType)
HXDLIN( 668) return 1;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(MagLevNull_obj,getStaticType,return )
::maglev::MagLevAny MagLevNull_obj::wrap( ::maglev::MagLevAny o){
HX_GC_STACKFRAME(&_hx_pos_25586abe6b76e172_682_wrap)
HXDLIN( 682) if (::hx::IsNull( o )) {
HXLINE( 683) return ::maglev::MagLevNull_obj::__alloc( HX_CTX );
}
else {
HXLINE( 685) return o;
}
HXLINE( 682) return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(MagLevNull_obj,wrap,return )
::hx::ObjectPtr< MagLevNull_obj > MagLevNull_obj::__new() {
::hx::ObjectPtr< MagLevNull_obj > __this = new MagLevNull_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< MagLevNull_obj > MagLevNull_obj::__alloc(::hx::Ctx *_hx_ctx) {
MagLevNull_obj *__this = (MagLevNull_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(MagLevNull_obj), false, "maglev.MagLevNull"));
*(void **)__this = MagLevNull_obj::_hx_vtable;
__this->__construct();
return __this;
}
MagLevNull_obj::MagLevNull_obj()
{
}
::hx::Val MagLevNull_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"toJson") ) { return ::hx::Val( toJson_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"getType") ) { return ::hx::Val( getType_dyn() ); }
if (HX_FIELD_EQ(inName,"isEqual") ) { return ::hx::Val( isEqual_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
bool MagLevNull_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"wrap") ) { outValue = wrap_dyn(); return true; }
break;
case 6:
if (HX_FIELD_EQ(inName,"create") ) { outValue = create_dyn(); return true; }
break;
case 13:
if (HX_FIELD_EQ(inName,"getStaticType") ) { outValue = getStaticType_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *MagLevNull_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *MagLevNull_obj_sStaticStorageInfo = 0;
#endif
static ::String MagLevNull_obj_sMemberFields[] = {
HX_("getType",70,a2,8b,1f),
HX_("isEqual",6a,73,08,0f),
HX_("toJson",43,ad,21,7c),
::String(null()) };
::hx::Class MagLevNull_obj::__mClass;
static ::String MagLevNull_obj_sStaticFields[] = {
HX_("create",fc,66,0f,7c),
HX_("getStaticType",be,46,27,0b),
HX_("wrap",ca,39,ff,4e),
::String(null())
};
void MagLevNull_obj::__register()
{
MagLevNull_obj _hx_dummy;
MagLevNull_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("maglev.MagLevNull",95,75,57,ef);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &MagLevNull_obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(MagLevNull_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(MagLevNull_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< MagLevNull_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = MagLevNull_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = MagLevNull_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace maglev
| 34.296875
| 179
| 0.731815
|
mindpowered
|
544ebc8e13e44f1a9d4d382557bc3bffc28f7cfe
| 1,933
|
cpp
|
C++
|
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
|
FirstLoveLife/Rider-Faiz
|
ffa1ec3b335b836bd81600fb67587734325b2ce6
|
[
"MIT"
] | 3
|
2019-01-18T08:36:03.000Z
|
2020-10-29T08:30:59.000Z
|
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
|
FirstLoveLife/Faiz
|
ffa1ec3b335b836bd81600fb67587734325b2ce6
|
[
"MIT"
] | null | null | null |
test/type_traits/is_trivially_copy_assignable.libcxx.cpp
|
FirstLoveLife/Faiz
|
ffa1ec3b335b836bd81600fb67587734325b2ce6
|
[
"MIT"
] | null | null | null |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// is_trivially_copy_assignable
// XFAIL: gcc-4.9
#include "test-utilities.hpp"
#include <catch2/catch.hpp>
#include "rider/faiz/type_traits.hpp"
namespace
{
template<class T>
void
test_has_trivially_copy_assignable()
{
STATIC_REQUIRE(Rider::Faiz::is_trivially_copy_assignable<T>::value);
#if TEST_STD_VER > 14
STATIC_REQUIRE(Rider::Faiz::is_trivially_copy_assignable_v<T>);
#endif
}
template<class T>
void
test_has_not_trivially_copy_assignable()
{
STATIC_REQUIRE(!Rider::Faiz::is_trivially_copy_assignable<T>::value);
#if TEST_STD_VER > 14
STATIC_REQUIRE(!Rider::Faiz::is_trivially_copy_assignable_v<T>);
#endif
}
class Empty
{};
class NotEmpty
{
virtual ~NotEmpty();
};
union Union
{};
struct bit_zero
{
int : 0;
};
class Abstract
{
virtual ~Abstract() = 0;
};
struct A
{
A&
operator=(const A&);
};
} // namespace
TEST_CASE("is_trivially_copy_assignable.libcxx: ")
{
test_has_trivially_copy_assignable<int&>();
test_has_trivially_copy_assignable<Union>();
test_has_trivially_copy_assignable<Empty>();
test_has_trivially_copy_assignable<int>();
test_has_trivially_copy_assignable<double>();
test_has_trivially_copy_assignable<int*>();
test_has_trivially_copy_assignable<const int*>();
test_has_trivially_copy_assignable<bit_zero>();
test_has_not_trivially_copy_assignable<void>();
test_has_not_trivially_copy_assignable<A>();
test_has_not_trivially_copy_assignable<NotEmpty>();
test_has_not_trivially_copy_assignable<Abstract>();
test_has_not_trivially_copy_assignable<const Empty>();
}
| 21.719101
| 80
| 0.691154
|
FirstLoveLife
|
5450373884e4d7eeae4d4c943765a34f77388329
| 650
|
cpp
|
C++
|
dlls/ADM/Physics/PhysManager.cpp
|
BlueNightHawk4906/HL-ADM-Custom
|
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
|
[
"Unlicense"
] | 1
|
2020-12-11T17:52:33.000Z
|
2020-12-11T17:52:33.000Z
|
dlls/ADM/Physics/PhysManager.cpp
|
BlueNightHawk4906/HL-ADM-Custom
|
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
|
[
"Unlicense"
] | 7
|
2021-07-09T09:19:14.000Z
|
2021-07-20T19:35:21.000Z
|
dlls/ADM/Physics/PhysManager.cpp
|
phoenixprojectsoftware/phoenixADM
|
5f170a34739e64111dbe161d9ab9e0baa219512b
|
[
"Unlicense"
] | null | null | null |
#include "Base/ExtDLL.h"
#include "Util.h"
#include "Base/CBase.h"
#include "PhysManager.h"
#include "../shared/ADM/Physics/PhysicsWorld.h"
LINK_ENTITY_TO_CLASS( phys_manager, CPhysManager );
void CPhysManager::Spawn()
{
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
// pev->flags |= FL_ALWAYSTHINK;
SetThink( &CPhysManager::PhysManagerThink );
pev->nextthink = gpGlobals->time + 1.5f;
}
void CPhysManager::PhysManagerThink()
{
g_Physics.StepSimulation( 1.f / 64.f, 16 );
pev->nextthink = gpGlobals->time + 1.f / 64.f;
//ALERT( at_console, "CPhysManager::Think() time %3.2f\n", pev->nextthink );
}
| 22.413793
| 78
| 0.673846
|
BlueNightHawk4906
|
54571cf0e13f22a286b8c650a63c535529550a82
| 35,187
|
hpp
|
C++
|
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | 1
|
2018-05-14T13:46:59.000Z
|
2018-05-14T13:46:59.000Z
|
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | null | null | null |
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <functional>
#include <iterator>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
#include <ext/config.hpp>
#include <ext/future.hpp>
#include <ext/thread_pool.hpp>
#include <ext/intrusive_ptr.hpp>
#include <ext/library_logger/logger.hpp>
#include <ext/stream_filtering/filter_types.hpp>
#include <ext/openssl.hpp>
#include <ext/net/socket_stream.hpp>
#include <ext/net/socket_queue.hpp>
#include <ext/net/http_parser.hpp>
#include <ext/net/http/http_types.hpp>
#include <ext/net/http/http_server_handler.hpp>
#include <ext/net/http/http_server_filter.hpp>
#include <ext/net/http/nonblocking_http_parser.hpp>
#include <ext/net/http/nonblocking_http_writer.hpp>
namespace ext::net::http
{
/// Simple embedded http server.
/// Listens for incoming connections on given listener sockets,
/// parses http requests, calls registered handler that accepts that request
///
/// supports:
/// * SSL
/// * http_handlers: sync and async(result is returned via ext::future)
/// * http_filters
/// * thread_pool executor
///
/// have 2 working modes(those should not be mixed):
/// * work on current thread(join/interrupt), useful when you want start simple http_server on main thread
/// * work on internal background thread(start/stop), useful when you do not want block main thread in http_server
///
/// NOTE: by default there no preinstalled filters or handlers
class http_server
{
using self_type = http_server;
public:
using handle_type = socket_queue::handle_type;
using duration_type = socket_queue::duration_type;
using time_point = socket_queue::time_point;
using handler_result_type = http_server_handler::result_type;
using simple_handler_result_type = simple_http_server_handler::result_type;
using simple_handler_body_function_type = simple_http_server_handler::body_function_types;
using simple_handler_request_function_type = simple_http_server_handler::request_function_type;
#ifdef EXT_ENABLE_OPENSSL
using SSL = ::SSL;
using ssl_ctx_iptr = ext::openssl::ssl_ctx_iptr;
using ssl_iptr = ext::openssl::ssl_iptr;
#else
using SSL = std::nullptr_t;
using ssl_ctx_iptr = std::nullptr_t;
using ssl_iptr = std::nullptr_t;
#endif
// Internally sockets(both regular and listeners) are handled by ext::net::socket_queue, this class is not thread safe
// (system calls select/poll used by ext::net::socket_queue do not affected by any pthread related functions).
// So we have background thread(internal or joined) running ext::net::socket_queue, whenever some action is performed via public method
// it's submitted into internal task queue -> socket_queue interrupted and all pending queued actions are executed on background thread.
// See m_sock_queue, m_tasks, m_delayed
//
// http_request/socket processing:
// When there is ready socket in socket_queue - it's taken, http_request is read, then action handler is searched and invoked,
// http_response is written back, socket is placed back into the queue or closed.
//
// This whole http processing can be done on executor or, if unset, in background thread.
// http action handlers can be async - return ext::future<http_response>, sync - return ready http_response
//
// Currently http request and response are synchronously processed in executor or background thread -
// while whole http request will not be read, action handler invoked, http response written back - socket will not be placed back into queue,
// and background thread will be busy working with current request/socket, unless processing executor is set.
//
// In case of async special continuation is attached to returned future, it submits special task when http_result future become ready.
// This task continues processing of this http request, writes back response, etc(see m_delayed)
//
// There also pre/post http filters, currently those can't be async, but maybe changed in future.
// Those can be used for some common functionality: zlib processing, authentication, CORS, other.
//
// processing_context:
// When http request is processed - processing context is allocated for it, it holds registered filters, handlers and some helper members.
// Some minimal numbers of contexts are cached and only reinitialized if needed, if there no cached contexts are available - one is allocated.
// When maximum number exceeds - server busy is returned as http answer.
//
// handle_* group:
// http request is handled by handle_* method group. All methods can be overridden, also to allow more customization, each method returns what must be done next:
// handle_request -> handle_prefilters -> .... -> handle_finish
protected:
using process_result = http_server_handler::result_type;
using async_process_result = std::variant<ext::future<http_response>, ext::future<null_response_type>>;
using hook_type = boost::intrusive::list_base_hook<
boost::intrusive::link_mode<boost::intrusive::link_mode_type::normal_link>
>;
class task_base; // inherits hook_type
template <class Functor, class ResultType>
class task_impl; // implements task_base
class delayed_async_executor_task_continuation;
class processing_executor;
template <class ExecutorPtr>
class processing_executor_impl;
class async_http_body_source_impl;
class http_body_streambuf_impl;
protected:
using list_option = boost::intrusive::base_hook<hook_type>;
using task_list = boost::intrusive::list<task_base, list_option, boost::intrusive::constant_time_size<false>>;
using delayed_async_executor_task_continuation_list = boost::intrusive::list<delayed_async_executor_task_continuation, list_option, boost::intrusive::constant_time_size<false>>;
protected:
class closable_http_body;
struct processing_context;
class http_server_control;
/// sort of union of bellow methods;
class handle_method_type;
using regular_handle_methed = auto (http_server::*)(processing_context * context) -> handle_method_type ;
using finalizer_handle_method = void (http_server::*)(processing_context * context);
protected:
using streaming_context = ext::stream_filtering::streaming_context
<
std::vector<std::unique_ptr<ext::stream_filtering::filter>>, // FilterVector
std::vector<ext::stream_filtering::data_context>, // DataContextVector
std::vector<std::vector<char>> // BuffersVector
>;
/// holds some listener context configuration
struct listener_context
{
unsigned backlog;
ssl_ctx_iptr ssl_ctx;
ext::net::listener listener; // valid until it placed into sock_queue
};
struct config_context;
struct filtering_context;
struct filtering_context
{
streaming_context request_streaming_ctx, response_streaming_ctx;
boost::container::flat_map<std::string, http::http_server_control::property> property_map;
};
/// groups some context parameters for processing http request
struct processing_context
{
socket_streambuf sock; // socket where http request came from
ssl_iptr ssl_ptr = nullptr; // ssl session, created from listener ssl context
// socket waiting
socket_queue::wait_type wait_type;
// next method after socket waiting is complete
regular_handle_methed next_method;
// current method that is executed
regular_handle_methed cur_method;
// state used by some handle_methods, value for switch
unsigned async_state = 0;
// should this connection be closed after request processed, determined by Connection header,
// but also - were there errors while processing request.
connection_action_type conn_action = connection_action_type::close;
// byte counters, used in various scenarios
std::size_t read_count; // number of bytes read from socket
std::size_t written_count; // number of bytes written socket
http_server_utils::nonblocking_http_parser parser; // http parser with state
http_server_utils::nonblocking_http_writer writer; // http writer with state
// buffers for filtered and non filtered parsing and writting
std::vector<char> request_raw_buffer, request_filtered_buffer;
std::vector<char> response_raw_buffer, response_filtered_buffer;
std::string chunk_prefix; // buffer for preparing and holding chunk prefix(chunked transfer encoding)
// contexts for filtering request/reply http_body;
std::unique_ptr<filtering_context> filter_ctx;
ext::stream_filtering::processing_parameters filter_params;
http_request request; // current http request, valid after is was parsed
process_result response = null_response; // current http response, valid after handler was called
std::shared_ptr<const config_context> config; // config snapshot
const http_server_handler * handler; // found handler for request
bool expect_extension; // request with Expect: 100-continue header, see RFC7231 section 5.1.1.
bool continue_answer; // context holds answer 100 Continue
bool first_response_written; // wrote first 100-continue
bool final_response_written; // wrote final(possibly second) response
bool response_is_final; // response was marked as final, see http_server_filter_control
std::atomic<ext::shared_state_basic *> executor_state = nullptr; // holds current pending processing execution task state, used for internal synchronization
std::atomic<ext::shared_state_basic *> async_task_state = nullptr; // holds current pending async operation(from handlers), used for internal synchronization
// async_http_body_source/http_body_streambuf closing closer
// allowed values:
// 0x00 - no body closer
// 0x01 - http_server is closing, already set body closer is taken, new should not be installed
// other - some body closer
std::atomic_uintptr_t body_closer = 0;
};
/// holds some configuration parameters sharable by processing contexts
struct config_context
{
/// http filters, handlers can added when http server already started. What if we already processing some request and handler is added?
/// When processing starts - context holds snapshot of currently registered handlers, filters and only they are used; it also handles multithreaded issues.
/// whenever filters, handlers or anything config related changes -> new context is config_context as copy of current is created with dirty set to true.
/// sort of copy on write
unsigned dirty = true;
std::vector<const http_server_handler *> handlers; // http handlers registered in server
std::vector<const http_prefilter *> prefilters; // http prefilters registered in server, sorted by order
std::vector<const http_postfilter *> postfilters; // http postfilters registered in server, sorted by order
/// Maximum bytes read from socket while parsing HTTP request headers, -1 - unlimited.
/// If request headers are not parsed yet, and server read from socket more than maximum_http_headers_size, BAD request is returned
std::size_t maximum_http_headers_size = -1;
/// Maximum bytes read from socket while parsing HTTP body, -1 - unlimited.
/// This affects only simple std::vector<char>/std::string bodies, and never affects stream/async bodies.
/// If server read from socket more than maximum_http_body_size, BAD request is returned
std::size_t maximum_http_body_size = -1;
/// Maximum bytes read from socket while parsing discarded HTTP request, -1 - unlimited.
/// If there is no handler for this request, or some other error code is answered(e.g. unauthorized),
/// this request is considered to be discarded - in this case we still might read it's body,
/// but no more than maximum_discarded_http_body_size, otherwise connection is forcibly closed.
std::size_t maximum_discarded_http_body_size = -1;
};
protected:
socket_queue m_sock_queue; // intenal socket and listener queue
boost::container::flat_map<socket_handle_type, listener_context> m_listener_contexts; // listener contexts map by listener handle
// sharable cow config context, see config_context description
std::shared_ptr<config_context> m_config_context = std::make_shared<config_context>();
ext::library_logger::logger * m_logger = nullptr;
// log level on which http request and reply headers are logged
unsigned m_request_logging_level = -1;
// log level on which http request and reply body are logger, overrides m_request_logging_level if bigger
unsigned m_request_body_logging_level = -1;
// log level on which every read from socket operation buffer is logged
unsigned m_read_buffer_logging_level = -1;
// log level on which every write to socket operation buffer is logged
unsigned m_write_buffer_logging_level = -1;
// processing_contexts
std::size_t m_minimum_contexts = 10;
std::size_t m_maximum_contexts = 128;
// set of existing contexts for which sockets are waiting for read/write state
boost::container::flat_map<socket_streambuf::handle_type, processing_context *> m_pending_contexts;
// set of existing contexts
boost::container::flat_set<processing_context *> m_processing_contexts;
// free contexts that can be reused
std::vector<processing_context *> m_free_contexts;
mutable std::mutex m_mutex;
mutable std::condition_variable m_event;
mutable std::thread m_thread;
std::thread::id m_threadid; // id of thread running tasks and socket queue
// linked list of task
task_list m_tasks;
// delayed tasks are little tricky, for every one - we create a service continuation,
// which when fired, adds task to task_list.
// Those can work and fire when we are being destructed,
// http_server lifetime should not linger on delayed_task - they should become abandoned.
// Nevertheless we have lifetime problem.
//
// So we store those active service continuations in a list:
// - When continuation is fired it checks if it's taken(future internal helper flag):
// * if yes - http_server is gone, nothing to do;
// * if not - http_server is still there - we should add task to a list;
//
// - When destructing we are checking each continuation if it's taken(future internal helper flag):
// * if successful - service continuation is sort of cancelled and it will not access http_server
// * if not - continuation is firing right now somewhere in the middle,
// so destructor must wait until it finishes and then complete destruction.
delayed_async_executor_task_continuation_list m_delayed;
// how many delayed_continuations were not "taken/cancelled" at destruction,
// and how many we must wait - it's sort of a semaphore.
std::size_t m_delayed_count = 0;
// optional http request processing executor
std::shared_ptr<processing_executor> m_processing_executor;
// http_server running state variables
bool m_running = false; // http_server is in running state
bool m_started = false; // http_server is started either by start or join
bool m_joined = false; // used only by join/interrupt pair methods
bool m_interrupted = false; // used only by join/interrupt pair methods
// listeners default backlog
int m_default_backlog = 10;
/// socket HTTP request processing operations(read/write) timeout
duration_type m_socket_timeout = std::chrono::seconds(10);
/// how long socket can be kept open awaiting new incoming HTTP requests
duration_type m_keep_alive_timeout = m_sock_queue.get_default_timeout();
/// timeout for socket operations when closing, basicly affects SSL shutdown
static constexpr duration_type m_close_socket_timeout = std::chrono::milliseconds(100);
static constexpr auto chunkprefix_size = sizeof(int) * CHAR_BIT / 4 + (CHAR_BIT % 4 ? 1 : 0); // in hex
static constexpr std::string_view crlf = "\r\n";
protected:
/// Performs actual startup of http server, blocking
virtual void do_start(std::unique_lock<std::mutex> & lk);
/// Performs actual stopping of http server, blocking
virtual void do_stop (std::unique_lock<std::mutex> & lk);
/// Resets http server to default state: closes all sockets, deletes handlers, filters.
/// Some properties are not reset
virtual void do_reset(std::unique_lock<std::mutex> & lk);
/// clears m_config_context
virtual void do_clear_config(std::unique_lock<std::mutex> & lk);
public:
/// Starts http_server: internal background thread + listeners start listen
virtual void start();
/// Stops http_server: background thread stopped, all sockets are closed, all http handlers, filters are deleted
virtual void stop();
/// Similar to start, but callers thread becomes background one and caller basicly joins it.
/// Useful for simple configurations were you start https_server from main thread
virtual void join();
/// Similar to stop, but must be called if http_server was started via join.
/// Can be called from signal handler.
virtual void interrupt();
protected:
/// Main background thread function, started_promise can be used to propagate exceptions to caller, and notify when actual startup is complete
virtual void run_proc(ext::promise<void> & started_promise);
/// Runs socket_queue until it interrupted.
virtual void run_sockqueue();
/// Reads, parses, process http request and writes http_response back, full cycle for single http request on socket.
virtual void run_socket(processing_context * context);
/// Runs handle_* circuit, updates context->cur_method for regular methods
virtual void executor_handle_runner(handle_method_type next_method, processing_context * context);
/// Submits and schedules processing of async result
virtual void submit_async_executor_task(ext::intrusive_ptr<ext::shared_state_basic> handle, handle_method_type method, processing_context * context);
/// Helper method for creating async handle_method
static auto async_method(ext::intrusive_ptr<ext::shared_state_basic> future_handle, regular_handle_methed async_method) -> handle_method_type;
static auto async_method(socket_queue::wait_type wait, regular_handle_methed async_method) -> handle_method_type;
/// non blocking recv with MSG_PEEK:
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto peek(processing_context * context, char * data, int len, int & read) const -> handle_method_type;
/// non blocking recv method:
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto recv(processing_context * context, char * data, int len, int & read) const -> handle_method_type;
/// non blocking send method:
/// * if successfully sends something - returns nullptr
/// * if send would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto send(processing_context * context, const char * data, int len, int & written) const -> handle_method_type;
/// returns socket send buffer size getsockopt(..., SOL_SOCKET, SO_SNDBUF, ...), but no more that 10 * 1024
virtual std::size_t sendbuf_size(processing_context * context) const;
/// non blocking recv method, read data is parsed with http parser,
/// result is stored in whatever parser body destination is set
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish.
virtual auto recv_and_parse(processing_context * context) const -> handle_method_type;
/// same as recv_and_parse, but no more than limit is ever read from socket in total,
/// otherwise bad response is created and http_server::handle_response is returned, connection is closed.
virtual auto recv_and_parse(processing_context * context, std::size_t limit) const -> handle_method_type;
protected:
// http_request processing parts
virtual auto handle_start(processing_context * context) -> handle_method_type;
virtual auto handle_close(processing_context * context) -> handle_method_type;
virtual void handle_finish(processing_context * context);
virtual auto handle_ssl_configuration(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_start_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_continue_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_finish_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_shutdown(processing_context * context) -> handle_method_type;
virtual auto handle_request_headers_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_normal_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_filtered_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_discarded_request_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_normal_async_source_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_filtered_async_source_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_parsed_headers(processing_context * context) -> handle_method_type;
virtual auto handle_prefilters(processing_context * context) -> handle_method_type;
virtual auto handle_find_handler(processing_context * context) -> handle_method_type;
virtual auto handle_request_header_processing(processing_context * context) -> handle_method_type;
virtual auto handle_request_init_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_parsed_request(processing_context * context) -> handle_method_type;
virtual auto handle_processing(processing_context * context) -> handle_method_type;
virtual auto handle_processing_result(processing_context * context) -> handle_method_type;
virtual auto handle_postfilters(processing_context * context) -> handle_method_type;
virtual auto handle_response(processing_context * context) -> handle_method_type;
virtual auto handle_response_headers_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_headers_written(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_lstream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_stream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_stream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_async_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_async_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_written(processing_context * context) -> handle_method_type;
protected: // filtering
virtual void prepare_request_http_body_filtering(processing_context * context);
virtual void filter_request_http_body(processing_context * context);
virtual void prepare_response_http_body_filtering(processing_context * context);
virtual void filter_response_http_body(processing_context * context);
protected:
/// Acquires processing context, one of cached ones, or creates one if allowed. If exhausted - returns null
virtual auto acquire_context() -> processing_context *;
/// Release processing context after http request processed, this method should place this context to cache or delete it, if cache is full
virtual void release_context(processing_context * context);
/// Prepares processing context, called each time new http request should be processed.
/// Makes http handlers and filters snapshots if needed.
virtual void prepare_context(processing_context * context, const socket_streambuf & sock, bool newconn);
/// Called when processing context is created, default implementation does nothing
virtual void construct_context(processing_context * context);
/// Called when processing context is deleted, default implementation does nothing
virtual void destruct_context(processing_context * context);
/// Checks if there is pending context for this socket and returns it, otherwise returns new context via acquire_context()
/// Can return null if maximum number of contexts are created.
virtual auto acquire_context(socket_streambuf & sock) -> processing_context *;
/// Checks if there is pending context for this socket and release it, otherwise does nothing
virtual void release_context(socket_streambuf & sock);
/// Submits socket into internal socket_queue for waiting socket event(readable/writable).
/// When socket will become ready, processing will continue from where it stopped.
/// Should be called from server background thread
virtual void wait_connection(processing_context * context);
/// Submits connection into socket_queue, also sets m_keep_alive_timeout on socket. Should be called from server background thread
virtual void submit_connection(socket_streambuf sock);
/// Closes connection, logs, does some internal cleanup. Should be called from server background thread
virtual void close_connection(socket_streambuf sock);
/// Writes http response to socket, if errors occurs, logs it and returns false
virtual bool write_response(socket_streambuf & sock, const http_response & resp) const;
/// Postprocess ready http response, can be used to do some http headers machinery,
/// called after all http filter are handled, just before writting response.
/// Also called for special answers created via create_*_response.
/// Default implementation tweaks Close and Content-Length
virtual void postprocess_response(http_response & resp) const;
virtual void postprocess_response(processing_context * context) const;
/// Does some response checking, default implementation checks if request http body was fully parsed
/// NOTE: postprocess_response is called separately
virtual void check_response(processing_context * context) const;
/// Exception wrapper for handler.process(request), on exception returns create_internal_server_error_response(sock, request, ex)
virtual auto process_request(socket_streambuf & sock, const http_server_handler & handler, http_request & request) -> process_result;
/// Exception wrapper for getting result from ext::future<http_response>, on exception returns create_internal_server_error_response(sock, request, ex).
/// Also checks if future is cancelled or abandoned.
virtual auto process_ready_response(async_process_result result, socket_streambuf & sock, http_request & request) -> process_result;
/// Searches listener context by listener handle
virtual const listener_context & get_listener_context(socket_handle_type listener_handle) const;
/// Searches acceptable http handler, nullptr if not found
virtual const http_server_handler * find_handler(processing_context & context) const;
protected:
template <class Lock>
void process_tasks(Lock & lock);
template <class Lock, class Task>
auto submit_task(Lock & lk, Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>;
template <class Task>
auto submit_task(Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>;
/// submits task for running handle_* circuit
void submit_handler(handle_method_type next_method, processing_context * context);
template <class Lock>
void submit_handler(Lock & lk, handle_method_type next_method, processing_context * context);
protected:
/// obtains current config context, copying one if needed
config_context & current_config();
protected:
virtual auto do_add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx) -> ext::future<void>;
virtual void do_add_handler(std::unique_ptr<const http_server_handler> handler);
virtual void do_add_filter(ext::intrusive_ptr<http_filter_base> filter);
//virtual void do_remove_handler(std::string uri, std::vector<std::string> methods);
protected:
/// Logs http request, checks log levels
virtual void log_request(const http_request & request) const;
/// Logs http response, checks log levels
virtual void log_response(const http_response & response) const;
/// Formats error from error codes, in case of SSL error reads and formats all SSL errors from OpenSSL error queue
virtual std::string format_error(std::error_code errc) const;
/// logs read buffer in hex dump format
virtual void log_read_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const;
/// logs write buffer in hex dump format
virtual void log_write_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const;
/// parses Accept header and returns text/plain and text/html weights
static std::pair<double, double> parse_accept(const http_request & request);
/// Creates HTTP 400 BAD REQUEST answer
virtual http_response create_bad_request_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const;
/// Creates HTTP 503 Service Unavailable answer
virtual http_response create_server_busy_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const;
/// Creates HTTP 404 Not found answer
virtual http_response create_unknown_request_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 500 Internal Server Error answer, body = Request processing abandoned
virtual http_response create_processing_abondoned_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 404 Canceled, body = Request processing cancelled
virtual http_response create_processing_cancelled_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 500 Internal Server Error answer
virtual http_response create_internal_server_error_response(const socket_streambuf & sock, const http_request & request, std::exception * ex) const;
/// Creates HTTP 417 Expectation Failed answer
virtual http_response create_expectation_failed_response(const processing_context * context) const;
/// Creates HTTP 100 Continue response
virtual http_response create_continue_response(const processing_context * context) const;
public:
/// Adds http filter(both pre and post if applicable)
virtual void add_filter(ext::intrusive_ptr<http_filter_base> filter);
/// Adds listener with optional SSL configuration
virtual void add_listener(listener listener, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds opens listener with given backlog with optional SSL configuration
virtual void add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds and opens listener by port number with optional SSL configuration
virtual void add_listener(unsigned short port, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds http handler
virtual void add_handler(std::unique_ptr<const http_server_handler> handler);
/// Adds simple http handler
virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::string method, std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
/// Adds simple http handler
virtual void add_handler(std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
/// Adds simple http handler
virtual void add_handler(std::string method, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
public:
/// Configures processing context limits
virtual void set_processing_context_limits(std::size_t minimum, std::size_t maximum);
/// Sets http processing executor
virtual void set_processing_executor(std::shared_ptr<processing_executor> executor);
/// Sets http processing executor to given thread_pool
virtual void set_thread_pool(std::shared_ptr<ext::thread_pool> pool);
public:
void set_socket_timeout(duration_type timeout);
auto get_socket_timeout() const -> duration_type;
void set_keep_alive_timeout(duration_type timeout);
auto get_keep_alive_timeout() const -> duration_type;
public: // limits
void set_maximum_http_headers_size(std::size_t size);
auto get_maximum_http_headers_size() -> std::size_t;
void set_maximum_http_body_size(std::size_t size);
auto get_maximum_http_body_size() -> std::size_t;
void set_maximum_discarded_http_body_size(std::size_t size);
auto get_maximum_discarded_http_body_size() -> std::size_t;
public:
void set_logger(ext::library_logger::logger * logger) { m_logger = logger; m_sock_queue.set_logger(logger); }
auto get_logger() const noexcept { return m_logger; }
void set_request_logging_level(unsigned log_level) noexcept { m_request_logging_level = log_level; }
auto get_request_logging_level() const noexcept { return m_request_logging_level; }
void set_request_body_logging_level(unsigned log_level) noexcept { m_request_body_logging_level = log_level; }
auto get_request_body_logging_level() const noexcept { return m_request_body_logging_level; }
void set_read_buffer_logging_level(unsigned log_level) noexcept { m_read_buffer_logging_level = log_level; }
auto get_read_buffer_logging_level() const noexcept { return m_read_buffer_logging_level; }
void set_write_buffer_logging_level(unsigned log_level) noexcept { m_write_buffer_logging_level = log_level; }
auto get_write_buffer_logging_level() const noexcept { return m_write_buffer_logging_level; }
public:
http_server();
virtual ~http_server();
http_server(http_server && ) = delete;
http_server & operator =(http_server && ) = delete;
};
}
| 55.412598
| 191
| 0.772729
|
dmlys
|
54576dde40f92e2115e8513477ef33ee1b106a31
| 673
|
cpp
|
C++
|
campion-era/control.cpp/control.cpp
|
GeorgianBadita/algorithmic-problems
|
6b260050b7a1768b5e47a1d7d4ef7138a52db210
|
[
"MIT"
] | 1
|
2021-07-05T16:32:14.000Z
|
2021-07-05T16:32:14.000Z
|
campion-era/control.cpp/control.cpp
|
GeorgianBadita/algorithmic-problems
|
6b260050b7a1768b5e47a1d7d4ef7138a52db210
|
[
"MIT"
] | null | null | null |
campion-era/control.cpp/control.cpp
|
GeorgianBadita/algorithmic-problems
|
6b260050b7a1768b5e47a1d7d4ef7138a52db210
|
[
"MIT"
] | 1
|
2021-05-14T15:40:09.000Z
|
2021-05-14T15:40:09.000Z
|
#include<fstream>
using namespace std;
int x[100];
int main()
{
ifstream f("control.in");
ofstream g("control.out");
int ok,aux,i,n,v[101],ap=0,s=0;
f>>n;
for(i=1;i<=n;i++)
{
f>>v[i];
}
do
{
ok=1;
for(i=1;i<=n-1;i++)
{
if(v[i]>v[i+1])
{
ok=0;
aux=v[i];
v[i]=v[i+1];
v[i+1]=aux;
}
}
}while(ok==0);
for(i=1;i<=n;i++)
{
}
}
| 20.393939
| 40
| 0.2526
|
GeorgianBadita
|
546385e4c80aaa2894a8b262692e2894d57c4c14
| 5,774
|
cpp
|
C++
|
test/indenter/test_indenter_python.cpp
|
SammyEnigma/qutepart-cpp
|
3c5401c7d2856697171c4331099e2fa05ef0c49b
|
[
"WTFPL"
] | 5
|
2019-11-02T15:36:38.000Z
|
2021-11-01T21:17:32.000Z
|
test/indenter/test_indenter_python.cpp
|
SammyEnigma/qutepart-cpp
|
3c5401c7d2856697171c4331099e2fa05ef0c49b
|
[
"WTFPL"
] | 1
|
2021-02-11T23:11:00.000Z
|
2021-02-11T23:11:00.000Z
|
test/indenter/test_indenter_python.cpp
|
SammyEnigma/qutepart-cpp
|
3c5401c7d2856697171c4331099e2fa05ef0c49b
|
[
"WTFPL"
] | 3
|
2020-01-29T17:55:34.000Z
|
2021-12-23T11:38:41.000Z
|
#include <QtTest/QtTest>
#include "base_indenter_test.h"
class Test: public BaseTest
{
Q_OBJECT
private slots:
void python_data() {
addColumns();
QTest::newRow("dedent return")
<< "def some_function():\n"
" return"
<< std::make_pair(1, 8)
<< "\npass"
<< "def some_function():\n"
" return\n"
"pass";
QTest::newRow("dedent continue")
<< "while True:\n"
" continue"
<< std::make_pair(1, 10)
<< "\npass"
<< "while True:\n"
" continue\n"
"pass";
QTest::newRow("keep indent 1")
<< "def some_function(param, param2):\n"
" a = 5\n"
" b = 7"
<< std::make_pair(2, 7)
<< "\npass"
<< "def some_function(param, param2):\n"
" a = 5\n"
" b = 7\n"
" pass";
QTest::newRow("keep indent 2")
<< "class my_class():\n"
" def my_fun():\n"
" print \"Foo\"\n"
" print 3"
<< std::make_pair(3, 11)
<< "\npass"
<< "class my_class():\n"
" def my_fun():\n"
" print \"Foo\"\n"
" print 3\n"
" pass";
QTest::newRow("keep indent 3")
<< "while True:\n"
" returnFunc()\n"
" myVar = 3"
<< std::make_pair(2, 11)
<< "\npass"
<< "while True:\n"
" returnFunc()\n"
" myVar = 3\n"
" pass";
QTest::newRow("keep indent 4")
<< "def some_function():"
<< std::make_pair(0, 20)
<< "\npass\n\npass"
<< "def some_function():\n"
" pass\n"
"\n"
"pass";
QTest::newRow("dedent raise")
<< "try:\n"
" raise"
<< std::make_pair(1, 7)
<< "\nexcept:"
<< "try:\n"
" raise\n"
"except:";
QTest::newRow("indent colon 1")
<< "def some_function(param, param2):"
<< std::make_pair(0, 33)
<< "\npass"
<< "def some_function(param, param2):\n"
" pass";
QTest::newRow("indent colon 2")
<< "def some_function(1,\n"
" 2):"
<< std::make_pair(1, 21)
<< "\npass"
<< "def some_function(1,\n"
" 2):\n"
" pass";
QTest::newRow("indent colon 3") // do not indent colon if hanging indentation used
<< " a = {1:"
<< std::make_pair(0, 11)
<< "\nx"
<< " a = {1:\n"
" x";
QTest::newRow("dedent pass")
<< "def some_function():\n"
" pass"
<< std::make_pair(1, 6)
<< "\npass"
<< "def some_function():\n"
" pass\n"
"pass";
QTest::newRow("dedent return")
<< "def some_function():\n"
" return"
<< std::make_pair(1, 8)
<< "\npass"
<< "def some_function():\n"
" return\n"
"pass";
QTest::newRow("autoindent after empty")
<< "while True:\n"
" returnFunc()\n"
"\n"
" myVar = 3"
<< std::make_pair(2, 0)
<< "\n\tx"
<< "while True:\n"
" returnFunc()\n"
"\n"
" x\n"
" myVar = 3";
QTest::newRow("hanging indentation")
<< " return func (something,"
<< std::make_pair(0, 28)
<< "\nx"
<< " return func (something,\n"
" x";
QTest::newRow("hanging indentation 2")
<< " return func (\n"
" something,"
<< std::make_pair(1, 18)
<< "\nx"
<< " return func (\n"
" something,\n"
" x";
QTest::newRow("hanging indentation 3")
<< " a = func (\n"
" something)"
<< std::make_pair(1, 20)
<< "\nx"
<< " a = func (\n"
" something)\n"
" x";
QTest::newRow("hanging indentation 4")
<< " return func(a,\n"
" another_func(1,\n"
" 2),"
<< std::make_pair(2, 33)
<< "\nx"
<< " return func(a,\n"
" another_func(1,\n"
" 2),\n"
" x";
QTest::newRow("hanging indentation 5")
<< " return func(another_func(1,\n"
" 2),"
<< std::make_pair(1, 33)
<< "\nx"
<< " return func(another_func(1,\n"
" 2),\n"
" x";
}
void python() {
qpart.setIndentAlgorithm(Qutepart::INDENT_ALG_PYTHON);
qpart.setIndentWidth(2);
runDataDrivenTest();
}
};
QTEST_MAIN(Test)
#include "test_indenter_python.moc"
| 29.762887
| 91
| 0.336682
|
SammyEnigma
|
5463d9bb199bab6956d3a9ba142fbd22002a67a9
| 3,707
|
hpp
|
C++
|
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | 2
|
2016-09-15T22:29:46.000Z
|
2017-11-30T11:16:12.000Z
|
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
//
// file : pipeline_layout.hpp
// in : file:///home/tim/projects/hydra/hydra/vulkan/pipeline_layout.hpp
//
// created by : Timothée Feuillet
// date: Sun Aug 14 2016 13:43:28 GMT+0200 (CEST)
//
//
// Copyright (c) 2016 Timothée Feuillet
//
// 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 __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
#define __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
#include <vulkan/vulkan.h>
#include "../hydra_exception.hpp"
#include "device.hpp"
#include "descriptor_set_layout.hpp"
namespace neam
{
namespace hydra
{
namespace vk
{
/// \brief Wraps a VkPipelineLayout and its creation
/// \note This class is far from being complete
class pipeline_layout
{
public: // advanced
public:
/// \brief Create an empty pipeline layout
pipeline_layout(device &_dev)
: dev(_dev)
{
VkPipelineLayoutCreateInfo plci
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
0, nullptr,
0, nullptr
};
check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout));
}
/// \brief Create a pipeline layout (without push constants)
pipeline_layout(device &_dev, const std::vector<descriptor_set_layout *> &dsl_vct, const std::vector<VkPushConstantRange> &pc_range_vct = {})
: dev(_dev)
{
std::vector<VkDescriptorSetLayout> vk_dsl_vct;
vk_dsl_vct.reserve(dsl_vct.size());
for (descriptor_set_layout *it : dsl_vct)
vk_dsl_vct.push_back(it->_get_vk_descriptor_set_layout());
VkPipelineLayoutCreateInfo plci
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
(uint32_t)vk_dsl_vct.size(), vk_dsl_vct.data(),
(uint32_t)pc_range_vct.size(), pc_range_vct.data()
};
check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout));
}
~pipeline_layout()
{
if (vk_playout)
dev._vkDestroyPipelineLayout(vk_playout, nullptr);
}
public: // advanced
/// \brief Return the VkPipelineLayout
VkPipelineLayout _get_vk_pipeline_layout() const { return vk_playout; }
private:
device &dev;
VkPipelineLayout vk_playout = nullptr;
};
} // namespace vk
} // namespace hydra
} // namespace neam
#endif // __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
| 36.70297
| 151
| 0.671702
|
tim42
|
5463e2b117bb725c57e7be31f033e82e3e782a5d
| 30,428
|
cpp
|
C++
|
src/topology/TMR_TACSTopoCreator.cpp
|
peekwez/tmr
|
3ac41d8edd9b65c833f55940c451ee87019c5f55
|
[
"Apache-2.0"
] | null | null | null |
src/topology/TMR_TACSTopoCreator.cpp
|
peekwez/tmr
|
3ac41d8edd9b65c833f55940c451ee87019c5f55
|
[
"Apache-2.0"
] | null | null | null |
src/topology/TMR_TACSTopoCreator.cpp
|
peekwez/tmr
|
3ac41d8edd9b65c833f55940c451ee87019c5f55
|
[
"Apache-2.0"
] | null | null | null |
/*
This file is part of the package TMR for adaptive mesh refinement.
Copyright (C) 2015 Georgia Tech Research Corporation.
Additional copyright (C) 2015 Graeme Kennedy.
All rights reserved.
TMR is licensed under the Apache License, Version 2.0 (the "License");
you may not use this software 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 "TMR_TACSTopoCreator.h"
#include "TMROctStiffness.h"
#include "TMRQuadStiffness.h"
#include "FElibrary.h"
#include "Solid.h"
#include "PlaneStressQuad.h"
/*
Compare integers for sorting
*/
static int compare_integers( const void *a, const void *b ){
return (*(int*)a - *(int*)b);
}
/*
Set up a creator class for the given filter problem
*/
TMROctTACSTopoCreator::TMROctTACSTopoCreator( TMRBoundaryConditions *_bcs,
TMROctForest *_filter ):
TMROctTACSCreator(_bcs){
// Reference the filter
filter = _filter;
filter->incref();
int mpi_rank;
MPI_Comm comm = filter->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
// Create the nodes within the filter
filter->createNodes();
// Get the node range for the filter design variables
const int *filter_range;
filter->getOwnedNodeRange(&filter_range);
// Set up the variable map for the design variable numbers
int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank];
filter_map = new TACSVarMap(comm, num_filter_local);
filter_map->incref();
// Set the filter indices to NULL
filter_indices = NULL;
}
/*
Free the creator object
*/
TMROctTACSTopoCreator::~TMROctTACSTopoCreator(){
filter->decref();
filter_map->decref();
if (filter_indices){ filter_indices->decref(); }
}
// Get the underlying information about the filter
void TMROctTACSTopoCreator::getFilter( TMROctForest **_filter ){
*_filter = filter;
}
void TMROctTACSTopoCreator::getMap( TACSVarMap **_map ){
*_map = filter_map;
}
void TMROctTACSTopoCreator::getIndices( TACSBVecIndices **_indices ){
*_indices = filter_indices;
}
void TMROctTACSTopoCreator::computeWeights( const int mesh_order,
const double *knots,
TMROctant *node,
TMROctant *oct,
TMRIndexWeight *weights,
double *tmp ){
// Find the side length of the octant in the filter that contains
// the element octant
const int32_t h = 1 << (TMR_MAX_LEVEL - node->level);
const int32_t hoct = 1 << (TMR_MAX_LEVEL - oct->level);
// Compute the i, j, k location of the nod
const int i = node->info % mesh_order;
const int j = (node->info % (mesh_order*mesh_order))/mesh_order;
const int k = node->info/(mesh_order*mesh_order);
// Get the u/v/w values within the filter octant
double pt[3];
pt[0] = -1.0 + 2.0*((node->x % hoct) + 0.5*h*(1.0 + knots[i]))/hoct;
pt[1] = -1.0 + 2.0*((node->y % hoct) + 0.5*h*(1.0 + knots[j]))/hoct;
pt[2] = -1.0 + 2.0*((node->z % hoct) + 0.5*h*(1.0 + knots[k]))/hoct;
// Get the Lagrange shape functions
double *N = tmp;
filter->evalInterp(pt, N);
// Get the dependent node information for this mesh
const int *dep_ptr, *dep_conn;
const double *dep_weights;
filter->getDepNodeConn(&dep_ptr, &dep_conn, &dep_weights);
// Get the mesh order
const int order = filter->getMeshOrder();
// Get the connectivity
const int *conn;
filter->getNodeConn(&conn);
const int *c = &conn[oct->tag*order*order*order];
// Loop over the adjacent nodes within the filter
int nweights = 0;
for ( int kk = 0; kk < order; kk++ ){
for ( int jj = 0; jj < order; jj++ ){
for ( int ii = 0; ii < order; ii++ ){
// Set the weights
int offset = ii + jj*order + kk*order*order;
double weight = N[offset];
// Get the tag number
if (c[offset] >= 0){
weights[nweights].index = c[offset];
weights[nweights].weight = weight;
nweights++;
}
else {
int node = -c[offset]-1;
for ( int jp = dep_ptr[node]; jp < dep_ptr[node+1]; jp++ ){
weights[nweights].index = dep_conn[jp];
weights[nweights].weight = weight*dep_weights[jp];
nweights++;
}
}
}
}
}
// Sort and sum the array of weights - there are only 8 nodes
// per filter point at most
nweights = TMRIndexWeight::uniqueSort(weights, nweights);
}
/*
Create all of the elements for the topology optimization problem
*/
void TMROctTACSTopoCreator::createElements( int order,
TMROctForest *forest,
int num_elements,
TACSElement **elements ){
// Get the MPI communicator
int mpi_rank, mpi_size;
MPI_Comm comm = forest->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
MPI_Comm_size(comm, &mpi_size);
// Get the octants associated with the forest
TMROctantArray *octants;
forest->getOctants(&octants);
// Get the array of octants from the forest
int num_octs;
TMROctant *octs;
octants->getArray(&octs, &num_octs);
// Create a queue for the external octants
TMROctantQueue *queue = new TMROctantQueue();
// The number of weights/element
const int filter_order = filter->getMeshOrder();
const int nweights = filter_order*filter_order*filter_order;
// Allocate temp space
double *tmp = new double[ nweights ];
TMRIndexWeight *wtmp = new TMRIndexWeight[ nweights*filter_order*filter_order ];
// Allocate the weights for all of the local elements
TMRIndexWeight *weights = new TMRIndexWeight[ nweights*num_octs ];
// Fake the information as if we have a third-order and we are
// searching for the centeral node
const int node_info = 13;
const double node_knots[] = {-1.0, 0.0, 1.0};
const int node_order = 3;
for ( int i = 0; i < num_octs; i++ ){
// Get the original octant from the forest
TMROctant node = octs[i];
node.info = node_info;
// Find the enclosing central node
int mpi_owner = 0;
TMROctant *oct = filter->findEnclosing(node_order, node_knots,
&node, &mpi_owner);
if (!oct){
// Push the octant to the external queue. We will handle these
// cases seperately after a collective communication.
node.tag = mpi_owner;
queue->push(&node);
weights[nweights*i].index = -1;
}
else {
computeWeights(node_order, node_knots, &node,
oct, wtmp, tmp);
memcpy(&weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight));
}
}
// Create a list of octants that are external
TMROctantArray *nodes = queue->toArray();
delete queue;
// Distribute the nodes to the processors that own them
int use_tags = 1;
int *send_ptr, *recv_ptr;
TMROctantArray *dist_nodes =
filter->distributeOctants(nodes, use_tags, &send_ptr, &recv_ptr);
delete nodes;
// Get the external nodes that are local to this processor and
// compute their weights
int dist_size;
TMROctant *dist_array;
dist_nodes->getArray(&dist_array, &dist_size);
// Create the distributed weights
TMRIndexWeight *dist_weights = new TMRIndexWeight[ nweights*dist_size ];
for ( int i = 0; i < dist_size; i++ ){
TMROctant *oct = filter->findEnclosing(node_order, node_knots,
&dist_array[i]);
if (oct){
computeWeights(node_order, node_knots, &dist_array[i],
oct, wtmp, tmp);
memcpy(&dist_weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight));
}
else {
fprintf(stderr, "[%d] TMROctTACSTopoCreator: Node not found\n", mpi_rank);
}
}
// Free the temporary space
delete [] wtmp;
delete [] tmp;
// The distributed nodes are no longer required
delete dist_nodes;
// Compute the number of sends and recvs that were performed.
int nsends = 0, nrecvs = 0;
for ( int i = 0; i < mpi_size; i++ ){
if (i != mpi_rank){
if (send_ptr[i+1] - send_ptr[i] > 0){
nsends++;
}
if (recv_ptr[i+1] - recv_ptr[i] > 0){
nrecvs++;
}
}
}
// Now prepare to reverse the communication to distribute the
// weights back to the processors that need them. First allocate
// space for the requests
MPI_Request *send_request = new MPI_Request[ nrecvs ];
// Allocate space for the new weights
TMRIndexWeight *new_weights =
new TMRIndexWeight[ nweights*send_ptr[mpi_size] ];
// Loop over all the ranks and send
for ( int i = 0, j = 0; i < mpi_size; i++ ){
if (i != mpi_rank &&
recv_ptr[i+1] - recv_ptr[i] > 0){
// Post the send to the destination
int count = nweights*(recv_ptr[i+1] - recv_ptr[i]);
MPI_Isend(&dist_weights[nweights*recv_ptr[i]], count,
TMRIndexWeight_MPI_type,
i, 0, comm, &send_request[j]);
j++;
}
}
// Loop over the recieve calls
for ( int i = 0; i < mpi_size; i++ ){
if (i != mpi_rank &&
send_ptr[i+1] > send_ptr[i]){
int count = nweights*(send_ptr[i+1] - send_ptr[i]);
MPI_Recv(&new_weights[nweights*send_ptr[i]], count,
TMRIndexWeight_MPI_type,
i, 0, comm, MPI_STATUS_IGNORE);
}
}
// Wait for any remaining sends to complete
MPI_Waitall(nrecvs, send_request, MPI_STATUSES_IGNORE);
// Now place the weights back into their original locations
for ( int i = 0, j = 0; i < num_octs && j < send_ptr[mpi_size]; i++ ){
if (weights[nweights*i].index == -1){
memcpy(&weights[nweights*i], &new_weights[nweights*j],
nweights*sizeof(TMRIndexWeight));
j++;
}
}
delete [] new_weights;
delete [] send_request;
delete [] send_ptr;
delete [] recv_ptr;
delete [] dist_weights;
// The node numbers within the weights are global. Convert them to a
// local node ordering and create a list of the external node
// numbers referenced by the weights.
// Get the node range for the filter design variables
const int *filter_range;
filter->getOwnedNodeRange(&filter_range);
// The number of local nodes
int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank];
// Get the external numbers from the filter itself
const int *filter_ext;
int num_filter_ext = filter->getNodeNumbers(&filter_ext);
// Count up all the external nodes
int num_ext = 0;
int max_ext_nodes = nweights*num_octs + num_filter_ext;
int *ext_nodes = new int[ max_ext_nodes ];
// Add the external nodes from the filter
for ( int i = 0; i < num_filter_ext; i++ ){
int node = filter_ext[i];
if (node >= 0 &&
(node < filter_range[mpi_rank] ||
node >= filter_range[mpi_rank+1])){
ext_nodes[num_ext] = node;
num_ext++;
}
}
// Add the external nodes from the element-level connectivity
for ( int i = 0; i < nweights*num_octs; i++ ){
int node = weights[i].index;
if (node < filter_range[mpi_rank] ||
node >= filter_range[mpi_rank+1]){
ext_nodes[num_ext] = node;
num_ext++;
}
}
// Sort the external array of nodes
qsort(ext_nodes, num_ext, sizeof(int), compare_integers);
// Remove duplicates from the array
int len = 0;
for ( int i = 0; i < num_ext; i++, len++ ){
while ((i < num_ext-1) && (ext_nodes[i] == ext_nodes[i+1])){
i++;
}
if (i != len){
ext_nodes[len] = ext_nodes[i];
}
}
// Truncate the array and delete the old array
int num_ext_nodes = len;
int *ext_node_nums = new int[ len ];
memcpy(ext_node_nums, ext_nodes, len*sizeof(int));
delete [] ext_nodes;
// Set up the external filter indices for this filter. The indices
// objects steals the array for the external nodes.
filter_indices = new TACSBVecIndices(&ext_node_nums, num_ext_nodes);
filter_indices->incref();
filter_indices->setUpInverse();
// Scan through all of the weights and convert them to the local
// ordering
for ( int i = 0; i < nweights*num_octs; i++ ){
int node = weights[i].index;
if (node >= filter_range[mpi_rank] && node < filter_range[mpi_rank+1]){
node = node - filter_range[mpi_rank];
}
else {
node = num_filter_local + filter_indices->findIndex(node);
}
weights[i].index = node;
}
// Loop over the octants
octants->getArray(&octs, &num_octs);
for ( int i = 0; i < num_octs; i++ ){
// Allocate the stiffness object
elements[i] = createElement(order, &octs[i],
&weights[nweights*i], nweights);
}
delete [] weights;
}
/*
Set up a creator class for the given filter problem
*/
TMRQuadTACSTopoCreator::TMRQuadTACSTopoCreator( TMRBoundaryConditions *_bcs,
TMRQuadForest *_filter ):
TMRQuadTACSCreator(_bcs){
// Reference the filter
filter = _filter;
filter->incref();
int mpi_rank;
MPI_Comm comm = filter->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
// Create the nodes within the filter
filter->createNodes();
// Get the node range for the filter design variables
const int *filter_range;
filter->getOwnedNodeRange(&filter_range);
// Set up the variable map for the design variable numbers
int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank];
filter_map = new TACSVarMap(comm, num_filter_local);
filter_map->incref();
// Set the filter indices to NULL
filter_indices = NULL;
}
/*
Free the creator object
*/
TMRQuadTACSTopoCreator::~TMRQuadTACSTopoCreator(){
filter->decref();
filter_map->decref();
if (filter_indices){ filter_indices->decref(); }
}
// Get the underlying information about the problem
void TMRQuadTACSTopoCreator::getFilter( TMRQuadForest **_filter ){
*_filter = filter;
}
void TMRQuadTACSTopoCreator::getMap( TACSVarMap **_map ){
*_map = filter_map;
}
void TMRQuadTACSTopoCreator::getIndices( TACSBVecIndices **_indices ){
*_indices = filter_indices;
}
/*
Compute the weights associated with the given quadrant
*/
void TMRQuadTACSTopoCreator::computeWeights( const int mesh_order,
const double *knots,
TMRQuadrant *node,
TMRQuadrant *quad,
TMRIndexWeight *weights,
double *tmp, int sort ){
// Find the side length of the octant in the filter that contains
// the element octant
const int32_t h = 1 << (TMR_MAX_LEVEL - node->level);
const int32_t hquad = 1 << (TMR_MAX_LEVEL - quad->level);
// Compute the i, j, k location of the node
const int i = node->info % mesh_order;
const int j = node->info/mesh_order;
// Get the u/v values within the filter octant
double pt[3];
pt[0] = -1.0 + 2.0*((node->x % hquad) + 0.5*h*(1.0 + knots[i]))/hquad;
pt[1] = -1.0 + 2.0*((node->y % hquad) + 0.5*h*(1.0 + knots[j]))/hquad;
// Get the shape functions
double *N = tmp;
filter->evalInterp(pt, N);
// Get the dependent node information for this mesh
const int *dep_ptr, *dep_conn;
const double *dep_weights;
filter->getDepNodeConn(&dep_ptr, &dep_conn, &dep_weights);
// Get the mesh order
const int order = filter->getMeshOrder();
// Get the connectivity
const int *conn;
filter->getNodeConn(&conn);
const int *c = &conn[quad->tag*order*order];
// Loop over the adjacent nodes within the filter
int nweights = 0;
for ( int jj = 0; jj < order; jj++ ){
for ( int ii = 0; ii < order; ii++ ){
// Set the weights
int offset = ii + jj*order;
double weight = N[offset];
// Get the tag number
if (c[offset] >= 0){
weights[nweights].index = c[offset];
weights[nweights].weight = weight;
nweights++;
}
else {
int node = -c[offset]-1;
for ( int jp = dep_ptr[node]; jp < dep_ptr[node+1]; jp++ ){
weights[nweights].index = dep_conn[jp];
weights[nweights].weight = weight*dep_weights[jp];
nweights++;
}
}
}
}
if (sort){
// Sort and sum the array of weights - there are only 8 nodes
// per filter point at most
nweights = TMRIndexWeight::uniqueSort(weights, nweights);
}
}
/*
Create all of the elements for the topology optimization problem
*/
void TMRQuadTACSTopoCreator::createElements( int order,
TMRQuadForest *forest,
int num_elements,
TACSElement **elements ){
// Get the MPI communicator
int mpi_rank, mpi_size;
MPI_Comm comm = forest->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
MPI_Comm_size(comm, &mpi_size);
// Get the quadrants associated with the forest
TMRQuadrantArray *quadrants;
forest->getQuadrants(&quadrants);
// Get the array of quadrants from the forest
int num_quads;
TMRQuadrant *quads;
quadrants->getArray(&quads, &num_quads);
// Create a queue for the external octants
TMRQuadrantQueue *queue = new TMRQuadrantQueue();
// The number of weights/element
const int filter_order = filter->getMeshOrder();
const int nweights = filter_order*filter_order;
// Allocate temp space
double *tmp = new double[ nweights ];
TMRIndexWeight *wtmp = new TMRIndexWeight[ nweights*filter_order*filter_order ];
// Allocate the weights for all of the local elements
TMRIndexWeight *weights = new TMRIndexWeight[ nweights*num_quads ];
// Fake the information as if we have a third-order and we are
// searching for the centeral node
const int node_info = 4;
const double node_knots[] = {-1.0, 0.0, 1.0};
const int node_order = 3;
for ( int i = 0; i < num_quads; i++ ){
// Get the original quadrant from the forest
TMRQuadrant node = quads[i];
node.info = node_info;
// Find the central node
int mpi_owner = 0;
TMRQuadrant *quad = filter->findEnclosing(node_order, node_knots,
&node, &mpi_owner);
if (!quad){
// Push the quadrant to the external queue. We will handle these
// cases seperately after a collective communication.
node.tag = mpi_owner;
queue->push(&node);
weights[nweights*i].index = -1;
}
else {
computeWeights(node_order, node_knots, &node,
quad, wtmp, tmp);
memcpy(&weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight));
}
}
// Create a list of quadrants that are external
TMRQuadrantArray *nodes = queue->toArray();
delete queue;
// Distribute the nodes to the processors that own them
int use_tags = 1;
int *send_ptr, *recv_ptr;
TMRQuadrantArray *dist_nodes =
filter->distributeQuadrants(nodes, use_tags, &send_ptr, &recv_ptr);
delete nodes;
// Get the external nodes that are local to this processor and
// compute their weights
int dist_size;
TMRQuadrant *dist_array;
dist_nodes->getArray(&dist_array, &dist_size);
// Create the distributed weights
TMRIndexWeight *dist_weights = new TMRIndexWeight[ nweights*dist_size ];
for ( int i = 0; i < dist_size; i++ ){
TMRQuadrant *quad = filter->findEnclosing(node_order, node_knots,
&dist_array[i]);
if (quad){
computeWeights(node_order, node_knots, &dist_array[i],
quad, wtmp, tmp);
memcpy(&dist_weights[nweights*i], wtmp, nweights*sizeof(TMRIndexWeight));
}
}
// Free the tmporary space
delete [] wtmp;
delete [] tmp;
// The distributed nodes are no longer required
delete dist_nodes;
// Compute the number of sends and recvs that were performed.
int nsends = 0, nrecvs = 0;
for ( int i = 0; i < mpi_size; i++ ){
if (i != mpi_rank){
if (send_ptr[i+1] - send_ptr[i] > 0){
nsends++;
}
if (recv_ptr[i+1] - recv_ptr[i] > 0){
nrecvs++;
}
}
}
// Now prepare to reverse the communication to distribute the
// weights back to the processors that need them. First allocate
// space for the requests
MPI_Request *send_request = new MPI_Request[ nrecvs ];
// Allocate space for the new weights
TMRIndexWeight *new_weights =
new TMRIndexWeight[ nweights*send_ptr[mpi_size] ];
// Loop over all the ranks and send
for ( int i = 0, j = 0; i < mpi_size; i++ ){
if (i != mpi_rank &&
recv_ptr[i+1] - recv_ptr[i] > 0){
// Post the send to the destination
int count = nweights*(recv_ptr[i+1] - recv_ptr[i]);
MPI_Isend(&dist_weights[nweights*recv_ptr[i]], count,
TMRIndexWeight_MPI_type,
i, 0, comm, &send_request[j]);
j++;
}
}
// Loop over the recieve calls
for ( int i = 0; i < mpi_size; i++ ){
if (i != mpi_rank &&
send_ptr[i+1] > send_ptr[i]){
int count = nweights*(send_ptr[i+1] - send_ptr[i]);
MPI_Recv(&new_weights[nweights*send_ptr[i]], count,
TMRIndexWeight_MPI_type,
i, 0, comm, MPI_STATUS_IGNORE);
}
}
// Wait for any remaining sends to complete
MPI_Waitall(nrecvs, send_request, MPI_STATUSES_IGNORE);
// Now place the weights back into their original locations
for ( int i = 0, j = 0; i < num_quads && j < send_ptr[mpi_size]; i++ ){
if (weights[nweights*i].index == -1){
memcpy(&weights[nweights*i], &new_weights[nweights*j],
nweights*sizeof(TMRIndexWeight));
j++;
}
}
delete [] new_weights;
delete [] send_request;
delete [] send_ptr;
delete [] recv_ptr;
delete [] dist_weights;
// The node numbers within the weights are global. Convert them into
// a local node ordering and create a list of the external node
// numbers referenced by the weights.
// Get the node range for the filter design variables
const int *filter_range;
filter->getOwnedNodeRange(&filter_range);
// The number of local nodes
int num_filter_local = filter_range[mpi_rank+1] - filter_range[mpi_rank];
// Get the external numbers from the filter itself
const int *filter_ext;
int num_filter_ext = filter->getNodeNumbers(&filter_ext);
// Count up all the external nodes
int num_ext = 0;
int max_ext_nodes = nweights*num_quads + num_filter_ext;
int *ext_nodes = new int[ max_ext_nodes ];
// Add the external nodes from the filter
for ( int i = 0; i < num_filter_ext; i++ ){
int node = filter_ext[i];
if (node >= 0 &&
(node < filter_range[mpi_rank] ||
node >= filter_range[mpi_rank+1])){
ext_nodes[num_ext] = node;
num_ext++;
}
}
// Add the external nodes from the element-level connectivity
for ( int i = 0; i < nweights*num_quads; i++ ){
int node = weights[i].index;
if (node < filter_range[mpi_rank] ||
node >= filter_range[mpi_rank+1]){
ext_nodes[num_ext] = node;
num_ext++;
}
}
// Sort the external array of nodes
qsort(ext_nodes, num_ext, sizeof(int), compare_integers);
// Remove duplicates from the array
int len = 0;
for ( int i = 0; i < num_ext; i++, len++ ){
while ((i < num_ext-1) && (ext_nodes[i] == ext_nodes[i+1])){
i++;
}
if (i != len){
ext_nodes[len] = ext_nodes[i];
}
}
// Truncate the array and delete the old array
int num_ext_nodes = len;
int *ext_node_nums = new int[ len ];
memcpy(ext_node_nums, ext_nodes, len*sizeof(int));
delete [] ext_nodes;
// Set up the external filter indices for this filter. The indices
// objects steals the array for the external nodes.
filter_indices = new TACSBVecIndices(&ext_node_nums, num_ext_nodes);
filter_indices->incref();
filter_indices->setUpInverse();
// Scan through all of the weights and convert them to the local
// ordering
for ( int i = 0; i < nweights*num_quads; i++ ){
int node = weights[i].index;
if (node >= filter_range[mpi_rank] && node < filter_range[mpi_rank+1]){
node = node - filter_range[mpi_rank];
}
else {
node = num_filter_local + filter_indices->findIndex(node);
}
weights[i].index = node;
}
// Loop over the octants
quadrants->getArray(&quads, &num_quads);
for ( int i = 0; i < num_quads; i++ ){
// Allocate the stiffness object
elements[i] = createElement(order, &quads[i],
&weights[nweights*i], nweights);
}
// Free the weights
delete [] weights;
}
/*
Set up a creator class for the given forest problem
*/
TMROctConformTACSTopoCreator::TMROctConformTACSTopoCreator( TMRBoundaryConditions *_bcs,
TMROctForest *_forest,
int order,
TMRInterpolationType interp_type ):
TMROctTACSCreator(_bcs){
// Use the forest as the filter in these cases
if (order < 0 ||
(order == _forest->getMeshOrder() &&
interp_type == _forest->getInterpType())){
filter = _forest;
}
else {
filter = _forest->duplicate();
order = filter->getMeshOrder()-1;
if (order < 2){
order = 2;
}
filter->setMeshOrder(order, interp_type);
}
filter->incref();
// Create the nodes within the filter
filter->createNodes();
}
/*
Free the creator object
*/
TMROctConformTACSTopoCreator::~TMROctConformTACSTopoCreator(){
filter->decref();
}
// Get the underlying information about the problem
void TMROctConformTACSTopoCreator::getFilter( TMROctForest **_filter ){
*_filter = filter;
}
/*
Create all of the elements for the topology optimization problem
*/
void TMROctConformTACSTopoCreator::createElements( int order,
TMROctForest *forest,
int num_elements,
TACSElement **elements ){
// Get the MPI communicator
int mpi_rank, mpi_size;
MPI_Comm comm = forest->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
MPI_Comm_size(comm, &mpi_size);
// Get the quadrants associated with the forest
TMROctantArray *octants;
forest->getOctants(&octants);
// Get the array of quadrants from the forest
int num_octs;
TMROctant *octs;
octants->getArray(&octs, &num_octs);
// The number of weights/element
const int filter_order = filter->getMeshOrder();
const int nweights = filter_order*filter_order*filter_order;
// Allocate the weights for all of the local elements
int *index = new int[ nweights*num_octs ];
// Loop over the nodes and convert to the local numbering scheme
const int *conn;
filter->getNodeConn(&conn);
// Get the local node index on this processor
for ( int i = 0; i < nweights*num_octs; i++ ){
index[i] = filter->getLocalNodeNumber(conn[i]);
}
// Loop over the octants
octants->getArray(&octs, &num_octs);
for ( int i = 0; i < num_octs; i++ ){
// Allocate the stiffness object
elements[i] = createElement(order, &octs[i],
&index[nweights*i], nweights,
filter);
}
}
/*
Set up a creator class for the given forest problem
*/
TMRQuadConformTACSTopoCreator::TMRQuadConformTACSTopoCreator( TMRBoundaryConditions *_bcs,
TMRQuadForest *_forest,
int order,
TMRInterpolationType interp_type ):
TMRQuadTACSCreator(_bcs){
// Create and reference the filter
if (order < 0 ||
(order == _forest->getMeshOrder() &&
interp_type == _forest->getInterpType())){
filter = _forest;
}
else {
filter = _forest->duplicate();
order = filter->getMeshOrder()-1;
if (order < 2){
order = 2;
}
filter->setMeshOrder(order, interp_type);
}
filter->incref();
// Create the nodes within the filter
filter->createNodes();
}
/*
Free the creator object
*/
TMRQuadConformTACSTopoCreator::~TMRQuadConformTACSTopoCreator(){
filter->decref();
}
// Get the underlying information about the problem
void TMRQuadConformTACSTopoCreator::getFilter( TMRQuadForest **_filter ){
*_filter = filter;
}
/*
Create all of the elements for the topology optimization problem
*/
void TMRQuadConformTACSTopoCreator::createElements( int order,
TMRQuadForest *forest,
int num_elements,
TACSElement **elements ){
// Get the MPI communicator
int mpi_rank, mpi_size;
MPI_Comm comm = forest->getMPIComm();
MPI_Comm_rank(comm, &mpi_rank);
MPI_Comm_size(comm, &mpi_size);
// Get the quadrants associated with the forest
TMRQuadrantArray *quadrants;
forest->getQuadrants(&quadrants);
// Get the array of quadrants from the forest
int num_quads;
TMRQuadrant *quads;
quadrants->getArray(&quads, &num_quads);
// The number of weights/element
const int filter_order = filter->getMeshOrder();
const int nweights = filter_order*filter_order;
// Allocate the weights for all of the local elements
int *index = new int[ nweights*num_quads ];
// Loop over the nodes and convert to the local numbering scheme
const int *conn;
filter->getNodeConn(&conn);
// Get the local node index on this processor
for ( int i = 0; i < nweights*num_quads; i++ ){
index[i] = filter->getLocalNodeNumber(conn[i]);
}
// Loop over the octants
quadrants->getArray(&quads, &num_quads);
for ( int i = 0; i < num_quads; i++ ){
// Allocate the stiffness object
elements[i] = createElement(order, &quads[i],
&index[nweights*i], nweights,
filter);
}
}
| 31.401445
| 97
| 0.627021
|
peekwez
|
546a11c1b2fb0ea64885541a70df951ecaf43844
| 1,136
|
hpp
|
C++
|
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <exception>
#include <algorithm>
#include <fstream>
#include <chrono>
#include <time.h> //#include <stdio.h>
namespace stool
{
class NaiveAlgorithms
{
template <typename INDEX>
static std::vector<INDEX> naive_sa(std::string &text)
{
std::vector<INDEX> sa;
INDEX n = text.size();
sa.resize(n);
for (INDEX i = 0; i < n; i++)
{
sa[i] = i;
}
std::sort(sa.begin(), sa.end(),
[&](const INDEX &x, const INDEX &y) {
INDEX size = x < y ? text.size() - y : text.size() - x;
for (INDEX i = 0; i < size; i++)
{
if ((uint8_t)text[x + i] != (uint8_t)text[y + i])
{
return (uint8_t)text[x + i] < (uint8_t)text[y + i];
}
}
return x <= y ? false : true;
});
return sa;
}
};
} // namespace stool
| 27.047619
| 81
| 0.43662
|
TNishimoto
|
54720cd912f3adf5ecc237fbb8e1ef36829439c1
| 773
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_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_EngramEntry_Toilet_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C
// 0x0000 (0x0090 - 0x0090)
class UEngramEntry_Toilet_C : public UPrimalEngramEntry
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C");
return ptr;
}
void ExecuteUbergraph_EngramEntry_Toilet(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 19.820513
| 106
| 0.626132
|
2bite
|
5472d4010d1eaeaf62637e439bd939e07cee465d
| 28,590
|
cpp
|
C++
|
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
//
// Created by Philip Smith on 10/17/2020.
//
#include <engine/Renderer.h>
#include <engine/OrbitCam.h>
#include <engine/InstanceList.h>
#include <engine/mesh/Mesh.h>
#include <engine/sprite/ShapeSprite.h>
#include <engine/sprite/TextSprite.h>
#include <engine/sprite/TextureSprite.h>
#include <fmt/format.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <iostream>
#include <utils/file_util.h>
namespace engine {
Renderer::Renderer(entt::registry& registry) {
m_context_entity = registry.create();
registry.emplace<RenderContext>(m_context_entity);
}
bool Renderer::init(entt::registry ®istry) {
// init config
auto& context = registry.get<RenderContext>(m_context_entity);
context.screen_width = 800;
context.screen_height = 600;
context.fovy = 45.0f;
context.z_near = 0.1f;
context.z_far = 10000.0f;
json requested_textures;
json requested_fonts;
try {
// load override from config file if available
auto config_json = utils::file::read_json_file("../res/renderer.json");
if (config_json.contains("width"))
context.screen_width = config_json["width"];
if (config_json.contains("height"))
context.screen_height = config_json["height"];
if(config_json.contains("fovy"))
context.fovy = config_json["fovy"];
if(config_json.contains("z_near"))
context.z_near = config_json["z_near"];
if(config_json.contains("z_far"))
context.z_far = config_json["z_far"];
if(config_json.contains("textures"))
requested_textures = config_json["textures"];
if(config_json.contains("fonts"))
requested_fonts = config_json["fonts"];
} catch (nlohmann::detail::parse_error& e) {
std::cout << "Error reading config file: " << e.what() << std::endl;
}
//init subsystems
if(!init_glfw()) {
std::cerr << "Failed to init GLFW" << std::endl;
return false;
}
if(!init_window(context)) {
std::cerr << "Failed to init window" << std::endl;
return false;
}
if(!init_glew()) {
std::cerr << "Failed to init glew" << std::endl;
return false;
}
if(!init_shaders(context)) {
std::cerr << "Failed to init shaders" << std::endl;
return false;
}
if(!init_fonts(requested_fonts)) {
std::cerr << "Failed to init fonts" << std::endl;
return false;
}
// cull triangles facing away from camera
glEnable(GL_CULL_FACE);
// enable depth buffer
glEnable(GL_DEPTH_TEST);
// background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// load textures from config
for(auto info: requested_textures) {
std::string path = info["filepath"];
std::string name = info["name"];
std::cout << "Loading texture '" << name << "' at '" << path << "'" << std::endl;
m_loaded_textures.insert({name, utils::file::read_png_file_to_texture(path)});
}
registry.on_construct<Mesh>().connect<&load_mesh>();
registry.on_construct<ShapeSprite>().connect<&load_shape_sprite>();
registry.on_construct<TextureSprite>().connect<&Renderer::load_texture_sprite>(this);
registry.on_construct<TextSprite>().connect<&Renderer::load_text_sprite>();
registry.on_update<Mesh>().connect<&update_mesh>();
registry.on_update<ShapeSprite>().connect<&update_shape_sprite>();
registry.on_update<TextureSprite>().connect<&Renderer::update_texture_sprite>(this);
registry.on_update<TextSprite>().connect<&Renderer::update_text_sprite>( );
registry.on_destroy<VertexArrayObject>().connect<&destroy_vao>();
registry.on_destroy<InstanceList>().connect<&destroy_instances>();
return true;
}
bool Renderer::init_glfw() {
if (!glfwInit())
return false;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
return true;
}
bool Renderer::init_glew() {
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
glfwTerminate();
return false;
}
return true;
}
bool Renderer::init_fonts(const nlohmann::json& fonts) {
FT_Library ft;
if(FT_Init_FreeType(&ft)) {
std::cerr << "Could not initialize FreeType library" << std::endl;
return false;
}
// enable blending for text transparency
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for(auto font: fonts) {
auto glyphs = load_font(ft, font["path"], font["size"]);
if(glyphs.empty())
std::cerr << "Could not initialize font from '" << font["path"] << "'" << std::endl;
else
m_loaded_fonts[font["name"]] = glyphs;
}
FT_Done_FreeType(ft);
return true;
}
bool Renderer::init_window(RenderContext& context) {
// Open a window and create its OpenGL context
context.window = glfwCreateWindow(context.screen_width, context.screen_height, "Civil War", nullptr, nullptr);
if (context.window == nullptr) {
std::cerr << "Failed to open GLFW window" << std::endl;
glfwTerminate();
return false;
}
glfwMakeContextCurrent(context.window);
return true;
}
bool Renderer::init_shaders(RenderContext& context) {
auto color_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/color_vert.glsl");
auto color_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/color_vert2d.glsl");
auto color_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/color_frag.glsl");
auto tex_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/tex_vert.glsl");
auto tex_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/tex_vert2d.glsl");
auto tex_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/tex_frag.glsl");
auto text_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/text_vert.glsl");
auto text_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/text_frag.glsl");
try {
context.color_shader2d = load_shader(color_vshader_src2d.c_str(), color_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "2d color shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.color_shader3d = load_shader(color_vshader_src.c_str(), color_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "3d color shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.tex_shader2d = load_shader(tex_vshader_src2d.c_str(), tex_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "2d texture shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.tex_shader3d = load_shader(tex_vshader_src.c_str(), tex_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "3d texture shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.text_shader = load_shader(text_vshader_src.c_str(), text_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "Text shader failed to init: " << e.what() << std::endl;
return false;
}
return true;
}
void Renderer::load_mesh(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec4 = sizeof(glm::vec4);
auto sizeof_vec3 = sizeof(glm::vec3);
auto& mesh = registry.get<Mesh>(entity);
// setup vertex array object
glGenVertexArrays(1, &mesh.vao);
glBindVertexArray(mesh.vao);
// verts
glGenBuffers(1, &mesh.vbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// colors
glGenBuffers(1, &mesh.cbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &mesh.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0],
GL_STATIC_DRAW);
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
mesh.num_indices = mesh.indices.size();
registry.emplace<InstanceList>(entity, ibo);
glBindVertexArray(0);
}
void Renderer::load_shape_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec4 = sizeof(glm::vec4);
auto& sprite = registry.get<ShapeSprite>(entity);
// setup vertex array object
glGenVertexArrays(1, &sprite.vao);
glBindVertexArray(sprite.vao);
// verts
glGenBuffers(1, &sprite.vbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// colors
glGenBuffers(1, &sprite.cbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &sprite.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glBindVertexArray(0);
sprite.num_indices = sprite.indices.size();
registry.emplace<InstanceList>(entity, ibo);
}
void Renderer::load_texture_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec2 = sizeof(glm::vec2);
auto sizeof_vec4 = sizeof(glm::vec4);
auto& sprite = registry.get<TextureSprite>(entity);
// setup vertex array object
glGenVertexArrays(1, &sprite.vao);
glBindVertexArray(sprite.vao);
// verts
glGenBuffers(1, &sprite.vbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// uvs
glGenBuffers(1, &sprite.tex_uvs);
glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &sprite.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// texture sampler
sprite.tex_id = m_loaded_textures[sprite.name];
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glBindVertexArray(0);
sprite.num_indices = sprite.indices.size();
registry.emplace<InstanceList>(entity, ibo);
}
void Renderer::load_text_sprite(entt::registry ®istry, entt::entity entity) {
auto& sprite = registry.get<TextSprite>(entity);
glGenVertexArrays(1, &sprite.vao);
glGenBuffers(1, &sprite.vbo);
glBindVertexArray(sprite.vao);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, nullptr, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Renderer::update_mesh(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec3 = sizeof(glm::vec3);
auto& mesh = registry.get<Mesh>(entity);
glBindVertexArray(mesh.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW);
// colors
glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Renderer::update_shape_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec3 = sizeof(glm::vec3);
auto sizeof_vec2 = sizeof(glm::vec2);
auto& sprite = registry.get<ShapeSprite>(entity);
glBindVertexArray(sprite.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
// colors
glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Renderer::update_texture_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec2 = sizeof(glm::vec2);
auto& sprite = registry.get<TextureSprite>(entity);
glBindVertexArray(sprite.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
// uvs
glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// texture sampler
sprite.tex_id = m_loaded_textures[sprite.name];
glBindVertexArray(0);
}
void Renderer::update_text_sprite(entt::registry ®istry, entt::entity entity) {}
void Renderer::destroy_vao(entt::registry ®istry, entt::entity entity) {
auto vao = registry.get<VertexArrayObject>(entity);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
if(vao.vao)
glDeleteVertexArrays(1, &vao.vao);
if(vao.vbo)
glDeleteBuffers(1, &vao.vbo);
if(vao.ebo)
glDeleteBuffers(1, &vao.ebo);
if(vao.cbo)
glDeleteBuffers(1, &vao.cbo);
if(vao.tex_id)
glDeleteTextures(1, &vao.tex_id);
if(vao.tex_uvs)
glDeleteBuffers(1, &vao.tex_uvs);
}
void Renderer::destroy_instances(entt::registry ®istry, entt::entity entity) {
auto instances = registry.get<InstanceList>(entity);
if(instances.id)
glDeleteBuffers(1, &instances.id);
}
void Renderer::render(entt::registry ®istry, const Camera::Ptr& camera) {
const auto& ctx = registry.get<RenderContext>(m_context_entity);
glm::mat4 vp;
// 3D rendering
if(camera != nullptr) {
vp = glm::perspective(ctx.fovy, ctx.screen_width / ctx.screen_height, ctx.z_near, ctx.z_far) * camera->get_view();
glUseProgram(ctx.color_shader3d);
glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader3d, "VP"), 1, GL_FALSE, &vp[0][0]);
auto view3d = registry.view<Mesh, InstanceList>();
for (const auto &entity: view3d) {
auto[mesh, ilist] = view3d.get(entity);
if (mesh.visible) {
glBindVertexArray(mesh.vao);
glDrawElementsInstanced(ilist.render_strategy, mesh.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
}
}
}
// 2D rendering (TODO: Add occlusion culling to prevent drawing 3D entities that are covered by 2D elements)
vp = glm::ortho(0.f, ctx.screen_width, ctx.screen_height, 0.f);
glUseProgram(ctx.color_shader2d);
glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]);
auto color_view = registry.view<ShapeSprite, InstanceList>();
for(const auto &entity: color_view) {
auto [sprite, ilist] = color_view.get(entity);
if(sprite.visible) {
glBindVertexArray(sprite.vao);
glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
}
}
// texture rendering
glUseProgram(ctx.tex_shader2d);
glUniformMatrix4fv(glGetUniformLocation(ctx.tex_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]);
glUniform1i(glGetUniformLocation(ctx.tex_shader2d, "texSampler"), 0);
auto tex_view = registry.view<TextureSprite, InstanceList>();
for(const auto &entity: tex_view) {
auto [sprite, ilist] = tex_view.get(entity);
if(sprite.visible) {
glBindVertexArray(sprite.vao);
glBindTexture(GL_TEXTURE_2D, sprite.tex_id);
glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
}
// text rendering
glUseProgram(ctx.text_shader);
glUniformMatrix4fv(glGetUniformLocation(ctx.text_shader, "VP"), 1, GL_FALSE, &vp[0][0]);
glUniform1i(glGetUniformLocation(ctx.text_shader, "texSampler"), 0);
auto text_view = registry.view<TextSprite>();
for(const auto &entity: text_view) {
auto [sprite] = text_view.get(entity);
if(sprite.visible) {
if(!m_loaded_fonts.contains(sprite.font))
std::cerr << "Can't render sprite with unloaded font '" << sprite.font << "'" << std::endl;
else {
glUniform3f(glGetUniformLocation(ctx.text_shader, "textColor"),
sprite.color.x, sprite.color.y, sprite.color.z);
auto x = sprite.x;
for(std::string::const_iterator c = sprite.text.begin(); c != sprite.text.end(); c++) {
if(!m_loaded_fonts[sprite.font].contains(*c)) {
std::cerr << "Todo: add 404 texture. Error on '" << *c << "'"<< std::endl;
continue;
}
auto glyph = m_loaded_fonts[sprite.font][*c];
float xpos = x + glyph.bearing.x * sprite.scale;
float ypos = sprite.y - (glyph.size.y - glyph.bearing.y) * sprite.scale;
float w = glyph.size.x * sprite.scale;
float h = glyph.size.y * sprite.scale;
// update VBO for each character
float vertices[6][4] = {
{ xpos, ypos - h, 0.0f, 0.0f },
{ xpos, ypos, 0.0f, 1.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos, ypos - h, 0.0f, 0.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos + w, ypos - h, 1.0f, 0.0f }
};
glBindVertexArray(sprite.vao);
// render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, glyph.tex_id);
// update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// now advance cursors for next glyph (note that advance is number of 1/64 pixels)
x += (glyph.advance >> 6) * sprite.scale; // bitshift by 6 to get value in pixels (2^6 = 64)
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
}
}
}
glUseProgram(0);
}
void Renderer::cleanup(entt::registry ®istry) {
const auto& ctx = registry.get<RenderContext>(m_context_entity);
glDeleteProgram(ctx.color_shader2d);
glDeleteProgram(ctx.color_shader3d);
glDeleteProgram(ctx.tex_shader2d);
glDeleteProgram(ctx.tex_shader3d);
glDeleteProgram(ctx.text_shader);
glfwTerminate();
}
const RenderContext& Renderer::get_context(entt::registry& registry) const {
return registry.get<RenderContext>(m_context_entity);
}
GLuint Renderer::load_shader(const char* vertex_source, const char* frag_source) {
int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_source, nullptr);
glCompileShader(vertex_shader);
int success;
char infoLog[512];
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertex_shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error on vertex compilation ", infoLog);
throw std::runtime_error(message.c_str());
}
int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &frag_source, nullptr);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragment_shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error on fragment compilation ", infoLog);
throw std::runtime_error(message.c_str());
}
auto shader = glCreateProgram();
glAttachShader(shader, vertex_shader);
glAttachShader(shader, fragment_shader);
glLinkProgram(shader);
glValidateProgram(shader);
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error linking program ", infoLog);
throw std::runtime_error(message.c_str());
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return shader;
}
std::map<unsigned long, Renderer::Glyph> Renderer::load_font(FT_Library ft,
const std::string& fontfile,
unsigned int font_size,
const std::string& text) {
std::cout << "Loading font at '" << fontfile << "'" << std::endl;
FT_Face face;
if(FT_New_Face(ft, fontfile.c_str(), 0, &face)) {
std::cerr << "Could not initialize font from file at " << fontfile << std::endl;
FT_Done_Face(face);
return {};
}
// set size to load glyphs as
FT_Set_Pixel_Sizes(face, 0, font_size);
// disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
std::map<unsigned long, Glyph> glyphs;
for (unsigned char c: text) {
if(glyphs.contains(c))
continue;
if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
std::cout << "ERROR::FREETYTPE: Failed to load Glyph '" << c << "'" << std::endl;
continue;
}
// generate texture
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Glyph glyph = {
texture,
glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
static_cast<unsigned int>(face->glyph->advance.x)
};
glyphs.insert({c, glyph});
}
glBindTexture(GL_TEXTURE_2D, 0);
// destroy FreeType once we're finished
FT_Done_Face(face);
return glyphs;
}
} // namespace engine
| 42.863568
| 123
| 0.619203
|
smithy545
|
547358039612061aa8526099823f2a38d461fac8
| 11,458
|
cpp
|
C++
|
src/common/backend/utils/adt/oid.cpp
|
opengauss-mirror/openGauss-graph
|
6beb138fd00abdbfddc999919f90371522118008
|
[
"MulanPSL-1.0"
] | 360
|
2020-06-30T14:47:34.000Z
|
2022-03-31T15:21:53.000Z
|
src/common/backend/utils/adt/oid.cpp
|
opengauss-mirror/openGauss-graph
|
6beb138fd00abdbfddc999919f90371522118008
|
[
"MulanPSL-1.0"
] | 4
|
2020-06-30T15:09:16.000Z
|
2020-07-14T06:20:03.000Z
|
src/common/backend/utils/adt/oid.cpp
|
opengauss-mirror/openGauss-graph
|
6beb138fd00abdbfddc999919f90371522118008
|
[
"MulanPSL-1.0"
] | 133
|
2020-06-30T14:47:36.000Z
|
2022-03-25T15:29:00.000Z
|
/* -------------------------------------------------------------------------
*
* oid.c
* Functions for the built-in type Oid ... also oidvector.
*
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/oid.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include <limits.h>
#include "catalog/pg_type.h"
#include "libpq/pqformat.h"
#include "utils/array.h"
#include "utils/builtins.h"
#define OidVectorSize(n) (offsetof(oidvector, values) + (n) * sizeof(Oid))
/*****************************************************************************
* USER I/O ROUTINES *
*****************************************************************************/
static Oid oidin_subr(const char* s, char** endloc)
{
unsigned long cvt;
char* endptr = NULL;
Oid result;
if (*s == '\0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s)));
errno = 0;
cvt = strtoul(s, &endptr, 10);
/*
* strtoul() normally only sets ERANGE. On some systems it also may set
* EINVAL, which simply means it couldn't parse the input string. This is
* handled by the second "if" consistent across platforms.
*/
if (errno && errno != ERANGE && errno != EINVAL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s)));
if (endptr == s && *s != '\0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s)));
if (errno == ERANGE)
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("value \"%s\" is out of range for type oid", s)));
if (endloc != NULL) {
/* caller wants to deal with rest of string */
*endloc = endptr;
} else {
/* allow only whitespace after number */
while (*endptr && isspace((unsigned char)*endptr))
endptr++;
if (*endptr)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for type oid: \"%s\"", s)));
}
result = (Oid)cvt;
/*
* Cope with possibility that unsigned long is wider than Oid, in which
* case strtoul will not raise an error for some values that are out of
* the range of Oid.
*
* For backwards compatibility, we want to accept inputs that are given
* with a minus sign, so allow the input value if it matches after either
* signed or unsigned extension to long.
*
* To ensure consistent results on 32-bit and 64-bit platforms, make sure
* the error message is the same as if strtoul() had returned ERANGE.
*/
#if OID_MAX != ULONG_MAX
if (cvt != (unsigned long)result && cvt != (unsigned long)((int)result))
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("value \"%s\" is out of range for type oid", s)));
#endif
return result;
}
Datum oidin(PG_FUNCTION_ARGS)
{
char* s = PG_GETARG_CSTRING(0);
Oid result;
result = oidin_subr(s, NULL);
PG_RETURN_OID(result);
}
Datum oidout(PG_FUNCTION_ARGS)
{
Oid o = PG_GETARG_OID(0);
const int data_len = 12;
char* result = (char*)palloc(data_len);
errno_t ss_rc = snprintf_s(result, data_len, data_len - 1, "%u", o);
securec_check_ss(ss_rc, "\0", "\0");
PG_RETURN_CSTRING(result);
}
/*
* oidrecv - converts external binary format to oid
*/
Datum oidrecv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
PG_RETURN_OID((Oid)pq_getmsgint(buf, sizeof(Oid)));
}
/*
* oidsend - converts oid to binary format
*/
Datum oidsend(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
StringInfoData buf;
pq_begintypsend(&buf);
pq_sendint32(&buf, arg1);
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}
/*
* construct oidvector given a raw array of Oids
*
* If oids is NULL then caller must fill values[] afterward
*/
oidvector* buildoidvector(const Oid* oids, int n)
{
oidvector* result = NULL;
result = (oidvector*)palloc0(OidVectorSize(n));
if (n > 0 && oids) {
errno_t ss_rc = memcpy_s(result->values, n * sizeof(Oid), oids, n * sizeof(Oid));
securec_check(ss_rc, "\0", "\0");
}
/*
* Attach standard array header. For historical reasons, we set the index
* lower bound to 0 not 1.
*/
SET_VARSIZE(result, OidVectorSize(n));
result->ndim = 1;
result->dataoffset = 0; /* never any nulls */
result->elemtype = OIDOID;
result->dim1 = n;
result->lbound1 = 0;
return result;
}
#define OID_MAX_NUM 8192
/*
* oidvectorin - converts "num num ..." to internal form
*/
Datum oidvectorin(PG_FUNCTION_ARGS)
{
char* oidString = PG_GETARG_CSTRING(0);
oidvector* result = NULL;
int n;
result = (oidvector*)palloc0(OidVectorSize(OID_MAX_NUM));
for (n = 0; n < OID_MAX_NUM; n++) {
while (*oidString && isspace((unsigned char)*oidString))
oidString++;
if (*oidString == '\0')
break;
result->values[n] = oidin_subr(oidString, &oidString);
}
while (*oidString && isspace((unsigned char)*oidString))
oidString++;
if (*oidString)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("oidvector has too many elements")));
SET_VARSIZE(result, OidVectorSize(n));
result->ndim = 1;
result->dataoffset = 0; /* never any nulls */
result->elemtype = OIDOID;
result->dim1 = n;
result->lbound1 = 0;
PG_RETURN_POINTER(result);
}
/*
* oidvectorout - converts internal form to "num num ..."
*/
Datum oidvectorout(PG_FUNCTION_ARGS)
{
Datum oid_array_datum = PG_GETARG_DATUM(0);
oidvector* oidArray = (oidvector*)PG_DETOAST_DATUM(oid_array_datum);
int num, nnums = oidArray->dim1;
char* rp = NULL;
char* result = NULL;
/* assumes sign, 10 digits, ' ' */
rp = result = (char*)palloc(nnums * 12 + 1);
int postition = 0;
for (num = 0; num < nnums; num++) {
if (num != 0) {
*rp++ = ' ';
postition++;
}
errno_t ss_rc = sprintf_s(rp, nnums * 12 + 1 - postition, "%u", oidArray->values[num]);
securec_check_ss(ss_rc, "\0", "\0");
while (*++rp != '\0')
postition++;
}
*rp = '\0';
if (oidArray != (oidvector*)DatumGetPointer(oid_array_datum))
pfree_ext(oidArray);
PG_RETURN_CSTRING(result);
}
/*
* oidvectorrecv - converts external binary format to oidvector
*/
Datum oidvectorrecv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo)PG_GETARG_POINTER(0);
FunctionCallInfoData locfcinfo;
oidvector* result = NULL;
/*
* Normally one would call array_recv() using DirectFunctionCall3, but
* that does not work since array_recv wants to cache some data using
* fcinfo->flinfo->fn_extra. So we need to pass it our own flinfo
* parameter.
*/
InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 3, InvalidOid, NULL, NULL);
locfcinfo.arg[0] = PointerGetDatum(buf);
locfcinfo.arg[1] = ObjectIdGetDatum(OIDOID);
locfcinfo.arg[2] = Int32GetDatum(-1);
locfcinfo.argnull[0] = false;
locfcinfo.argnull[1] = false;
locfcinfo.argnull[2] = false;
result = (oidvector*)DatumGetPointer(array_recv(&locfcinfo));
Assert(!locfcinfo.isnull);
/* sanity checks: oidvector must be 1-D, 0-based, no nulls */
if (ARR_NDIM(result) != 1 || ARR_HASNULL(result) || ARR_ELEMTYPE(result) != OIDOID || ARR_LBOUND(result)[0] != 0)
ereport(ERROR, (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION), errmsg("invalid oidvector data")));
/* check length for consistency with oidvectorin() */
if (ARR_DIMS(result)[0] > FUNC_MAX_ARGS)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("oidvector has too many elements")));
PG_RETURN_POINTER(result);
}
/*
* oidvectorsend - converts oidvector to binary format
*/
Datum oidvectorsend(PG_FUNCTION_ARGS)
{
return array_send(fcinfo);
}
Datum oidvectorin_extend(PG_FUNCTION_ARGS)
{
return oidvectorin(fcinfo);
}
Datum oidvectorout_extend(PG_FUNCTION_ARGS)
{
return oidvectorout(fcinfo);
}
Datum oidvectorsend_extend(PG_FUNCTION_ARGS)
{
return oidvectorsend(fcinfo);
}
Datum oidvectorrecv_extend(PG_FUNCTION_ARGS)
{
return oidvectorrecv(fcinfo);
}
/*
* oidparse - get OID from IConst/FConst node
*/
Oid oidparse(Node* node)
{
switch (nodeTag(node)) {
case T_Integer:
return intVal(node);
case T_Float:
/*
* Values too large for int4 will be represented as Float
* constants by the lexer. Accept these if they are valid OID
* strings.
*/
return oidin_subr(strVal(node), NULL);
default:
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE), errmsg("unrecognized node type: %d", (int)nodeTag(node))));
}
return InvalidOid; /* keep compiler quiet */
}
/*****************************************************************************
* PUBLIC ROUTINES *
*****************************************************************************/
Datum oideq(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 == arg2);
}
Datum oidne(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 != arg2);
}
Datum oidlt(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 < arg2);
}
Datum oidle(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 <= arg2);
}
Datum oidge(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 >= arg2);
}
Datum oidgt(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_BOOL(arg1 > arg2);
}
Datum oidlarger(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_OID((arg1 > arg2) ? arg1 : arg2);
}
Datum oidsmaller(PG_FUNCTION_ARGS)
{
Oid arg1 = PG_GETARG_OID(0);
Oid arg2 = PG_GETARG_OID(1);
PG_RETURN_OID((arg1 < arg2) ? arg1 : arg2);
}
Datum oidvectoreq(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp == 0);
}
Datum oidvectorne(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp != 0);
}
Datum oidvectorlt(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp < 0);
}
Datum oidvectorle(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp <= 0);
}
Datum oidvectorge(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp >= 0);
}
Datum oidvectorgt(PG_FUNCTION_ARGS)
{
int32 cmp = DatumGetInt32(btoidvectorcmp(fcinfo));
PG_RETURN_BOOL(cmp > 0);
}
| 26.400922
| 120
| 0.616774
|
opengauss-mirror
|
5473a402d01ac1bead5979450f8b478098257405
| 1,972
|
cpp
|
C++
|
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
//
// test2.cpp
// EZasync
//
// Created by 贾皓翔 on 2019/6/5.
// Copyright © 2019 贾皓翔. All rights reserved.
//
#include <stdio.h>
#include "asynchttp/HTTP.hpp"
using namespace std;
using namespace HTTP;
int main(){
IOContext ctx;
Serv s(ctx,"8088");
HttpDispatcher *http=HttpDispatcherImpl::Create();
http->SetDefaultPath("./web");
http->Register("/hello", [](RequestBody &request,ResponseBody &response){
response.status=200;
response.otherHeaders_["Content-Type"]="text/html";
response.out("hello Nice my HTTP!");
});
http->Register("/world", [](RequestBody &request,ResponseBody &response){
response.status=200;
response.otherHeaders_["Content-Type"]="text/html;charset=utf-8";
for(auto i:request.headers_){
response.out("%s:%s<br>",i.first.c_str(),i.second.c_str());
}
for(auto i:request.cookies_){
response.out("%s=%s<br>",i.first.c_str(),i.second.c_str());
}
});
http->Register("/jump", [](RequestBody &request,ResponseBody &response){
response.sendRedirect("/world");
});
http->Register("/param", [](RequestBody &request,ResponseBody& response){
response.out("param:%s",request.parameters.c_str());
});
http->Register("/forward", [](RequestBody &req,ResponseBody &res){
res.out("这是跳转前第一个接口<br>");
res.forward(req,"/world");
});
http->RegisterFilter("/hello", [](RequestBody &request,ResponseBody &response){
cout<<"调用第一个过滤器!"<<endl;
return FILTER_NEXT;
});
http->RegisterFilter("/index.html", [](RequestBody &request,ResponseBody &response){
if (request.parameters.compare("hello")!=0) {
cout<<request.parameters<<endl;
response.forward(request, "/hello");
return FILTER_END;
}
cout<<"NICE!"<<endl;
return FILTER_NEXT;
});
ctx.run();
}
| 31.301587
| 88
| 0.591785
|
jhxqy
|
54759639a050f166bc45c0f04691f95a389bba4d
| 1,915
|
cpp
|
C++
|
src/Neuron.cpp
|
AmarOk1412/NeuralDriver
|
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
|
[
"WTFPL"
] | null | null | null |
src/Neuron.cpp
|
AmarOk1412/NeuralDriver
|
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
|
[
"WTFPL"
] | null | null | null |
src/Neuron.cpp
|
AmarOk1412/NeuralDriver
|
672fa4284eaaa88dc18498e23c7b40e1ec3d1c7d
|
[
"WTFPL"
] | null | null | null |
#include "Neuron.h"
#include <math.h>
#include <random>
#include <iostream>
#include <assert.h>
Neuron::Neuron(const int nbInput)
{
init(nbInput, 3.4);
}
Neuron::~Neuron()
{
}
double Neuron::calcOutput(std::vector<double> const& input)
{
return 1/(1+exp(-thetaTX(input)));
}
double Neuron::thetaTX(const std::vector<double>& input)
{
assert(_theta.size() == input.size());
assert(input.size() > 0);
double res = .0;
std::vector<double>::const_iterator itInputb = input.cbegin();
std::vector<double>::const_iterator itThetab = _theta.cbegin();
std::vector<double>::const_iterator itThetae = _theta.cend();
while(itThetab != itThetae)
{
res += (*itThetab) * (*itInputb);
++itInputb;
++itThetab;
}
return res+_biase;
}
void Neuron::adjust(const double error)
{
//Error is a ratio
std::vector<double>::iterator itThetab = _theta.begin();
std::vector<double>::iterator itThetae = _theta.end();
while(itThetab != itThetae)
{
*itThetab *= error;
++itThetab;
++itThetae;
}
}
void Neuron::init(int length, double epsilon)
{
std::uniform_real_distribution<double> unif(-epsilon, epsilon);
std::random_device rand_dev;
std::mt19937 rand_engine(rand_dev());
for(auto i = 0; i < length; ++i)
_theta.push_back(unif(rand_engine));
_biase = unif(rand_engine);
}
Neuron& Neuron::operator=(const Neuron& o)
{
//Some parameters will change (to pointer).
_input = o._input;
_theta = o._theta;
_biase = o._biase;
_learningRate = o._learningRate;
_output = o._output;
}
const double Neuron::getBiase() const
{
return _biase;
}
const std::vector<double>& Neuron::getThetas() const
{
return _theta;
}
std::ostream& operator<<(std::ostream & out, const Neuron& n)
{
out << '[' << n.getBiase() << ',';
std::vector<double> thetas = n.getThetas();
for(auto t : thetas)
out << t << ',';
out << ']';
}
| 19.742268
| 66
| 0.643864
|
AmarOk1412
|
547978b2f97378047c7210e419cf5cedb7255741
| 1,531
|
cpp
|
C++
|
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
|
ram-nad/chapel
|
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
|
[
"ECL-2.0",
"Apache-2.0"
] | 115
|
2018-02-01T18:56:44.000Z
|
2022-03-21T13:23:00.000Z
|
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
|
ram-nad/chapel
|
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
|
[
"ECL-2.0",
"Apache-2.0"
] | 27
|
2018-09-17T17:49:49.000Z
|
2021-11-03T04:31:51.000Z
|
third-party/llvm/llvm-src/tools/clang/lib/Driver/DarwinSDKInfo.cpp
|
ram-nad/chapel
|
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
|
[
"ECL-2.0",
"Apache-2.0"
] | 55
|
2018-02-01T07:11:49.000Z
|
2022-03-04T01:20:23.000Z
|
//===--- DarwinSDKInfo.cpp - SDK Information parser for darwin - ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/DarwinSDKInfo.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang::driver;
using namespace clang;
Expected<Optional<DarwinSDKInfo>>
driver::parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath) {
llvm::SmallString<256> Filepath = SDKRootPath;
llvm::sys::path::append(Filepath, "SDKSettings.json");
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
VFS.getBufferForFile(Filepath);
if (!File) {
// If the file couldn't be read, assume it just doesn't exist.
return None;
}
Expected<llvm::json::Value> Result =
llvm::json::parse(File.get()->getBuffer());
if (!Result)
return Result.takeError();
if (const auto *Obj = Result->getAsObject()) {
auto VersionString = Obj->getString("Version");
if (VersionString) {
VersionTuple Version;
if (!Version.tryParse(*VersionString))
return DarwinSDKInfo(Version);
}
}
return llvm::make_error<llvm::StringError>("invalid SDKSettings.json",
llvm::inconvertibleErrorCode());
}
| 34.022222
| 80
| 0.63292
|
ram-nad
|
54802c98caf4d2337d84f7b53369a0cc6d201cb7
| 334
|
cpp
|
C++
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | 5
|
2022-02-01T22:49:51.000Z
|
2022-03-03T10:18:36.000Z
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | 1
|
2022-01-31T23:09:04.000Z
|
2022-01-31T23:09:04.000Z
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | null | null | null |
// Copyright 2022 Mickael Daniel. All Rights Reserved.
#include "XeluIconsDeveloperSettings.h"
UXeluIconsDeveloperSettings::UXeluIconsDeveloperSettings()
{
IconsDataTable = FSoftObjectPath(TEXT("/XeluIcons/DT_Xelu_Icons.DT_Xelu_Icons"));
}
FName UXeluIconsDeveloperSettings::GetCategoryName() const
{
return FName("Plugins");
}
| 22.266667
| 82
| 0.805389
|
mklabs
|
54873d2ce7769081b8be72c41d3903efc133f45d
| 155
|
cpp
|
C++
|
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
#include "Zadanie20.h"
Zadanie20::Zadanie20()
{
}
Zadanie20::~Zadanie20()
{
}
void Zadanie20::run()
{
cout<<"Zadanie20"<<endl<<endl;
pokazTresc();
}
| 9.117647
| 31
| 0.645161
|
radzbydzi
|
54888c9318b3b338b8652db0a9750d917d1eef3b
| 297
|
hpp
|
C++
|
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#ifndef REGULAR_EXPRESSION_MATCHING_HPP_
#define REGULAR_EXPRESSION_MATCHING_HPP_
#include <string>
using namespace std;
class RegularExpressionMatching {
public:
bool isMatch(string s, string p);
private:
bool isMatch(char _s, char _p);
};
#endif // REGULAR_EXPRESSION_MATCHING_HPP_
| 17.470588
| 42
| 0.787879
|
yanzhe-chen
|
5489c5139f0a48c5e723f63b2936a0cfd0342dfb
| 995
|
cpp
|
C++
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | 5
|
2017-12-27T12:57:36.000Z
|
2021-10-02T03:21:40.000Z
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | 9
|
2020-09-29T22:40:49.000Z
|
2020-10-17T20:05:05.000Z
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | null | null | null |
#include "event.hpp"
#include <SDL.h>
#include "sink.hpp"
timestamp_t Event::system_time;
Event::Event() :
current(system_time - 10000), // 10 seconds ago...
counter(0)
{
}
void Event::Trigger()
{
this->triggered = true;
this->current = system_time;
this->counter += 1;
}
void Event::Reset()
{
this->counter = 0;
}
float Event::GetTimeSinceLastTrigger() const
{
return (system_time - this->current) / 1000.0;
}
void Event::NewFrame()
{
system_time = SDL_GetTicks();
}
bool Event::Any(Sink * sink)
{
if(sink == nullptr)
return false;
assert(sink->GetType() == CgDataType::Event);
for(int i = 0; i < sink->GetSourceCount(); i++)
{
if(sink->GetObject<CgDataType::Event>(i))
return true;
}
return false;
}
int Event::Count(Sink * sink)
{
if(sink == nullptr)
return false;
assert(sink->GetType() == CgDataType::Event);
int cnt = 0;
for(int i = 0; i < sink->GetSourceCount(); i++)
{
if(sink->GetObject<CgDataType::Event>(i))
++cnt;
}
return cnt;
}
| 15.307692
| 54
| 0.638191
|
MasterQ32
|
548bc5e3181dfac55df4e56c841997aa1b26ed76
| 8,428
|
hpp
|
C++
|
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
#ifndef BUW_LIST_HPP
#define BUW_LIST_HPP
#include <cassert>
#include <cstddef> //ptrdiff_t
#include <iterator> //std::bidirectional_iterator_tag
#include <iostream>
#include <initializer_list>
template <typename T>
class List;
template <typename T>
struct ListNode {
T value = T{};
ListNode* prev = nullptr;
ListNode* next = nullptr;
};
//TODO: Implementierung der Methoden des Iterators
// (nach Vorlesung STL-1 am 09. Juni) (Aufgabe 3.11)
template <typename T>
struct ListIterator {
using Self = ListIterator<T>;
using value_type = T;
using pointer = T*;
using reference = T&;
using difference_type = ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;
/* Returns Reference to Value of current Node */
T& operator*() const {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
return node->value;
} //call *it
/* Returns pointer to Reference of current node */
T* operator->() const {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
return &node->value;
} //call it->method() or it->member
/* PREINCREMENT, call: ++it, advances one element forward */
ListIterator<T>& operator++() {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
node = node->next;
return *this;
}
/* POSTINCREMENT (signature distinguishes the iterators),
call: it++, advances one element forward*/
ListIterator<T> operator++(int) {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
auto newit = *this;
++*this;
return newit;
}
/* Compares Values of Both Nodes */
bool operator==(ListIterator<T> const& x) const {
if(x.node == node) {
return true;
}
return false;
} // call it: == it
/* Compares Values of Both Nodes */
bool operator!=(ListIterator<T> const& x) const {
if(x.node != node) {
return true;
}
return false;
} // call it: != it
/* Advances Iterator */
ListIterator<T> next() const {
if (nullptr != node) {
return ListIterator{node->next};
} else {
return ListIterator{nullptr};
}
}
ListNode <T>* node = nullptr;
};
template <typename T>
class List {
public:
//friend declarations for testing the members
template <typename TEST_TYPE>
friend size_t get_size(List<TEST_TYPE> const& list_to_test);
template <typename TEST_TYPE>
friend ListNode<TEST_TYPE>* get_first_pointer(List<TEST_TYPE> const& list_to_test);
template <typename TEST_TYPE>
friend ListNode<TEST_TYPE>* get_last_pointer(List<TEST_TYPE> const& list_to_test);
using value_type = T;
using pointer = T*;
using const_pointer = T const*;
using reference = T&;
using const_reference = T const&;
using iterator = ListIterator<T>;
/* Initializes the List with size_ = 0 and both the first and the last node pointing to null */
List()=default;
//Copy Constructor (Deep Copy)
/* Initializes a new empty List and copies (deep) the elements of the input List until it reaches the last node */
List(List<T> const& l) :
size_{0},
first_{nullptr},
last_{nullptr }
{
ListNode<T> *node = l.first_;
while(node != nullptr) {
push_back(node->value);
node = node->next;
}
}
//TODO: Initializer-List Konstruktor (3.14 - Teil 1)
/* ... */
// test and implement:
List(std::initializer_list<T> ini_list) {
//not implemented yet
}
/* Unifying Assignment Operator */
/* Makes Use of Swap function to Assign Pointers and Size */
List& operator=(List rhs) {
swap(rhs);
return *this;
}
//swap function that swaps the first_ and last_ pointers as well as size_
void swap(List& rhs) {
std::swap(first_, rhs.first_);
std::swap(last_, rhs.last_);
std::swap(size_, rhs.size_);
}
/* ... */
// test and implement:
bool operator==(List const& rhs) {
bool status = false;
if(size_ == rhs.size_) {
status = true;
ListNode<T> *nodelhs = first_;
ListNode<T> *noderhs = rhs.first_;
while(nodelhs != nullptr && status) {
if(nodelhs->value == noderhs->value) {
nodelhs = nodelhs->next;
noderhs = noderhs->next;
} else {
status = false;
}
}
}
return status;
}
bool operator!=(List const& rhs)
{
if(*this == rhs) {
return false;
} else {
return true;
}
}
/* calls clear function */
~List() {
clear();
} //can not really be tested
/* Returns iterator that points to first node */
ListIterator<T> begin() {
auto begin = first_;
return {begin};
}
/* Returns iterator that points behind last node (nullptr) */
ListIterator<T> end() {
auto end = nullptr;
return {end};
}
/* Calls pop_front until first_ = last_ and then pops the last element indivdually */
void clear() {
while(size_ > 0) {
pop_back();
}
}
/* ... */
//TODO: member function insert (Aufgabe 3.12)
/* ... */
//TODO: member function insert (Aufgabe 3.13)
/* Reverses List by changing the direction of the pointers, from front to back*/
//TODO: member function reverse (Aufgabe 3.7 - Teil 1)
void reverse() {
ListNode<T> *node = last_;
last_ = first_;
first_ = node;
while(node != nullptr) {
std::swap(node->next, node->prev);
node = node->next;
}
}
/* Insert Element at the front of the List */
void push_front(T const& element) {
ListNode<T> *node = new ListNode<T>{element};
if (first_ == nullptr) {
first_ = node;
last_ = node;
node->next = nullptr;
node->prev = nullptr;
} else {
node->next = first_;
first_->prev = node;
first_ = node;
}
size_++;
}
/* Insert Element at the back of the List */
void push_back(T const& element) {
ListNode<T> *node = new ListNode<T>{element};
if (first_ == nullptr) {
first_ = node;
last_ = node;
node->next = nullptr;
node->prev = nullptr;
} else {
last_->next = node;
node->prev = last_;
last_ = node;
}
size_++;
}
/* Checks if list has one or more than one item and adjusts pointers */
void pop_front() {
if(empty()) {
throw "List is empty";
}
if(first_ == last_) {
first_ = nullptr;
last_ = nullptr;
} else {
ListNode<T> *newFirst = first_->next;
first_->next = nullptr;
delete first_;
first_ = newFirst;
first_->prev = nullptr;
}
size_--;
}
/* Checks if list has one or more than one item and adjusts pointers */
void pop_back() {
if(empty()) {
throw "List is empty";
}
if(first_ == last_) {
first_ = nullptr;
last_ = nullptr;
} else {
ListNode<T> *newLast = last_->prev;
last_->prev = nullptr;
delete last_;
last_ = newLast;
last_->next = nullptr;
}
size_--;
}
/* returns value of first node */
T& front() {
if(empty()) {
throw "List is empty";
}
return first_->value;
}
/* returns value of last node */
T& back() {
if(empty()) {
throw "List is empty";
}
return last_->value;
}
/* Returns wether List is empty or not*/
bool empty() const {
return size_ == 0;
};
/* Size */
std::size_t size() const{
return size_;
};
// list members
private:
std::size_t size_ = 0;
ListNode<T>* first_ = nullptr;
ListNode<T>* last_ = nullptr;
};
/* Makes use of member function reverse - takes a List as input and returns a new one */
//TODO: Freie Funktion reverse
//(Aufgabe 3.7 - Teil 2, benutzt Member-Funktion reverse)
template<typename T>
List<T> reverse(List<T> const& list) {
List<T> newL = list;
newL.reverse();
return newL;
}
/* ... */
//TODO: Freie Funktion operator+ (3.14 - Teil 2)
#endif // # define BUW_LIST_HPP
| 24.218391
| 118
| 0.568818
|
saJonMR
|
548d738958b13f8c71e2e4d7c9fec12a2f52df80
| 316
|
cpp
|
C++
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 9
|
2016-05-27T01:00:39.000Z
|
2021-04-01T08:54:46.000Z
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 1
|
2016-03-03T22:54:08.000Z
|
2016-03-03T22:54:08.000Z
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 4
|
2016-05-27T01:00:43.000Z
|
2018-08-19T08:47:49.000Z
|
//do_wrapper.cpp
#include "HippoQOR/do_wrapper.h"
//--------------------------------------------------------------------------------
namespace nsUnitTesting
{
//--------------------------------------------------------------------------------
VirtualDestructable::~VirtualDestructable()
{
}
}//nsUnitTesting
| 22.571429
| 83
| 0.35443
|
mfaithfull
|
548e9d8103cba0d2c43a2530193557f5d737f284
| 8,134
|
cpp
|
C++
|
src/main/cpp/rocketmq/CredentialsProvider.cpp
|
lizhanhui/rocketmq-client-cpp
|
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
|
[
"Apache-2.0"
] | null | null | null |
src/main/cpp/rocketmq/CredentialsProvider.cpp
|
lizhanhui/rocketmq-client-cpp
|
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
|
[
"Apache-2.0"
] | null | null | null |
src/main/cpp/rocketmq/CredentialsProvider.cpp
|
lizhanhui/rocketmq-client-cpp
|
d2001836e40d4f1da29ae7b2848fdfe0077ed1bf
|
[
"Apache-2.0"
] | 1
|
2021-09-16T06:31:07.000Z
|
2021-09-16T06:31:07.000Z
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include "absl/memory/memory.h"
#include "absl/strings/match.h"
#include "fmt/format.h"
#include "ghc/filesystem.hpp"
#include "google/protobuf/struct.pb.h"
#include "google/protobuf/util/json_util.h"
#include "spdlog/spdlog.h"
#include "MixAll.h"
#include "StsCredentialsProviderImpl.h"
#include "rocketmq/Logger.h"
ROCKETMQ_NAMESPACE_BEGIN
StaticCredentialsProvider::StaticCredentialsProvider(std::string access_key, std::string access_secret)
: access_key_(std::move(access_key)), access_secret_(std::move(access_secret)) {
}
Credentials StaticCredentialsProvider::getCredentials() {
return Credentials(access_key_, access_secret_);
}
const char* EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_KEY = "ROCKETMQ_ACCESS_KEY";
const char* EnvironmentVariablesCredentialsProvider::ENVIRONMENT_ACCESS_SECRET = "ROCKETMQ_ACCESS_SECRET";
EnvironmentVariablesCredentialsProvider::EnvironmentVariablesCredentialsProvider() {
char* key = getenv(ENVIRONMENT_ACCESS_KEY);
if (key) {
access_key_ = std::string(key);
}
char* secret = getenv(ENVIRONMENT_ACCESS_SECRET);
if (secret) {
access_secret_ = std::string(secret);
}
}
Credentials EnvironmentVariablesCredentialsProvider::getCredentials() {
return Credentials(access_key_, access_secret_);
}
const char* ConfigFileCredentialsProvider::CREDENTIAL_FILE_ = "rocketmq/credentials";
const char* ConfigFileCredentialsProvider::ACCESS_KEY_FIELD_NAME = "AccessKey";
const char* ConfigFileCredentialsProvider::ACCESS_SECRET_FIELD_NAME = "AccessSecret";
ConfigFileCredentialsProvider::ConfigFileCredentialsProvider() {
std::string config_file;
if (MixAll::homeDirectory(config_file)) {
std::string path_separator(1, ghc::filesystem::path::preferred_separator);
if (!absl::EndsWith(config_file, path_separator)) {
config_file.append(1, ghc::filesystem::path::preferred_separator);
}
config_file.append(CREDENTIAL_FILE_);
ghc::filesystem::path config_file_path(config_file);
std::error_code ec;
if (!ghc::filesystem::exists(config_file_path, ec) || ec) {
SPDLOG_WARN("Config file[{}] does not exist.", config_file);
return;
}
std::ifstream config_file_stream;
config_file_stream.open(config_file.c_str(), std::ios::in | std::ios::ate | std::ios::binary);
if (config_file_stream.good()) {
auto size = config_file_stream.tellg();
std::string content(size, '\0');
config_file_stream.seekg(0);
config_file_stream.read(&content[0], size);
config_file_stream.close();
google::protobuf::Struct root;
google::protobuf::util::Status status = google::protobuf::util::JsonStringToMessage(content, &root);
if (status.ok()) {
auto&& fields = root.fields();
if (fields.contains(ACCESS_KEY_FIELD_NAME)) {
access_key_ = fields.at(ACCESS_KEY_FIELD_NAME).string_value();
}
if (fields.contains(ACCESS_SECRET_FIELD_NAME)) {
access_secret_ = fields.at(ACCESS_SECRET_FIELD_NAME).string_value();
}
SPDLOG_DEBUG("Credentials for access_key={} loaded", access_key_);
} else {
SPDLOG_WARN("Failed to parse credential JSON config file. Message: {}", status.message().data());
}
} else {
SPDLOG_WARN("Failed to open file: {}", config_file);
return;
}
}
}
ConfigFileCredentialsProvider::ConfigFileCredentialsProvider(std::string config_file,
std::chrono::milliseconds refresh_interval) {
}
Credentials ConfigFileCredentialsProvider::getCredentials() {
return Credentials(access_key_, access_secret_);
}
StsCredentialsProvider::StsCredentialsProvider(std::string ram_role_name)
: impl_(absl::make_unique<StsCredentialsProviderImpl>(std::move(ram_role_name))) {
}
Credentials StsCredentialsProvider::getCredentials() {
return impl_->getCredentials();
}
StsCredentialsProviderImpl::StsCredentialsProviderImpl(std::string ram_role_name)
: ram_role_name_(std::move(ram_role_name)) {
}
StsCredentialsProviderImpl::~StsCredentialsProviderImpl() {
http_client_->shutdown();
}
Credentials StsCredentialsProviderImpl::getCredentials() {
if (std::chrono::system_clock::now() >= expiration_) {
refresh();
}
{
absl::MutexLock lk(&mtx_);
return Credentials(access_key_, access_secret_, session_token_, expiration_);
}
}
void StsCredentialsProviderImpl::refresh() {
std::string path = fmt::format("{}{}", RAM_ROLE_URL_PREFIX, ram_role_name_);
absl::Mutex sync_mtx;
absl::CondVar sync_cv;
bool completed = false;
auto callback = [&, this](int code, const std::multimap<std::string, std::string>& headers, const std::string& body) {
SPDLOG_DEBUG("Received STS response. Code: {}", code);
if (static_cast<int>(HttpStatus::OK) == code) {
google::protobuf::Struct doc;
google::protobuf::util::Status status = google::protobuf::util::JsonStringToMessage(body, &doc);
if (status.ok()) {
const auto& fields = doc.fields();
assert(fields.contains(FIELD_ACCESS_KEY));
std::string access_key = fields.at(FIELD_ACCESS_KEY).string_value();
assert(fields.contains(FIELD_ACCESS_SECRET));
std::string access_secret = fields.at(FIELD_ACCESS_SECRET).string_value();
assert(fields.contains(FIELD_SESSION_TOKEN));
std::string session_token = fields.at(FIELD_SESSION_TOKEN).string_value();
assert(fields.contains(FIELD_EXPIRATION));
std::string expiration_string = fields.at(FIELD_EXPIRATION).string_value();
absl::Time expiration_instant;
std::string parse_error;
if (absl::ParseTime(EXPIRATION_DATE_TIME_FORMAT, expiration_string, absl::UTCTimeZone(), &expiration_instant,
&parse_error)) {
absl::MutexLock lk(&mtx_);
access_key_ = std::move(access_key);
access_secret_ = std::move(access_secret);
session_token_ = std::move(session_token);
expiration_ = absl::ToChronoTime(expiration_instant);
} else {
SPDLOG_WARN("Failed to parse expiration time. Message: {}", parse_error);
}
} else {
SPDLOG_WARN("Failed to parse STS response. Message: {}", status.message().as_string());
}
} else {
SPDLOG_WARN("STS response code is not OK. Code: {}", code);
}
{
absl::MutexLock lk(&sync_mtx);
completed = true;
sync_cv.Signal();
}
};
http_client_->get(HttpProtocol::HTTP, RAM_ROLE_HOST, 80, path, callback);
while (!completed) {
absl::MutexLock lk(&sync_mtx);
sync_cv.Wait(&sync_mtx);
}
}
const char* StsCredentialsProviderImpl::RAM_ROLE_HOST = "100.100.100.200";
const char* StsCredentialsProviderImpl::RAM_ROLE_URL_PREFIX = "/latest/meta-data/Ram/security-credentials/";
const char* StsCredentialsProviderImpl::FIELD_ACCESS_KEY = "AccessKeyId";
const char* StsCredentialsProviderImpl::FIELD_ACCESS_SECRET = "AccessKeySecret";
const char* StsCredentialsProviderImpl::FIELD_SESSION_TOKEN = "SecurityToken";
const char* StsCredentialsProviderImpl::FIELD_EXPIRATION = "Expiration";
const char* StsCredentialsProviderImpl::EXPIRATION_DATE_TIME_FORMAT = "%Y-%m-%d%ET%H:%H:%S%Ez";
ROCKETMQ_NAMESPACE_END
| 38.733333
| 120
| 0.717482
|
lizhanhui
|
54908d60e1fa2dd3d5ae4d32336bf6d1e354b105
| 2,911
|
cpp
|
C++
|
samples/client/enumeration/Client.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | 1
|
2021-11-10T19:36:30.000Z
|
2021-11-10T19:36:30.000Z
|
samples/client/enumeration/Client.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | null | null | null |
samples/client/enumeration/Client.cpp
|
vlsinitsyn/axis1
|
65a622201e526dedf7c3aeadce7cac5bd79895bf
|
[
"Apache-2.0"
] | 2
|
2021-11-02T13:09:57.000Z
|
2021-11-10T19:36:22.000Z
|
#include "EnumerationWS.hpp"
#include <stdlib.h> // For malloc(), calloc(), strdup() and free()
#include <iostream>
#define WSDL_DEFAULT_ENDPOINT "http://localhost:80/axis/enumeration"
static void usage( char * programName, char * defaultURL)
{
cout << "Usage:" << endl
<< programName << " [-? | service_url] " << endl
<< " -? Show this help." << endl
<< " service_url URL of the service." << endl
<< " Default service URL is assumed to be " << defaultURL << endl;
}
int main( int argc, char * argv[])
{
EnumerationWS * ws;
char endpoint[256];
int returnValue = 1; // Assume Failure
Type1 * input = NULL;
Type1 * result = NULL;
bool bSuccess = false;
int iRetryIterationCount = 3;
sprintf( endpoint, "%s", WSDL_DEFAULT_ENDPOINT);
if( argc > 1)
{
// Watch for special case help request
// Check for - only so that it works for
//-?, -h or --help; -anything
if( !strncmp( argv[1], "-", 1))
{
usage( argv[0], endpoint);
return 2;
}
sprintf( endpoint, argv[1]);
}
do
{
try
{
ws = new EnumerationWS( endpoint, APTHTTP1_1);
input = new Type1();
xsd__int iEnumInt = ENUMTYPEINT_0;
input->setatt_enum_string( "one");
input->setenum_string( "one");
input->setenum_int( &iEnumInt);
input->setatt_enum_int( ENUMTYPEINT_1);
input->setatt_enum_kind( "CHEQUE");
ws->setTransportProperty( "SOAPAction", "enumeration#getInput");
result = ws->getInput( input);
cout << "Result" << endl;
if( result == NULL)
{
cout << " result = NULL" << endl;
}
else
{
cout << "att_enum_int " << result->getatt_enum_int() << endl;
cout << "att_enum_string " << result->getatt_enum_string() << endl;
cout << "enum_int " << result->getenum_int() << endl;
cout << "enum_string " << result->getenum_string() << endl;
cout << "enum_kind " << result->getatt_enum_kind() << endl;
returnValue = 0; // Success
}
bSuccess = true;
}
catch( AxisException & e)
{
bool bSilent = false;
if( e.getExceptionCode () == CLIENT_TRANSPORT_OPEN_CONNECTION_FAILED)
{
if( iRetryIterationCount > 1)
{
bSilent = true;
}
}
else
{
iRetryIterationCount = 0;
}
if( !bSilent)
{
cerr << e.what () << endl;
}
}
catch( ...)
{
cerr << "Unknown Exception occured." << endl;
}
try
{
delete ws;
delete input;
delete result;
}
catch( exception & exception)
{
cout << "Exception when cleaning up: " << exception.what() << endl;
}
catch( ...)
{
cout << "Unknown exception when cleaning up: " << endl;
}
iRetryIterationCount--;
} while( iRetryIterationCount > 0 && !bSuccess);
cout << "---------------------- TEST COMPLETE -----------------------------" << endl;
cout << "successful" << endl;
return returnValue;
}
| 21.723881
| 89
| 0.571968
|
vlsinitsyn
|
5496e5f2c2d9d4d1c0f06af597e04c1a5be7b8db
| 30,774
|
hpp
|
C++
|
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
#pragma once
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
/**
* @file misc.hpp
* @author Harith Al-Safi
* @brief
* @version 0.1
* @date 2021-12-10
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <numeric>
#include "graphs.hpp"
/**
* @brief Operator to multiply two vectors
*
* @tparam TYPE
* @param first
* @param second
* @return std::vector<TYPE>
*/
template<typename TYPE>
std::vector<TYPE> operator *(std::vector<TYPE> first, std::vector<TYPE> second){
if(first.size() != second.size()){
throw std::invalid_argument("Invalid size");
}
std::vector<TYPE> temp;
for(int i = 0; i < first.size(); i++){
temp.push_back(first[i]*second[i]);
}
return temp;
}
/**
* @brief Overloads the round function
*
* @tparam TYPE
* @param a the value itself
* @param dp number of decimal places
* @return TYPE
*/
template<typename TYPE>
TYPE round(TYPE a, int dp = 0){
if(a < TYPE(0)){
return TYPE((int)(a*pow(10, dp)-.5)/pow(10, dp));
}
return TYPE((int)(a*pow(10, dp)+.5)/pow(10, dp));
}
namespace misc
{
/**
* @brief Genarate vector from min, max andn number of points
*
* @tparam TYPE
* @param mn min val
* @param mx max val
* @param n number of points
* @return std::vector<TYPE>
*/
template<typename TYPE>
std::vector<TYPE> generate_vector(TYPE mn, TYPE mx, int n){
std::vector<TYPE> v;
for(TYPE i = mn; i <= mx; i+=(TYPE)(mx-mn)/n){
v.push_back(i);
}
return v;
}
/**
* @brief Table class to contain the dataframe
*/
class Table: public std::vector<std::vector<long double>>
{
public:
/**
* @brief Struct to contain the quartile range
*
*/
struct QR
{
/**
* @brief Lower quartile
*
*/
long double LQ;
/**
* @brief Q1 (25%)
*
*/
long double Q1;
/**
* @brief Q2 (50%)
*
*/
long double Q2;
/**
* @brief Q3 (75%)
*
*/
long double Q3;
/**
* @brief Upper quartile
*
*/
long double UQ;
};
private:
/**
* @brief Checks the header and returns index
*
* @param head
* @return int
*/
int check_header(std::string head){
for(int i = 0; i < headers.size(); i++){
if(headers[i] == head){
return i;
}
}
return -1;
}
/**
* @brief Get the col vector based on header name
*
* @param headname
* @return std::vector<long double>
*/
std::vector<long double> get_col_(std::string headname){
int j = check_header(headname);
std::vector<long double> a;
if(j >= 0){
for(int i = 0; i < size(); i++){
a.push_back(at(i).at(j));
}
}
return a;
}
/**
* @brief Get the return average of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_avgs(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_avg(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return std of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_stds(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_std(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return variance of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_vars(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_var(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return quartile range of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<QR> get_qrs(){
std::vector<QR> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_qr(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return sums of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_sums(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_sum(get_col_(headers[j])));
}
return a;
}
/**
* @brief Re-centers a string based on given width
*
* @param s
* @param w
* @return std::string
*/
static std::string center(const string s, const int w) {
std::stringstream ss, spaces;
int padding = w - s.size(); // count excess room to pad
for(int i=0; i<padding/2; ++i)
spaces << " ";
ss << spaces.str() << s << spaces.str(); // format with padding
if(padding>0 && padding%2!=0) // if odd #, add 1 space
ss << " ";
return ss.str();
}
/**
* @brief converts double to a string with white space
*
* @param x
* @param width
* @return std::string
*/
static std::string prd(long double x, int width) {
std::stringstream ss;
ss << std::fixed << std::left;
ss.fill(' '); // fill space around displayed #
ss.width(width); // set width around displayed #
ss.precision(2); // set # places after decimal
ss << x;
return center(ss.str(), width);
}
/**
* @brief Gives spacing to a string
*
* @param x
* @param width
* @return std::string
*/
static std::string prd(std::string x, int width) {
std::stringstream ss;
ss << std::left;
ss.fill(' '); // fill space around displayed #
ss.width(width); // set width around displayed #
ss << x;
return center(ss.str(), width);
}
/**
* @brief Generates row names
*
*/
void generate_rows(){
rows.clear();
for(int i = 0; i < size(); i++){
rows.push_back("Row-"+std::to_string(i));
}
}
/**
* @brief Checks size of current class
*
*/
void check_size(){
if(empty()){
row = 0;
col = 0;
return;
}
col = at(0).size();
row = size();
}
/**
* @brief Generates line to seperate rows
*
* @param l
* @return std::string
*/
std::string generate_line(int l){
std::string line;
for(int i = 0; i < l; i++){
line+="―";
}
return line;
}
/**
* @brief Stores the headers
*
*/
std::vector<std::string> headers;
/**
* @brief Stores the row names
*
*/
std::vector<std::string> rows;
/**
* @brief Row size
*
*/
int row;
/**
* @brief Colum size
*
*/
int col;
/**
* @brief Spacing size for print
*
*/
int sz = 10;
public:
/**
* @brief Construct a new Table object
*
*/
Table(){}
/**
* @brief Destroy the Table object
*
*/
~Table(){}
/**
* @brief Reads from csv file
*
* @param file
* @return true: if read is success
* @return false: if read did not complete
*/
bool read_csv(std::string filename){
ifstream file(filename);
if(file.is_open()){
clear();
headers.clear();
// col name
string line, colname;
getline(file, line);
stringstream ss(line);
while(getline(ss, colname, ',')){
headers.push_back(colname);
}
// data
long double val;
while(std::getline(file, line))
{
// Create a stringstream of the current line
std::stringstream ss(line);
std::vector<long double> r;
while(ss >> val){
r.push_back(val);
// If the next token is a comma, ignore it and move on
if(ss.peek() == ',') ss.ignore();
}
push_back(r);
}
check_size();
file.close();
return true;
}
file.close();
return false;
}
/**
* @brief Reads from csv file
*
* @param file
* @return true: if read is success
* @return false: if read did not complete
*/
bool save_csv(std::string filename)
{
ofstream file(filename);
if(file.is_open()){
for(int i = 0; i < headers.size(); i++){
if(i != headers.size()-1){
file << headers[i] << ",";
}
else{
file << headers[i] << "\n";
}
}
check_size();
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(j != col-1){
file << at(i).at(j) << ",";
}
else if (j == col-1){
file << at(i).at(j) << "\n";
}
}
}
file.close();
return true;
}
file.close();
return false;
}
/**
* @brief Get the row size object
*
* @return int
*/
int get_row_size(){
return size();
}
/**
* @brief Get the col size object
*
* @return int
*/
int get_col_size(){
return at(0).size();
}
/**
* @brief Returns colum of certain header
*
* @param headname
* @return std::vector<TYPE>&
*/
std::vector<long double> operator[](std::string headname){
return get_col_(headname);
}
/**
* @brief Sorts data ascending
*
* @param a
* @return std::vector<long double>
*/
static std::vector<long double> sort_asc(std::vector<long double> & a){
std::vector<long double> v_sorted(a.size());
std::partial_sort_copy(a.begin(), a.end(),
v_sorted.begin(), v_sorted.end());
return v_sorted;
}
/**
* @brief Get the min value of vector
*
* @param a
* @return long double
*/
static long double get_min(std::vector<long double> a){
return *std::min_element(a.begin(), a.end());
}
/**
* @brief Get the max value of vector
*
* @param a
* @return long double
*/
static long double get_max(std::vector<long double> a){
return *std::max_element(a.begin(), a.end());
}
/**
* @brief Get the sum of vector
*
* @param a
* @return long double
*/
static long double get_sum(std::vector<long double> a){
return std::accumulate(a.begin(), a.end(), 0);
}
/**
* @brief Get the avg of vector
*
* @param a
* @return long double
*/
static long double get_avg(std::vector<long double> a){
return get_sum(a)/a.size();
}
/**
* @brief Get the variance of vector
*
* @param a
* @return long double
*/
static long double get_var(std::vector<long double> a){
long double mean = get_avg(a);
int N = a.size();
long double sum = 0;
for(int i = 0; i < N; i++){
sum+=pow((a[i]-mean), 2);
}
return (long double) sum/N;
}
/**
* @brief Get the standard diviation of vector
*
* @param a
* @return long double
*/
static long double get_std(std::vector<long double> a){
return sqrt(get_var(a));
}
/**
* @brief Get the quartile range of a vector
*
* @param a
* @return QR
*/
static QR get_qr(std::vector<long double> a){
QR qr;
qr.LQ = get_min(a);
qr.UQ = get_max(a);
auto a_sorted = sort_asc(a);
qr.Q1 = a_sorted.at((int) (a_sorted.size())/4);
qr.Q2 = a_sorted.at((int) (a_sorted.size())/2);
qr.Q3 = a_sorted.at((int) (3*(a_sorted.size()))/4);
return qr;
}
/**
* @brief Get the relation coefficient of two vectors
*
* @param _x
* @param _y
* @return long double
*/
static long double get_r(
std::vector<long double> _x, std::vector<long double> _y){
if(_x.size() != _y.size()){
throw std::invalid_argument("misc::Table::get_r -> Size mismatch");
}
long double sumx = misc::Table::get_sum(_x);
long double sumy = misc::Table::get_sum(_y);
long double sumxx = misc::Table::get_sum(_x*_x);
long double sumxy = misc::Table::get_sum(_x*_y);
long double sumyy = misc::Table::get_sum(_y*_y);
return (_x.size()*sumxy-(sumx*sumy))/
(sqrt((_x.size()*sumxx-pow(sumx, 2))*(_x.size()*sumyy-pow(sumy, 2))));
}
/**
* @brief Shows a certain number of rows in table
*
* @param r
*/
void show(int r){
if(rows.empty()){
generate_rows();
}
check_size();
std::string line;
if(col == 1){
line = generate_line((std::pow(2, 1/col)+0.2)*sz*col);
}
else{
line = generate_line((std::pow(1.05, 1/col)+1.9/col)*sz*col);
}
for(int i = -1; i < r; i++){
for(int j = 0; j < col; j++){
// to print header
if(i == -1){
if (j == 0 && col > 1){
std::cout << prd(" ", sz) << "│"
<< prd(headers[j], sz) << "│";
}
else if(j == 0 && col == 1){
std::cout << prd(" ", sz) << "│"
<< prd(headers[j], sz) << "\n";
std::cout << line << "\n";
}
else if(j != col-1){
std::cout << prd(headers[j], sz) << "│";
}
else{
std::cout << prd(headers[j], sz) << "\n";
std::cout << line << "\n";
}
}
// printing values
else{
// row name + val
if(j == 0 && col > 1){
std::cout << prd(rows[i], sz) << "│"
<< prd(get_col_(headers[j]).at(i), sz) << "│";
}
else if(j == 0 && col == 1){
std::cout << prd(rows[i], sz) << "│"
<< prd(get_col_(headers[j]).at(i), sz) << "│" << "\n";
std::cout << line << "\n";
}
else if(j != col-1){
std::cout << prd(get_col_(headers[j]).at(i), sz) << "│";
}
else{
std::cout << prd(get_col_(headers[j]).at(i), sz) << "\n";
std::cout << line << "\n";
}
}
}
}
}
/**
* @brief shows all of the table
*
*/
void show(){
check_size();
show(row);
}
/**
* @brief Statistical summary of all colums in table
*
* @return Table
*/
Table describe_all(){
Table t;
auto avg = get_avgs();
auto std = get_stds();
auto var = get_vars();
auto qrs = get_qrs();
auto sms = get_sums();
check_size();
// loading row names
for(int i = 0; i < col; i++){
t.rows.push_back(headers[i]);
}
// loading col names
t.headers.push_back("Mean");
t.headers.push_back("STD");
t.headers.push_back("VAR");
t.headers.push_back("Min");
t.headers.push_back("Q1");
t.headers.push_back("Q2");
t.headers.push_back("Q3");
t.headers.push_back("Max");
t.headers.push_back("IQR");
t.headers.push_back("Sum");
// loading values
t.row = t.rows.size();
t.col = t.headers.size();
for(int i = 0; i < t.row; i++){
std::vector<long double> rr;
rr.push_back(avg[i]);
rr.push_back(std[i]);
rr.push_back(var[i]);
rr.push_back(qrs[i].LQ);
rr.push_back(qrs[i].Q1);
rr.push_back(qrs[i].Q2);
rr.push_back(qrs[i].Q3);
rr.push_back(qrs[i].UQ);
rr.push_back(qrs[i].Q3-qrs[i].Q1);
rr.push_back(sms[i]);
t.push_back(rr);
}
t.check_size();
t.sz = 11;
return t;
}
/**
* @brief Get the row as table
*
* @param r
* @return Table
*/
Table get_row(int r){
Table t;
t.push_back(at(r));
t.headers = headers;
if(rows.empty()){
generate_rows();
}
t.rows.push_back(rows[r]);
return t;
}
/**
* @brief Get the col as table
*
* @param name
* @return Table
*/
Table get_col(std::string name){
Table t;
auto a = get_col_(name);
for(int i = 0; i < a.size(); i++){
t.push_back({a[i]});
}
if(rows.empty()){
generate_rows();
}
t.headers.push_back(headers[check_header(name)]);
return t;
}
/**
* @brief Adds new colum
*
* @param col_name
* @param col_data
* @return true
* @return false
*/
bool add_col(std::string col_name, std::vector<long double> col_data){
check_size();
if((col_data.size() != row && row != 0) || col_data.empty()){
return false;
}
headers.push_back(col_name);
for(int i = 0; i < col_data.size(); i++){
if(row == 0){
push_back({col_data[i]});
}
else{
at(i).push_back(col_data[i]);
}
}
return true;
}
/**
* @brief Shows headers only
*
*/
void show_header(){
show(0);
}
};
/**
* @brief Encapsulates graph.hpp (https://github.com/tdulcet/Tables-and-Graphs)
*
*/
class Plot
{
public:
/**
* @brief Colors for plots
*
*/
enum Color
{
red = 10,
green = 11,
yellow = 12,
purple = 14,
blue = 15,
white = 16
};
private:
/**
* @brief Height of terminal plot
*
*/
size_t height;
/**
* @brief Width of terminal plot
*
*/
size_t width;
/**
* @brief Minimum x-value
*
*/
long double xmin;
/**
* @brief Maxmimum x-value
*
*/
long double xmax;
/**
* @brief Minimum y-value
*
*/
long double ymin;
/**
* @brief Maximum y-value
*
*/
long double ymax;
/**
* @brief Size for cols which is 2
*
*/
const size_t cols = 2;
/**
* @brief Used to store domain vector
*
*/
std::vector<long double> domain;
/**
* @brief Stores graphing options
*
*/
graphoptions aoptions;
/**
* @brief Stores color
*
*/
Color c;
/**
* @brief Stores title
*
*/
std::string title;
public:
/**
* @brief Construct a new Plot object
*
* @param h height
* @param w width
* @param xmn min x
* @param xmx max x
* @param ymn min y
* @param ymx max y
*/
Plot(int h = 145, int w = 145,
long double xmn = -10, long double xmx = 10,
long double ymn = -10, long double ymx = 10):
height(h), width(w),
xmin(xmn), xmax(xmx),
ymin(ymn), ymax(ymx){}
/**
* @brief Set the Domain
*
* @param xmn
* @param xmx
*/
void set_domain(long double xmn = -10, long double xmx = 10){
xmin = xmn;
xmax = xmx;
}
/**
* @brief Set the Range
*
* @param ymn
* @param ymx
*/
void set_range(long double ymn = -10, long double ymx = 10){
ymin = ymn;
ymax = ymx;
}
/**
* @brief Set the Size of figure
*
* @param h
* @param w
*/
void set_size(int h = 140, int w = 140){
height = h;
width = w;
}
/**
* @brief Set the color
*
* @param cc
*/
void set_color(Color cc = Color::blue){
c = cc;
}
/**
* @brief Set the title
*
* @param tt
*/
void set_title(std::string tt){
title = tt;
}
/**
* @brief Generates domain
*
* @param n
*/
void generate_domain(int n = 50){
generate_domain(xmin, xmax, n);
}
/**
* @brief Generates domain to plot function
*
* @param xmn
* @param xmx
* @param n number of points
*/
void generate_domain(long double xmn, long double xmx, int n){
domain = generate_vector(xmn, xmx, n);
}
/**
* @brief Plots vectors
*
* @param x vector for x
* @param y vector for y
*/
void plot_vect(std::vector<long double> &x, std::vector<long double> &y)
{
if(x.size() != y.size()){
std::cerr << x.size() << "\t" << y.size() << "\n";
std::cerr << "misc::Plot::plot_vect-> Size mismatch \n";
return;
}
long double **array;
array = new long double *[x.size()];
for (unsigned int i = 0; i < x.size(); ++i){
array[i] = new long double[cols];
}
for (unsigned int i = 0; i < x.size(); ++i){
for (unsigned int j = 0; j < cols; ++j){
// x
if (j == 0){
array[i][j] = x[i];
}
// y
else{
array[i][j] = y[i];
}
}
}
aoptions.color = c;
std::cout <<
colors[c]
<< title << "\n"
<< colors[Color::white];
graph(height, width, xmin, xmax, ymin, ymax, x.size(), array, aoptions);
if(array != NULL){
for (unsigned int i = 0; i < x.size(); ++i){
delete[] array[i];
}
delete[] array;
}
}
/**
* @brief Plots function
*
* @tparam LAMBDA
* @param fun lambda function
*/
template<typename LAMBDA>
void plot_fun(LAMBDA fun)
{
std::vector<long double> y;
for(int i = 0; i < domain.size(); i++){
y.push_back(fun(domain[i]));
}
plot_vect(domain, y);
}
};
}
| 30.052734
| 96
| 0.34136
|
harith-alsafi
|
549a4413d99a4670838f6d27035dc1c820d069e9
| 3,305
|
cpp
|
C++
|
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
|
GBCNewGamePlus/Physics
|
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
|
[
"MIT"
] | null | null | null |
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
|
GBCNewGamePlus/Physics
|
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
|
[
"MIT"
] | null | null | null |
Assignment/OpenGLEngineA4/OpenGLEngine/SphereContactGeneratorSystem.cpp
|
GBCNewGamePlus/Physics
|
739a244cfee506b3506a2bc6ec0dcdebe2c5417d
|
[
"MIT"
] | null | null | null |
#include "SphereContactGeneratorSystem.h"
#include "ParticleContactComponent.h"
namespace Reality
{
SphereContactGeneratorSystem::SphereContactGeneratorSystem()
{
requireComponent<SphereComponent>();
requireComponent<ParticleComponent>();
requireComponent<TransformComponent>();
}
void SphereContactGeneratorSystem::Update(float deltaTime)
{
if (!dummyCreated)
{
dummy = getWorld().createEntity();
dummyCreated = true;
}
auto entities = getEntities();
for (int i = 0; i < entities.size(); i++)
{
auto& transform1 = entities[i].getComponent<TransformComponent>();
auto& sphere1 = entities[i].getComponent<SphereComponent>();
auto& particle1 = entities[i].getComponent<ParticleComponent>();
bool collided = false;
// Check collisions with other spheres
if (entities.size() > 1)
{
if (i < entities.size() - 1)
{
for (int j = i + 1; j < entities.size(); j++)
{
auto& transform2 = entities[j].getComponent<TransformComponent>();
auto& sphere2 = entities[j].getComponent<SphereComponent>();
auto& particle2 = entities[j].getComponent<ParticleComponent>();
if (glm::length(transform1.position - transform2.position)
< sphere1.radius + sphere2.radius)
{
float penetration = sphere1.radius + sphere2.radius -
glm::length(transform1.position - transform2.position);
ECSEntity e = getWorld().createEntity();
Vector3 normal = glm::normalize(transform1.position - transform2.position);
//getWorld().data.renderUtil->DrawLine(transform1.position - sphere1.radius * normal,
// transform1.position - sphere1.radius * normal + penetration * normal, Color(0, 0, 1));
e.addComponent<ParticleContactComponent>(entities[i],
entities[j],
1.0f,
normal,
penetration);
collided = true;
}
}
}
}
// Check collision with Hardcoded walls
if (abs(transform1.position.x) >= 14)
{
float penetration = abs(transform1.position.x) - 14;
ECSEntity e = getWorld().createEntity();
Vector3 normal = (transform1.position.x > 0 ? -1.0f : 1.0f) * Vector3(1, 0, 0);
e.addComponent<ParticleContactComponent>(entities[i],
dummy,
1.0f,
normal,
penetration);
collided = true;
}
if (abs(transform1.position.y - 20) >= 14)
{
float penetration = abs(transform1.position.y - 20) - 14;
ECSEntity e = getWorld().createEntity();
Vector3 normal = ((transform1.position.y - 20) > 0 ? -1.0f : 1.0f) * Vector3(0, 1, 0);
e.addComponent<ParticleContactComponent>(entities[i],
dummy,
1.0f,
normal,
penetration);
collided = true;
}
if (abs(transform1.position.z) >= 14)
{
float penetration = abs(transform1.position.z) - 14;
ECSEntity e = getWorld().createEntity();
Vector3 normal = (transform1.position.z > 0 ? -1.0f : 1.0f) * Vector3(0, 0, 1);
e.addComponent<ParticleContactComponent>(entities[i],
dummy,
1.0f,
normal,
penetration);
collided = true;
}
Color col = collided ? Color(1, 0, 0, 1) : Color(0, 1, 0, 1);
//getWorld().data.renderUtil->DrawSphere(transform1.position, sphere1.radius, col);
}
//getWorld().data.renderUtil->DrawCube(Vector3(0, 20, 0), Vector3(30, 30, 30));
}
}
| 31.778846
| 96
| 0.646596
|
GBCNewGamePlus
|
549e0a60308d6fc7cd2622cc282f2236689aee00
| 2,950
|
cc
|
C++
|
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | 1
|
2021-02-01T11:21:56.000Z
|
2021-02-01T11:21:56.000Z
|
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | null | null | null |
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | 1
|
2022-01-28T15:25:45.000Z
|
2022-01-28T15:25:45.000Z
|
// C++14 (gcc 8.3)
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
constexpr int kG{1'000};
long long CalculateTreeHeight(long long height, int max_velocity) {
return static_cast<long long>(std::pow(max_velocity, 2)) / (2 * kG) + height;
}
class Resident {
public:
Resident(int height, int age, int growth_quotient)
: height_{height}, age_{age}, growth_quotient_{growth_quotient} {}
long long GetTreeHeight(int year, int max_velocity) const {
return CalculateTreeHeight(GetHeight(year), max_velocity);
}
private:
int height_;
int age_;
int growth_quotient_;
long long GetHeight(int year) const {
if (age_ < 20) {
const int growth_years{std::min(year, 20 - age_)};
return static_cast<long long>(height_) +
growth_years * static_cast<long long>(growth_quotient_);
} else {
return height_;
}
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (--t >= 0) {
int max_velocity, n;
std::cin >> max_velocity >> n;
max_velocity *= 100;
std::vector<Resident> residents;
residents.reserve(n);
long long const_min_tree_height{std::numeric_limits<long long>::max()};
long long min_tree_height{std::numeric_limits<long long>::max()};
while (--n >= 0) {
int height, age, growth_quotient;
std::cin >> height >> age >> growth_quotient;
if (age >= 20) {
const long long tree_height{CalculateTreeHeight(height, max_velocity)};
if (tree_height < const_min_tree_height) {
const_min_tree_height = tree_height;
if (const_min_tree_height < min_tree_height) {
min_tree_height = const_min_tree_height;
}
}
} else {
const Resident new_resident(height, age, growth_quotient);
residents.push_back(new_resident);
const long long tree_height{
new_resident.GetTreeHeight(0, max_velocity)};
if (tree_height < min_tree_height) {
min_tree_height = tree_height;
}
}
}
std::cout << "0: " << min_tree_height << "\n";
bool const_heights{false};
for (int year{1}; year <= 20; ++year) {
if (!const_heights) {
min_tree_height = const_min_tree_height;
for (const Resident& resident : residents) {
const long long tree_height{
resident.GetTreeHeight(year, max_velocity)};
if (tree_height < min_tree_height) {
min_tree_height = tree_height;
}
}
if (min_tree_height == const_min_tree_height) {
const_heights = true;
}
std::cout << year << ": " << min_tree_height << "\n";
} else {
std::cout << year << ": " << const_min_tree_height << "\n";
}
}
}
return 0;
}
| 28.365385
| 80
| 0.591525
|
hkktr
|
54a0b6e2a9f9e376b72d0ade5bee4b71640c8e76
| 3,711
|
cpp
|
C++
|
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
#include "EniConfig.h"
#if defined(ENI_GPIO) && defined(ENI_STM)
#include "../Gpio.h"
#include "GpioPin.h"
#if !IS_ENI_GPIO_SUPPORTED
#if defined(ENI_HAL_INCLUDE_FILE)
#include ENI_HAL_INCLUDE_FILE
#else
#error "HAL include file missing declaration"
#endif
#endif
namespace Eni {
void Gpio::applyConfig(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
*(pin.getConfigRegister()) = static_cast<uint32_t>(pin.init.value) << ((pin.pin % (GpioPin::countPinInConfigRegister)) << 2);
#else
HAL_GPIO_Init(pin.port, &pin.init);
#endif
}
void Gpio::initInput(const GpioPin& pin, InputMode inputMode) {
#if IS_ENI_GPIO_SUPPORTED
pin.init.mode.mode = 0;
switch(inputMode) {
case InputMode::Analog:
pin.init.mode.cnf1 = 0;
pin.init.mode.cnf0 = 0;
break;
case InputMode::Floating:
pin.init.mode.cnf1 = 0;
pin.init.mode.cnf0 = 1;
break;
case InputMode::PullDown:
pin.init.mode.cnf1 = 1;
pin.init.mode.cnf0 = 0;
pin.port->ODR &= ~pin.mask;
break;
case InputMode::PullUp:
pin.init.mode.cnf1 = 1;
pin.init.mode.cnf0 = 0;
pin.port->ODR |= pin.mask;
break;
}
#else
pin.init.Mode = GPIO_MODE_INPUT;
switch(inputMode) {
case InputMode::Analog:
pin.init.Mode = GPIO_MODE_ANALOG;
pin.init.Pull = GPIO_NOPULL;
break;
case InputMode::Floating:
pin.init.Pull = GPIO_NOPULL;
break;
case InputMode::PullUp:
pin.init.Pull = GPIO_PULLUP;
break;
case InputMode::PullDown:
pin.init.Pull = GPIO_PULLDOWN;
break;
}
#endif
applyConfig(pin);
}
void Gpio::initOutput(const GpioPin& pin, OutputMode mode, bool isAlternateFunction, PinSpeed speed) {
#if IS_ENI_GPIO_SUPPORTED
pin.init.mode.mode = static_cast<uint8_t>(speed);
pin.init.mode.cnf1 = isAlternateFunction;
switch(mode) {
case OutputMode::PushPull:
pin.init.mode.cnf0 = 0;
break;
case OutputMode::OpenDrain:
pin.init.mode.cnf0 = 1;
break;
}
#else
switch(mode) {
case OutputMode::OpenDrain:
if(isAlternateFunction) {
pin.init.Mode = GPIO_MODE_AF_OD;
}
else {
pin.init.Mode = GPIO_MODE_OUTPUT_OD;
}
break;
case OutputMode::PushPull:
if(isAlternateFunction) {
pin.init.Mode = GPIO_MODE_AF_PP;
}
else {
pin.init.Mode = GPIO_MODE_OUTPUT_PP;
}
break;
}
#endif
applyConfig(pin);
}
void Gpio::disconnect(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
initInput(pin, InputMode::Floating);
#else
HAL_GPIO_DeInit(pin.port, pin.pin);
#endif
}
void Gpio::set(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->BSRR = pin.mask;
#else
HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_SET);
#endif
}
void Gpio::reset(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->BSRR = static_cast<uint32_t>(pin.mask) << 16U;
#else
HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_RESET);
#endif
}
void Gpio::toggle(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->ODR ^= pin.mask;
#else
HAL_GPIO_TogglePin(pin.port, pin.mask);
#endif
}
bool Gpio::read(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
return (pin.port->IDR & pin.mask) != 0;
#else
return HAL_GPIO_ReadPin(pin.port, pin.mask) == GPIO_PIN_SET;
#endif
}
bool Gpio::lock(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
/*LOCK key writing sequence:
Write 1
Write 0
Write 1
Read 0
Read 1 (this read is optional but confirms that the lock is active)
Note: During the LOCK Key Writing sequence, the value of LCK[15:0] must not change
*/
pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask;
pin.port->LCKR = pin.mask;
pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask;
auto dummy = pin.port->LCKR;
static_cast<void>(dummy);
return (pin.port->LCKR & GPIO_LCKR_LCKK) != 0;
#else
return HAL_GPIO_LockPin(pin.port, pin.pin) == HAL_OK;
#endif
}
}
#endif
| 21.327586
| 126
| 0.70574
|
vlad230596
|
54a1285f6999c571c5406de8597e25057d1389cb
| 2,537
|
hpp
|
C++
|
cpp/archive/archive-good-stuff/db.hpp
|
MomsFriendlyRobotCompany/gecko
|
f340381113bdb423a39d47aaee61e013bb9e002a
|
[
"MIT"
] | 2
|
2020-03-11T03:53:19.000Z
|
2020-10-06T03:18:32.000Z
|
cpp/archive/archive-good-stuff/db.hpp
|
MomsFriendlyRobotCompany/gecko
|
f340381113bdb423a39d47aaee61e013bb9e002a
|
[
"MIT"
] | null | null | null |
cpp/archive/archive-good-stuff/db.hpp
|
MomsFriendlyRobotCompany/gecko
|
f340381113bdb423a39d47aaee61e013bb9e002a
|
[
"MIT"
] | null | null | null |
/**************************************************\
* The MIT License (MIT)
* Copyright (c) 2014 Kevin Walchko
* see LICENSE for full details
\**************************************************/
#pragma once
#include <string>
#include <map>
#include <tuple>
#include <exception>
#include <gecko/exceptions.hpp>
struct InvalidKey : public std::exception {
InvalidKey(const std::string &s): msg("Invalid Key: " + s) {}
InvalidKey(): msg("Invalid Key") {}
const char * what () const throw () {return msg.c_str();}
protected:
std::string msg;
};
using record_t = std::tuple<std::string, std::string>; // pid endpt
/*
This is the data base for keeping track of things ... it is simple.
Data is tracked 2 ways:
- binders (topic, (pid, endpt)) are unique and tracked by topic. Only
one process can bind to a topic name
- connectors (pid, (topic, endpt)) are tracked by pid because there
can be a many to one relationship between processes and topics.
*/
class DBv {
public:
DBv(){}
std::string get(const std::string& topic);
void pushbind(const std::string& topic, const std::string& pid, const std::string& endpt);
void pushconn(const std::string& topic, const std::string& pid, const std::string& endpt);
// int size(){ return db.size(); }
void print();
void saveJson(const std::string& filename){throw NotImplemented("DBv::save()");} // value?
protected:
void pop(std::map<std::string, record_t>& db, const std::string& key);
void printDB(int type, std::map<std::string, record_t>& db);
std::map<std::string, record_t> bind, conn;
};
// class DB {
// public:
// DB(){}
// std::tuple<std::string, std::string> get(const std::string& topic);
// void push(const std::string& topic, const std::string& addr, const std::string& pid);
// void pop(const std::string& topic);
// int size(){ return db.size(); }
// void print();
//
// // protected:
// // [topic, (addr, pid)]
// std::map<std::string, std::tuple<std::string, std::string>> db;
// };
// class DBs {
// public:
// DBs(){}
// std::string get(const std::string& key);
// void push(const std::string& key, const std::string& val);
// void pop(const std::string& key);
// int size(){ return db.size(); }
// void print();
// void printPs();
//
// // protected:
// // [topic, (addr, pid)]
// std::map<std::string, std::string> db;
// };
// struct record {
// record() {}
// std::string pid, topic, endpt;
// int type;
// };
| 29.5
| 94
| 0.590067
|
MomsFriendlyRobotCompany
|
54a2408ceeedf2c24a17f3501e5dd355dc4906f8
| 9,375
|
cc
|
C++
|
content/browser/service_worker/service_worker_context_unittest.cc
|
Acidburn0zzz/chromium-1
|
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
content/browser/service_worker/service_worker_context_unittest.cc
|
Acidburn0zzz/chromium-1
|
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
content/browser/service_worker/service_worker_context_unittest.cc
|
Acidburn0zzz/chromium-1
|
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/public/browser/service_worker_context.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "content/browser/browser_thread_impl.h"
#include "content/browser/service_worker/embedded_worker_registry.h"
#include "content/browser/service_worker/embedded_worker_test_helper.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/common/service_worker/service_worker_messages.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
namespace {
void SaveResponseCallback(bool* called,
int64* store_result,
ServiceWorkerStatusCode status,
int64 result) {
*called = true;
*store_result = result;
}
ServiceWorkerContextCore::RegistrationCallback MakeRegisteredCallback(
bool* called,
int64* store_result) {
return base::Bind(&SaveResponseCallback, called, store_result);
}
void CallCompletedCallback(bool* called, ServiceWorkerStatusCode) {
*called = true;
}
ServiceWorkerContextCore::UnregistrationCallback MakeUnregisteredCallback(
bool* called) {
return base::Bind(&CallCompletedCallback, called);
}
void ExpectRegisteredWorkers(
bool expect_pending,
bool expect_active,
ServiceWorkerStatusCode status,
const scoped_refptr<ServiceWorkerRegistration>& registration) {
ASSERT_EQ(SERVICE_WORKER_OK, status);
if (expect_pending)
EXPECT_TRUE(registration->pending_version());
else
EXPECT_FALSE(registration->pending_version());
if (expect_active)
EXPECT_TRUE(registration->active_version());
else
EXPECT_FALSE(registration->active_version());
}
} // namespace
class ServiceWorkerContextTest : public testing::Test {
public:
ServiceWorkerContextTest()
: browser_thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
render_process_id_(99) {}
virtual void SetUp() OVERRIDE {
context_.reset(new ServiceWorkerContextCore(base::FilePath(), NULL));
helper_.reset(new EmbeddedWorkerTestHelper(
context_.get(), render_process_id_));
}
virtual void TearDown() OVERRIDE {
helper_.reset();
context_.reset();
}
protected:
TestBrowserThreadBundle browser_thread_bundle_;
scoped_ptr<ServiceWorkerContextCore> context_;
scoped_ptr<EmbeddedWorkerTestHelper> helper_;
const int render_process_id_;
};
// Make sure basic registration is working.
TEST_F(ServiceWorkerContextTest, Register) {
int64 registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
EXPECT_TRUE(helper_->inner_ipc_sink()->GetUniqueMessageMatching(
ServiceWorkerMsg_InstallEvent::ID));
EXPECT_NE(-1L, registration_id);
context_->storage()->FindRegistrationForId(
registration_id,
base::Bind(&ExpectRegisteredWorkers,
false /* expect_pending */,
true /* expect_active */));
base::RunLoop().RunUntilIdle();
}
class RejectInstallTestHelper : public EmbeddedWorkerTestHelper {
public:
RejectInstallTestHelper(ServiceWorkerContextCore* context,
int mock_render_process_id)
: EmbeddedWorkerTestHelper(context, mock_render_process_id) {}
virtual void OnInstallEvent(int embedded_worker_id,
int request_id,
int active_version_id) OVERRIDE {
SimulateSendMessageToBrowser(
embedded_worker_id,
request_id,
ServiceWorkerHostMsg_InstallEventFinished(
blink::WebServiceWorkerEventResultRejected));
}
};
// Test registration when the service worker rejects the install event. The
// registration callback should indicate success, but there should be no pending
// or active worker in the registration.
TEST_F(ServiceWorkerContextTest, Register_RejectInstall) {
helper_.reset(
new RejectInstallTestHelper(context_.get(), render_process_id_));
int64 registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
EXPECT_TRUE(helper_->inner_ipc_sink()->GetUniqueMessageMatching(
ServiceWorkerMsg_InstallEvent::ID));
EXPECT_NE(-1L, registration_id);
context_->storage()->FindRegistrationForId(
registration_id,
base::Bind(&ExpectRegisteredWorkers,
false /* expect_pending */,
false /* expect_active */));
base::RunLoop().RunUntilIdle();
}
// Test registration when there is an existing registration with no pending or
// active worker.
TEST_F(ServiceWorkerContextTest, Register_DuplicateScriptNoActiveWorker) {
helper_.reset(
new RejectInstallTestHelper(context_.get(), render_process_id_));
int64 old_registration_id = -1L;
bool called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(2UL, helper_->ipc_sink()->message_count());
int64 new_registration_id = -1L;
called = false;
context_->RegisterServiceWorker(
GURL("http://www.example.com/*"),
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(called);
EXPECT_EQ(old_registration_id, new_registration_id);
// Our current implementation does the full registration flow on re-register,
// so the worker receives another start message and install message.
EXPECT_EQ(4UL, helper_->ipc_sink()->message_count());
}
// Make sure registrations are cleaned up when they are unregistered.
TEST_F(ServiceWorkerContextTest, Unregister) {
GURL pattern("http://www.example.com/*");
bool called = false;
int64 registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, ®istration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
context_->UnregisterServiceWorker(
pattern, render_process_id_, MakeUnregisteredCallback(&called));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
}
// Make sure that when a new registration replaces an existing
// registration, that the old one is cleaned up.
TEST_F(ServiceWorkerContextTest, RegisterNewScript) {
GURL pattern("http://www.example.com/*");
bool called = false;
int64 old_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker.js"),
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
int64 new_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
GURL("http://www.example.com/service_worker_new.js"),
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
ASSERT_NE(old_registration_id, new_registration_id);
}
// Make sure that when registering a duplicate pattern+script_url
// combination, that the same registration is used.
TEST_F(ServiceWorkerContextTest, RegisterDuplicateScript) {
GURL pattern("http://www.example.com/*");
GURL script_url("http://www.example.com/service_worker.js");
bool called = false;
int64 old_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
script_url,
render_process_id_,
MakeRegisteredCallback(&called, &old_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
called = false;
int64 new_registration_id = -1L;
context_->RegisterServiceWorker(
pattern,
script_url,
render_process_id_,
MakeRegisteredCallback(&called, &new_registration_id));
ASSERT_FALSE(called);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(called);
ASSERT_EQ(old_registration_id, new_registration_id);
}
} // namespace content
| 31.779661
| 80
| 0.730773
|
Acidburn0zzz
|
54a47a460b163f0d3a76d7153685638c52a9e81b
| 2,135
|
cc
|
C++
|
deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc
|
ryuichiueda/ProbabilisticRaspiMouse
|
de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4
|
[
"MIT"
] | 5
|
2015-08-08T09:25:35.000Z
|
2022-02-17T04:43:10.000Z
|
deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc
|
ryuichiueda/ProbabilisticRaspiMouse
|
de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4
|
[
"MIT"
] | null | null | null |
deadrec_montecarlo_gyro/DeadRecMonteCarlo.cc
|
ryuichiueda/ProbabilisticRaspiMouse
|
de1c58f93d664d15d4b3f8f99c5a2ce6e56240c4
|
[
"MIT"
] | null | null | null |
#include "DeadRecMonteCarlo.h"
#include <iostream>
#include <limits.h>
#include <cmath>
using namespace std;
DeadRecMonteCarlo::DeadRecMonteCarlo(int num, ifstream *ifs)
{
Pose p{0.0,0.0,0.0};
m_poses.insert(m_poses.begin(),num,p);
m_rand_ifs = ifs;
m_step = 0;
m_distance_max_noise_ratio = 0.05; // 5% noise
m_direction_max_noise_ratio = 0.01; // 1% noise
}
DeadRecMonteCarlo::~DeadRecMonteCarlo()
{
}
void DeadRecMonteCarlo::motionUpdate(double fw_delta_mm,double side_delta_mm,double t_delta_deg)
{
double t_delta_rad = t_delta_deg * 3.141592 / 180;
for(auto &p : m_poses){
//xy方向
double pos_noise = m_distance_max_noise_ratio * getDoubleRand();
double pos_noise_angle = getDoubleRand() * 2 * 3.141592;
double x_noise = pos_noise * cos(pos_noise_angle);
double y_noise = pos_noise * sin(pos_noise_angle);
p.x_mm += fw_delta_mm * (cos(p.t_rad) + x_noise) + side_delta_mm * sin(p.t_rad);
p.y_mm += fw_delta_mm * (sin(p.t_rad) + y_noise) + side_delta_mm * cos(p.t_rad);
//theta方向
double ratio = m_direction_max_noise_ratio * (2*getDoubleRand()-1.0);
p.t_rad += t_delta_rad * (1.0 + ratio);
}
m_step++;
}
void DeadRecMonteCarlo::pointReset(double x_mm,double y_mm,double t_deg,
double pos_max_noise_mm,double dir_max_noise_deg)
{
for(auto &p : m_poses){
double dir_noise = dir_max_noise_deg *(2*getDoubleRand() - 1.0);
double pos_noise = pos_max_noise_mm * getDoubleRand();
double pos_noise_angle = getDoubleRand() * 2 * 3.141592;
double x_noise = pos_noise * cos(pos_noise_angle);
double y_noise = pos_noise * sin(pos_noise_angle);
p = {x_mm+x_noise, y_mm+y_noise, (t_deg + dir_noise)/180*3.141592};
}
}
// from 0 to UINT_MAX
unsigned int DeadRecMonteCarlo::getIntRand()
{
char buf[4];
m_rand_ifs->read(buf,4);
return (buf[0]<<24) + (buf[1]<<16) + (buf[2]<<8) + buf[3];
}
// from 0.0 to 1.0
double DeadRecMonteCarlo::getDoubleRand()
{
return (double)getIntRand() / UINT_MAX;
}
void DeadRecMonteCarlo::print(ofstream *ofs)
{
for(auto &p : m_poses){
*ofs << m_step << " " << (int)p.x_mm << " " << (int)p.y_mm << " "
<< (int)(p.t_rad / 3.141592 * 180) << endl;
}
}
| 26.6875
| 96
| 0.694145
|
ryuichiueda
|
54a900df45ab89a3259ef4d311d1653fe67ab3c8
| 2,098
|
hpp
|
C++
|
linkedlist.hpp
|
joshroybal/cpp-data_structures
|
3a570547d096da07c0b65ac0049d58e8d37f8dc3
|
[
"MIT"
] | null | null | null |
linkedlist.hpp
|
joshroybal/cpp-data_structures
|
3a570547d096da07c0b65ac0049d58e8d37f8dc3
|
[
"MIT"
] | null | null | null |
linkedlist.hpp
|
joshroybal/cpp-data_structures
|
3a570547d096da07c0b65ac0049d58e8d37f8dc3
|
[
"MIT"
] | null | null | null |
#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP
#include <iostream>
#include <iomanip>
template <class T>
class LinkedList
{
public:
LinkedList() { head_ = 0; }
~LinkedList() { destroy_(head_); }
void Add(const T& k) { head_ = add_(k); }
void Reverse() { head_ = reverse_(head_, 0); }
int Size() const { return size_(head_, 0); }
void Print() const { print_(head_); }
void Report() const;
private:
struct Node;
Node* head_;
void destroy_(Node*);
Node* add_(const T&);
Node* reverse_(Node*, Node*);
int size_(const Node*, int) const;
void print_(const Node*) const;
void printnode_(const Node*) const;
};
template <class T>
struct LinkedList<T>::Node {
Node(const T& k, Node* p=0) : key(k), next(p) {}
T key;
Node* next;
void print() const
{
std::cout << std::setw(10) << this << ':';
std::cout << std::setw(20) << key;
std::cout << std::setw(10) << next << std::endl;
}
};
template <class T>
void LinkedList<T>::Report() const
{
Print();
std::cout << "size = " << Size() << std::endl;
}
template <class T>
void LinkedList<T>::destroy_(Node* node)
{
if (!node) return;
Node* next = node->next;
delete node;
node = 0;
destroy_(next);
}
template <class T>
typename LinkedList<T>::Node* LinkedList<T>::add_(const T& k)
{
return new Node(k, head_);
}
template <class T>
typename LinkedList<T>::Node* LinkedList<T>::reverse_(Node* head, Node* prev)
{
if (!head) return(prev);
Node* body = head->next;
head->next = prev;
return reverse_(body, head);
}
template <class T>
int LinkedList<T>::size_(const Node* node, int siz) const
{
if (!node) return siz;
return size_(node->next, ++siz);
}
template <class T>
void LinkedList<T>::print_(const Node* node) const
{
if (!node) return;
printnode_(node);
print_(node->next);
}
template <class T>
void LinkedList<T>::printnode_(const Node* node) const
{
if (!node) {
std::cout << std::setw(10) << node << std::endl;
return;
}
node->print();
}
#endif
| 20.98
| 77
| 0.596759
|
joshroybal
|
54a9ea3d1cf584a8d1505c07faf72697055e4aa0
| 26,301
|
cpp
|
C++
|
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | 11
|
2020-11-04T13:51:19.000Z
|
2022-02-24T23:11:44.000Z
|
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | null | null | null |
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | 3
|
2022-01-23T10:14:56.000Z
|
2022-03-30T13:35:10.000Z
|
// Copyright Daniel Orchard 2020
#include "SLoaderWindow.h"
#include "Vault.h"
#include "VaultSettings.h"
#include "MetadataOps.h"
#include "SAssetPackTile.h"
#include "VaultStyle.h"
#include "AssetPublisher.h"
#include "VaultTypes.h"
#include "ImageUtils.h"
#include "EditorStyleSet.h"
#include "PakFileUtilities.h"
#include "EditorFramework/AssetImportData.h"
#include "AssetImportTask.h"
#include "AssetToolsModule.h"
#define LOCTEXT_NAMESPACE "SVaultLoader"
const int32 SLoaderWindow::THUMBNAIL_BASE_HEIGHT = 415;
const int32 SLoaderWindow::THUMBNAIL_BASE_WIDTH = 415;
const int32 SLoaderWindow::TILE_BASE_HEIGHT = 465;
const int32 SLoaderWindow::TILE_BASE_WIDTH = 415;
namespace VaultColumnNames
{
static const FName TagCheckedColumnName(TEXT("Flag"));
static const FName TagNameColumnName(TEXT("Tag Name"));
static const FName TagCounterColumnName(TEXT("Used"));
};
class VAULT_API STagFilterRow : public SMultiColumnTableRow<FTagFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(STagFilterRow) {}
SLATE_ARGUMENT(FTagFilteringItemPtr, TagData)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
TagData = InArgs._TagData;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FTagFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveTagFilters(TagData->Tag, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &STagFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(TagData->Tag));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(TagData->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FTagFilteringItemPtr TagData;
TSharedPtr<SLoaderWindow> ParentWindow;
};
class VAULT_API SDeveloperFilterRow : public SMultiColumnTableRow<FDeveloperFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(SDeveloperFilterRow) {}
SLATE_ARGUMENT(FDeveloperFilteringItemPtr, Entry)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
Entry = InArgs._Entry;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FDeveloperFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveDevFilters(Entry->Developer, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &SDeveloperFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromName(Entry->Developer));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(Entry->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FDeveloperFilteringItemPtr Entry;
TSharedPtr<SLoaderWindow> ParentWindow;
};
void SLoaderWindow::Construct(const FArguments& InArgs, const TSharedRef<SDockTab>& ConstructUnderMajorTab, const TSharedPtr<SWindow>& ConstructUnderWindow)
{
RefreshAvailableFiles();
PopulateBaseAssetList();
PopulateTagArray();
PopulateDeveloperNameArray();
// Bind to our publisher so we can refresh automatically when the user publishes an asset (they wont need to import it, but its a visual feedback for the user to check it appeared in the library
UAssetPublisher::OnVaultPackagingCompletedDelegate.BindRaw(this, &SLoaderWindow::OnNewAssetPublished);
// Construct the Holder for the Metadata List
MetadataWidget = SNew(SVerticalBox);
// Set the Default Scale for Sliders.
TileUserScale = 0.5;
const float TILE_SCALED_WIDTH = TILE_BASE_WIDTH * TileUserScale;
const float TILE_SCALED_HEIGHT = TILE_BASE_HEIGHT * TileUserScale;
// Main Widget
TSharedRef<SVerticalBox> LoaderRoot = SNew(SVerticalBox)
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
// Primary 3 Boxes go in Here
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
[
SNew(SSplitter)
.Orientation(Orient_Horizontal)
+SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+SVerticalBox::Slot()
.Padding(0,3,0,5)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderSidebarHeaderLabel", "FILTERING"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
// Asset List Amount
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.Padding(0,0,0,5)
[
SNew(STextBlock)
.Text(this, &SLoaderWindow::DisplayTotalAssetsInLibrary)
]
// Tag filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FTagFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&TagCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeTagFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Developer Filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FDeveloperFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&DeveloperCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeDeveloperFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Misc Filtering
+SVerticalBox::Slot()
// Spacer
+ SVerticalBox::Slot()
[
SNew(SSpacer)
]
// Selected Asset metadata
+ SVerticalBox::Slot()
] // close SBorder
] // ~Close Left Splitter Area
// Center Area!
+SSplitter::Slot()
.Value(0.6f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(1)
.Padding(FMargin(0,3,0,0))
[
// Center content area
SAssignNew(SearchBox, SSearchBox)
.HintText(LOCTEXT("SearchBoxHintText", "Search..."))
.OnTextChanged(this, &SLoaderWindow::OnSearchBoxChanged)
.OnTextCommitted(this, &SLoaderWindow::OnSearchBoxCommitted)
.DelayChangeNotificationsWhileTyping(false)
.Visibility(EVisibility::Visible)
.Style(FVaultStyle::Get(), "AssetSearchBar")
.AddMetaData<FTagMetaData>(FTagMetaData(TEXT("AssetSearch")))
]
+ SHorizontalBox::Slot()
.Padding(FMargin(15.f,0.f, 5.f, 0.f))
.AutoWidth()
[
SAssignNew(StrictSearchCheckBox, SCheckBox)
.Style(FCoreStyle::Get(), "ToggleButtonCheckbox")
.Padding(FMargin( 5.f,0.f ))
.ToolTipText(LOCTEXT("StrictSearchToolTip", "Search only the Pack Names"))
[
SNew(SBox)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.Padding(FMargin(4.f,2.f))
[
SNew(STextBlock)
.Text(LOCTEXT("StrictSearchCheckBox", "Strict Search"))
]
]
]
]
// Tile View
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
SNew(SBox)
.Padding(FMargin(5,5,5,5))
[
SAssignNew(TileView, STileView<TSharedPtr<FVaultMetadata>>)
.ItemWidth(TILE_SCALED_WIDTH)
.ItemHeight(TILE_SCALED_HEIGHT)
.ItemAlignment(EListItemAlignment::EvenlyDistributed)
.ListItemsSource(&FilteredAssetItems)
.OnGenerateTile(this, &SLoaderWindow::MakeTileViewWidget)
.SelectionMode(ESelectionMode::Single)
.OnSelectionChanged(this, &SLoaderWindow::OnAssetTileSelectionChanged)
.OnMouseButtonDoubleClick(this, &SLoaderWindow::OnAssetTileDoubleClicked)
.OnContextMenuOpening(this, &SLoaderWindow::OnAssetTileContextMenuOpened)
]
]
// Bottom Bar
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SButton)
.Text(LOCTEXT("RefreshLibraryScreenBtnLbl", "Refresh Library"))
.OnClicked(this, &SLoaderWindow::OnRefreshLibraryClicked)
]
+ SHorizontalBox::Slot()
[
SNew(SSpacer)
]
+ SHorizontalBox::Slot()
[
// Scale Slider
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.HAlign(HAlign_Right)
.Padding(FMargin(0, 0, 0, 0))
[
SNew(STextBlock)
.Text(LOCTEXT("ScaleSliderLabel", "Thumbnail Scale"))
.Justification(ETextJustify::Right)
]
+ SHorizontalBox::Slot()
[
SAssignNew(UserScaleSlider, SSlider)
.Value(TileUserScale)
.MinValue(0.2)
.OnValueChanged(this, &SLoaderWindow::OnThumbnailSliderValueChanged)
]
]
]
] // close border for center area
] // ~ Close Center Area Splitter
// Metadata Zone
+ SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderRightSidebarHeaderLabel", "METADATA"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
+ SVerticalBox::Slot()
.FillHeight(1)
[
SNew(SBox)
[
MetadataWidget.ToSharedRef()
]
]
]
]
] // ~ hbox
]; // ~ LoaderRoot
ChildSlot
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.DarkGroupBorder"))
.Padding(FMargin(2.f,2.f))
[
LoaderRoot
]
];
}
void SLoaderWindow::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
}
void SLoaderWindow::PopulateBaseAssetList()
{
FilteredAssetItems.Empty();
for (FVaultMetadata Meta : MetaFilesCache)
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Meta)));
}
}
// Only shows tags that are actually used, no empty tags will appear.
void SLoaderWindow::PopulateTagArray()
{
// Empty Tag Container
TagCloud.Empty();
// Create a map version of the array for more efficient searching.
TMap<FString, FTagFilteringItemPtr> TagCloudMap;
// For each Asset in our global list of assets...
for (auto Asset : MetaFilesCache)
{
// Get each tag belonging to that asset...
for (const FString AssetTag : Asset.Tags)
{
// If we already have a tag stored for it, increment the use counter
if (TagCloudMap.Contains(AssetTag))
{
TagCloudMap.Find(AssetTag)->Get()->UseCount++;
}
// otherwise, add a new tag to our list.
else
{
FTagFilteringItemPtr TagTemp = MakeShareable(new FTagFilteringItem);
TagTemp->Tag = AssetTag;
TagTemp->UseCount = 1;
TagCloudMap.Add(AssetTag, TagTemp);
}
}
}
// The Map version is easier to work with during generation, but since we have to use an Array, we convert our cloud map into an array now:
TagCloudMap.GenerateValueArray(TagCloud);
}
void SLoaderWindow::PopulateDeveloperNameArray()
{
// Developer Array
DeveloperCloud.Empty();
TMap<FName, int32> DevAssetCounter;
for (auto AssetItem : FilteredAssetItems)
{
if (DevAssetCounter.Contains(AssetItem->Author))
{
int Count = *DevAssetCounter.Find(AssetItem->Author);
Count++;
DevAssetCounter.Add(AssetItem->Author, Count);
}
else
{
DevAssetCounter.Add(AssetItem->Author, 1);
}
}
for (auto dev : DevAssetCounter)
{
FDeveloperFilteringItemPtr DevTemp = MakeShareable(new FDeveloperFilteringItem);
DevTemp->Developer = dev.Key;
DevTemp->UseCount = dev.Value;
DeveloperCloud.AddUnique(DevTemp);
}
}
TSharedRef<ITableRow> SLoaderWindow::MakeTileViewWidget(TSharedPtr<FVaultMetadata> AssetItem, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STableRow<TSharedPtr<FVaultMetadata>>, OwnerTable)
.Style(FEditorStyle::Get(), "ContentBrowser.AssetListView.TableRow")
.Padding(FMargin(5.0f, 5.0f, 5.0f, 25.0f))
[
SNew(SAssetTileItem)
.AssetItem(AssetItem)
];
}
TSharedRef<ITableRow> SLoaderWindow::MakeTagFilterViewWidget(FTagFilteringItemPtr inTag, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STagFilterRow, OwnerTable)
.TagData(inTag)
.ParentWindow(SharedThis(this));
}
TSharedRef<ITableRow> SLoaderWindow::MakeDeveloperFilterViewWidget(FDeveloperFilteringItemPtr Entry, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(SDeveloperFilterRow, OwnerTable)
.Entry(Entry)
.ParentWindow(SharedThis(this));
}
void SLoaderWindow::OnAssetTileSelectionChanged(TSharedPtr<FVaultMetadata> InItem, ESelectInfo::Type SelectInfo)
{
// Checks if anything is selected
if (TileView->GetNumItemsSelected() > 0)
{
ConstructMetadataWidget(InItem);
return;
}
// If no selection, clear the active metadata.
MetadataWidget->ClearChildren();
}
void SLoaderWindow::OnAssetTileDoubleClicked(TSharedPtr<FVaultMetadata> InItem)
{
// #todo Add Item to Project on Double Click
LoadAssetPackIntoProject(InItem);
}
TSharedPtr<SWidget> SLoaderWindow::OnAssetTileContextMenuOpened()
{
// Lets check we have stuff selected, we only want the context menu on selected items. No need to open on a blank area
if (TileView->GetNumItemsSelected() == 0)
{
return SNullWidget::NullWidget;
}
// Store our selected item for any future operations.
TSharedPtr<FVaultMetadata> SelectedAsset = TileView->GetSelectedItems()[0];
FMenuBuilder MenuBuilder(true, nullptr, nullptr, true);
static const FName FilterSelectionHook("AssetContextMenu");
MenuBuilder.BeginSection(FilterSelectionHook, LOCTEXT("AssetContextMenuLabel", "Vault Asset"));
{
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_AddToProjectLabel", "Add To Project"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
LoadAssetPackIntoProject(SelectedAsset);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_EditVaultAssetDetailsLabel", "Edit Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString MetaFilePath = LibraryPath / SelectedAsset->PackName.ToString() + ".meta";
// Rather than provide a tonne of edit options in engine and a load of extra UI support, for the time being lets just open the file in a text editor
FPlatformProcess::LaunchFileInDefaultExternalApplication(*MetaFilePath);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_DeleteVaultAssetLabel", "Delete Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
// Open a Msg dialog to confirm deletion
const EAppReturnType::Type Confirmation = FMessageDialog::Open(EAppMsgType::YesNo, LOCTEXT("DeleteViaContextMsg", "Are you sure you want to delete this asset from the Vault Library \nThis option cannot be undone." ));
if (Confirmation == EAppReturnType::Yes)
{
// Delete Pack. Handles all the UI stuff from here as well as the file deletes.
DeleteAssetPack(SelectedAsset);
}
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
}
MenuBuilder.EndSection();
return MenuBuilder.MakeWidget();
}
void SLoaderWindow::OnSearchBoxChanged(const FText& inSearchText)
{
//FilteredAssetItems.Empty();
// If its now empty, it was probably cleared or backspaced through, so we need to reapply just the filter based results.
if (inSearchText.IsEmpty())
{
UpdateFilteredAssets();
return;
}
// Store Strict Search - This controls if we only search pack name, or various data entries.
const bool bStrictSearch = StrictSearchCheckBox->GetCheckedState() == ECheckBoxState::Checked;
const FString SearchString = inSearchText.ToString();
// Holder for the newly filtered Results:
TArray<TSharedPtr<FVaultMetadata>> SearchMatchingEntries;
// Instead of searching raw meta, we search the filtered results, so this respects the tag and dev filters first, and we search within that.
for (auto Meta : FilteredAssetItems)
{
if (Meta->PackName.ToString().Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
continue;
}
if (bStrictSearch == false)
{
if (Meta->Author.ToString().Contains(SearchString) || Meta->Description.Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
}
}
}
FilteredAssetItems = SearchMatchingEntries;
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnSearchBoxCommitted(const FText& InFilterText, ETextCommit::Type CommitType)
{
OnSearchBoxChanged(InFilterText);
}
void SLoaderWindow::ConstructMetadataWidget(TSharedPtr<FVaultMetadata> AssetMeta)
{
// Safety Catches for Null Assets. Should never occur.
if (!MetadataWidget.IsValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Ptr is Null."));
return;
}
if (!AssetMeta.IsValid() || !AssetMeta->IsMetaValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Incoming Data is Null."));
return;
}
// Padding between words
const FMargin WordPadding = FMargin(0.f,12.f,0.f,0.f);
MetadataWidget->ClearChildren();
// Pack Name
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::FromName(AssetMeta->PackName))
];
// Description
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_DescLbl", "Description: \n{0}"), FText::FromString(AssetMeta->Description)))
.Text(FText::FromString(AssetMeta->Description))
];
// Author
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_AuthorLbl", "Author: {0}"), FText::FromName(AssetMeta->Author)))
];
// Creation Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_CreationLbl", "Created: {0}"), FText::FromString(AssetMeta->CreationDate.ToString())))
];
// Last Modified Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_LastModifiedLbl", "Last Modified: {0}"), FText::FromString(AssetMeta->LastModified.ToString())))
];
// Tags List - Header
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_TagsLbl", "Tags: {0}"), FText::FromString(FString::Join(AssetMeta->Tags.Array(), TEXT(",")))))
.Text(LOCTEXT("Meta_TagsLbl", "Tags:"))
];
// Tags, Per Tag. Instead of using Join, we add them as separate lines for ease of reading
for (auto MyTag : AssetMeta->Tags)
{
MyTag.TrimStartAndEndInline();
const FText TagName = FText::FromString(MyTag);
//MyTag.RemoveSpacesInline();
MetadataWidget->AddSlot()
.AutoHeight()
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("PerTagKeyFor{0}", "- {1}"), TagName, TagName))
];
}
// Object List
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
.Text(FText::Format(LOCTEXT("Meta_FilesLbl", "Files: {0}"), FText::FromString(FString::Join(AssetMeta->ObjectsInPack.Array(), TEXT(",")))))
];
}
void SLoaderWindow::LoadAssetPackIntoProject(TSharedPtr<FVaultMetadata> InPack)
{
// Root Directory
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
// All files live in same directory, so we just do some string mods to get the pack file that matches the meta file.
const FString AssetToImportTemp = LibraryPath / InPack->PackName.ToString() + ".upack";
// UPacks import natively with Unreal, so no need to try to use the PakUtilities, better to use the native importer and let Unreal handle the Pak concepts.
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
// Set up our Import Task
UAssetImportTask* Task = NewObject<UAssetImportTask>();
Task->AddToRoot();
Task->bAutomated = true;
Task->bReplaceExisting = true;
Task->bSave = true;
Task->Filename = AssetToImportTemp;
Task->DestinationPath = "/Game";
TArray<UAssetImportTask*> Tasks;
Tasks.Add(Task);
AssetToolsModule.Get().ImportAssetTasks(Tasks);
// Allow GC to collect
Task->RemoveFromRoot();
}
void SLoaderWindow::DeleteAssetPack(TSharedPtr<FVaultMetadata> InPack)
{
// Confirmation will have occurred already for this operation (Might be changed in future to have confirmation here)
UE_LOG(LogVault, Display, TEXT("Deleting File(s) from Vault: %s"), *InPack->PackName.ToString());
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString FilePathAbsNoExt = LibraryPath / InPack->PackName.ToString();
const FString AbsThumbnailPath = FilePathAbsNoExt + ".png";
const FString AbsMetaPath = FilePathAbsNoExt + ".meta";
const FString AbsPackPath = FilePathAbsNoExt + ".upack";
IFileManager::Get().Delete(*AbsThumbnailPath, true);
IFileManager::Get().Delete(*AbsMetaPath, true);
IFileManager::Get().Delete(*AbsPackPath, true);
MetaFilesCache.Remove(*InPack);
RefreshLibrary();
//UpdateFilteredAssets();
//TileView->RebuildList();
}
void SLoaderWindow::RefreshAvailableFiles()
{
MetaFilesCache = FMetadataOps::FindAllMetadataInLibrary();
}
// Applies the List of filters all together.
void SLoaderWindow::UpdateFilteredAssets()
{
FilteredAssetItems.Empty();
// Special Condition to check if all boxes are cleared:
if (ActiveTagFilters.Num() == 0 && ActiveDevFilters.Num() == 0)
{
PopulateBaseAssetList();
TileView->RebuildList();
TileView->ScrollToTop();
return;
}
for (auto Asset : MetaFilesCache)
{
// Apply all filtered Tags
for (auto UserTag : Asset.Tags)
{
if (ActiveTagFilters.Contains(UserTag))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
break;
}
}
// Apply All Developer Tags
if (ActiveDevFilters.Contains(Asset.Author))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
continue;
}
}
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnThumbnailSliderValueChanged(float Value)
{
TileUserScale = Value;
TileView->SetItemWidth(TILE_BASE_WIDTH * TileUserScale);
TileView->SetItemHeight(TILE_BASE_HEIGHT * TileUserScale);
TileView->RebuildList();
}
FText SLoaderWindow::DisplayTotalAssetsInLibrary() const
{
int assetCount = FMetadataOps::FindAllMetadataInLibrary().Num();
FText Display = FText::Format(LOCTEXT("displayassetcountlabel", "Total Assets in library: {0}"),assetCount);
return Display;
}
FReply SLoaderWindow::OnRefreshLibraryClicked()
{
RefreshLibrary();
return FReply::Handled();
}
void SLoaderWindow::RefreshLibrary()
{
RefreshAvailableFiles();
PopulateTagArray();
PopulateDeveloperNameArray();
//SearchBox->AdvanceSearch//
//TileView->RebuildList();
UpdateFilteredAssets();
}
void SLoaderWindow::OnNewAssetPublished()
{
RefreshLibrary();
}
void SLoaderWindow::ModifyActiveTagFilters(FString TagModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Tag Filter For %s"), *TagModified);
if (bFilterThis)
{
// Push our Active Tag into our Set of Tags currently being searched
ActiveTagFilters.Add(TagModified);
UpdateFilteredAssets();
return;
}
ActiveTagFilters.Remove(TagModified);
UpdateFilteredAssets();
}
void SLoaderWindow::ModifyActiveDevFilters(FName DevModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Dev Filter %s"), *DevModified.ToString());
if (bFilterThis)
{
ActiveDevFilters.Add(DevModified);
UpdateFilteredAssets();
return;
}
ActiveDevFilters.Remove(DevModified);
UpdateFilteredAssets();
}
#undef LOCTEXT_NAMESPACE
| 27.685263
| 222
| 0.705943
|
Unreal-Vault
|
54ab167058ce125f5fa40b23910f9857416f3ac2
| 276
|
hpp
|
C++
|
src/Time.hpp
|
matheuscscp/parallel-programming-final-project
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | 2
|
2019-05-26T17:13:23.000Z
|
2019-06-09T05:48:57.000Z
|
src/Time.hpp
|
matheuscscp/delta-stepping
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | null | null | null |
src/Time.hpp
|
matheuscscp/delta-stepping
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | null | null | null |
/*
* Time.hpp
*
* Created on: Nov 20, 2014
* Author: matheus
*/
#ifndef TIME_HPP_
#define TIME_HPP_
#include <sys/time.h>
class Stopwatch {
private:
timeval i;
public:
Stopwatch();
void start();
float time() const;
};
#endif /* TIME_HPP_ */
| 12
| 28
| 0.594203
|
matheuscscp
|
54ab50e9d1dc5c0ea91d3cb67f1434487d879004
| 681
|
cpp
|
C++
|
C++/holes.cpp
|
MADHAVAN001/Competitive-Programming-Practice
|
ca895315078880b403f4656677f60905681e7b86
|
[
"MIT"
] | null | null | null |
C++/holes.cpp
|
MADHAVAN001/Competitive-Programming-Practice
|
ca895315078880b403f4656677f60905681e7b86
|
[
"MIT"
] | null | null | null |
C++/holes.cpp
|
MADHAVAN001/Competitive-Programming-Practice
|
ca895315078880b403f4656677f60905681e7b86
|
[
"MIT"
] | null | null | null |
using namespace std;
#include<stdio.h>
#include<iostream>
int main()
{
int num_lines;
int count[50];
char text[50][100];
std::cout<<"This is the program to count number of holes in text";
std::cout<<endl<<"Please enter the number of lines follwed by each of the lines: ";
cin>>num_lines;
for(int i = 0;i<num_lines;i++)
{
cin>>text[i];
count[i] = 0;
for(int j = 0;text[i][j] != '\0';j++)
{
if(text[i][j] == 'A' || text[i][j] == 'O' || text[i][j] == 'R' || text[i][j] == 'D' || text[i][j] == 'P' ||text[i][j] == 'Q')
count[i]++;
else if(text[i][j] == 'B')
count[i]+=2;
}
}
std::cout<<endl;
for(int i = 0;i<num_lines;i++)
std::cout<<count[i]<<endl;
return 0;
}
| 20.636364
| 127
| 0.562408
|
MADHAVAN001
|
54ab7ccc3f96c9c82b3d77678a96f0a80fb2ec06
| 51
|
hpp
|
C++
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/metaparse/limit_sequence_size.hpp>
| 25.5
| 50
| 0.843137
|
miathedev
|
54b018813113477897e3df2360859fed801e2c3f
| 18,212
|
cpp
|
C++
|
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | 3
|
2021-07-12T05:38:00.000Z
|
2022-03-02T14:55:23.000Z
|
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | null | null | null |
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | null | null | null |
/* Generated by Edge Impulse
*
* 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.
*/
// Generated on: 11.11.2020 18:46:14
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "edge-impulse-sdk/tensorflow/lite/c/builtin_op_data.h"
#include "edge-impulse-sdk/tensorflow/lite/c/common.h"
#include "edge-impulse-sdk/tensorflow/lite/micro/kernels/micro_ops.h"
#if defined __GNUC__
#define ALIGN(X) __attribute__((aligned(X)))
#elif defined _MSC_VER
#define ALIGN(X) __declspec(align(X))
#elif defined __TASKING__
#define ALIGN(X) __align(X)
#endif
namespace {
constexpr int kTensorArenaSize = 144;
uint8_t* tensor_arena = NULL;
static uint8_t* current_location;
static uint8_t* tensor_boundary;
template <int SZ, class T> struct TfArray {
int sz; T elem[SZ];
};
enum used_operators_e {
OP_FULLY_CONNECTED, OP_SOFTMAX, OP_LAST
};
struct TensorInfo_t { // subset of TfLiteTensor used for initialization from constant memory
TfLiteAllocationType allocation_type;
TfLiteType type;
void* data;
TfLiteIntArray* dims;
size_t bytes;
TfLiteQuantization quantization;
};
struct NodeInfo_t { // subset of TfLiteNode used for initialization from constant memory
struct TfLiteIntArray* inputs;
struct TfLiteIntArray* outputs;
void* builtin_data;
used_operators_e used_op_index;
};
TfLiteContext ctx{};
TfLiteTensor tflTensors[11];
TfLiteRegistration registrations[OP_LAST];
TfLiteNode tflNodes[4];
const TfArray<2, int> tensor_dimension0 = { 2, { 1,33 } };
const TfArray<1, float> quant0_scale = { 1, { 359.61181640625, } };
const TfArray<1, int> quant0_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant0 = { (TfLiteFloatArray*)&quant0_scale, (TfLiteIntArray*)&quant0_zero, 0 };
const ALIGN(8) int32_t tensor_data1[20] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension1 = { 1, { 20 } };
const TfArray<1, float> quant1_scale = { 1, { 0.99230742454528809, } };
const TfArray<1, int> quant1_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant1 = { (TfLiteFloatArray*)&quant1_scale, (TfLiteIntArray*)&quant1_zero, 0 };
const ALIGN(8) int32_t tensor_data2[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension2 = { 1, { 10 } };
const TfArray<1, float> quant2_scale = { 1, { 0.73306155204772949, } };
const TfArray<1, int> quant2_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant2 = { (TfLiteFloatArray*)&quant2_scale, (TfLiteIntArray*)&quant2_zero, 0 };
const ALIGN(8) int32_t tensor_data3[2] = { 0, 0, };
const TfArray<1, int> tensor_dimension3 = { 1, { 2 } };
const TfArray<1, float> quant3_scale = { 1, { 1.3037328720092773, } };
const TfArray<1, int> quant3_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant3 = { (TfLiteFloatArray*)&quant3_scale, (TfLiteIntArray*)&quant3_zero, 0 };
const ALIGN(8) int8_t tensor_data4[20*33] = {
-82, -76, -66, 21, -13, 18, -95, -81, -91, 24, 114, -53, -74, 113, 57, 125, 117, -32, 89, -70, 111, -102, 120, -80, -62, -62, -102, 56, -40, -35, -69, -100, 29,
10, 20, -6, -53, 19, 107, 70, 95, -102, 72, 58, -60, -31, -105, -75, -49, -52, -102, 86, 55, -5, -68, -102, -73, 32, -75, 26, 51, -70, -1, 92, 104, -119,
8, -109, -86, 58, 9, 34, -106, -20, -72, 21, -32, -27, -80, -26, 74, -98, -75, -28, 97, -113, 74, -13, -52, 33, -45, 111, 20, -55, -10, -68, -72, 99, -97,
-125, -41, -103, 41, 26, 29, -90, 15, 13, 95, -5, -108, 14, 50, 1, -60, -38, -29, 115, 70, -117, -77, 114, -15, -23, 103, 3, -47, 87, 14, -6, 82, 5,
-5, 62, -78, 69, 30, 101, -99, -53, 18, 32, 33, -4, -13, -32, -106, -13, -67, -61, 23, 15, 10, -51, -52, 20, -19, -59, 97, 42, 103, -7, 4, -70, -68,
69, -60, -14, -12, 5, 52, 37, 47, 5, -92, -52, -70, 117, -52, 98, 24, -55, 46, 79, 103, -60, -109, -16, -32, -74, 64, 26, -40, 72, 47, 60, 121, 12,
-81, 118, -6, -32, -37, 45, 45, -24, -49, 74, -91, -84, -112, -79, 114, 33, -18, 67, 36, -42, 23, -9, 121, -85, 40, 10, -50, 32, 38, -22, 61, -26, -70,
-40, 118, -80, -24, -102, 113, 17, -111, 101, -96, 73, -58, -86, -44, -67, -7, 2, -91, 15, -29, -26, -91, -118, -27, -22, -101, 83, 37, 44, 88, -102, 94, -111,
40, 49, 48, -115, 74, 58, -39, -22, 55, -90, -121, 120, 7, -40, -124, -69, 23, -18, 95, 7, -6, -30, -23, -64, -52, 108, -103, 30, 94, -1, -37, 40, -52,
0, 29, 17, 61, -99, -3, -5, -41, 57, -15, 10, -41, -53, -9, 16, -52, 34, 104, 93, -101, 66, -74, -3, 108, 99, -86, -37, -72, 110, 69, -97, 44, 5,
-88, -91, -106, -84, 121, -33, 46, 3, 21, 90, 16, 109, 30, 107, -4, -82, -69, 80, -32, -7, -67, 12, 85, -100, -44, 48, -80, 76, 49, -92, 120, -12, -104,
98, 64, -7, -18, 9, 121, 28, 80, 99, 108, -30, 104, 12, -76, -74, 54, 12, 76, 98, 90, 71, -50, -9, 21, 79, -85, -26, 99, -80, 76, -100, 41, -86,
41, 78, 16, -72, 89, -43, 28, -57, -20, 107, -12, -63, -90, 96, 103, -120, 57, -10, -119, -31, -116, -26, 104, -24, -104, -18, -93, 32, 90, -53, 78, -44, -42,
6, 22, -42, 75, 9, -35, 53, -28, 32, 83, 110, 103, 53, -52, -3, 24, -75, -65, 36, 98, -112, -47, 44, -54, -125, 89, 61, 15, 99, -59, -123, 115, 29,
-70, -119, 119, -53, 63, -42, 66, 76, 8, -48, -94, -20, -94, -33, 17, -15, -61, -55, -54, -69, 21, 56, -65, 50, 73, 4, -85, -16, -45, 13, 18, 0, 93,
-79, 109, -43, 42, -32, 105, -79, -66, -16, 91, -74, 54, -53, -35, 115, -93, -16, 87, 77, 80, 31, -57, 25, -104, -59, -44, 70, 41, 6, 15, -112, -103, -114,
-82, 111, 80, 26, 3, 8, -5, -49, -6, 46, 12, -90, -61, -100, -70, 66, 91, 66, -95, -8, -49, -101, -46, 99, 83, 55, -19, 23, 127, 118, 15, -14, -4,
-43, 17, -103, -94, 117, -40, 31, 97, -59, 21, 21, 61, 35, -27, -8, -27, 15, -12, -59, 102, -104, -25, 78, -87, 117, -4, -76, 127, 80, 72, 77, 32, 31,
-74, -18, 104, 111, 80, 52, 5, -76, -28, -23, -95, -79, 95, -10, -45, 87, -41, -19, -104, -20, 70, -102, -29, 125, -70, -93, 96, -26, 30, -1, 72, 53, 105,
-42, 48, 76, 52, 19, -11, -6, -107, 100, 101, -32, 87, -13, -41, 93, 35, 24, -120, 27, -24, -39, 69, 98, -110, 75, 106, -8, 103, -113, -124, -121, -94, 125,
};
const TfArray<2, int> tensor_dimension4 = { 2, { 20,33 } };
const TfArray<1, float> quant4_scale = { 1, { 0.002759384922683239, } };
const TfArray<1, int> quant4_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant4 = { (TfLiteFloatArray*)&quant4_scale, (TfLiteIntArray*)&quant4_zero, 0 };
const ALIGN(8) int8_t tensor_data5[10*20] = {
-82, -9, 29, 16, 98, -76, -37, 17, -101, -114, -43, -71, 102, 91, -33, -2, -109, 12, -39, 10,
-77, 15, -62, 44, 21, 9, 81, -52, -53, -88, 17, -94, -30, -39, -96, -109, -51, 76, 54, -103,
-86, 89, 35, -53, 77, 5, 56, -45, 100, 97, -81, -47, 28, -106, 39, -33, -23, 122, -98, -34,
-88, -23, -80, -94, -11, 54, 78, 88, 103, -82, 96, 51, 5, -78, -29, 114, 31, 32, 28, -74,
18, 3, -69, -93, -123, 98, -50, -10, -73, 113, 3, -119, -106, 40, -23, 22, 17, -111, 110, 28,
78, 91, -99, 4, -74, -27, -1, -32, 115, -111, -127, 109, -96, 48, -62, 94, -107, -17, -107, 88,
91, -39, 11, 90, 73, -36, 12, 53, 48, 97, -60, 66, -121, -13, -6, -15, 44, -27, 41, -55,
-73, 112, -60, -107, -33, -15, -31, -90, 99, 77, 80, 112, -16, 1, -26, -47, -64, 26, -44, 48,
-74, 72, 3, 49, 118, -8, 63, -119, -23, -85, 45, 84, 101, 111, -20, 57, -98, 101, -6, 9,
-40, 43, 30, 97, -95, 74, 87, -60, 87, -42, -19, 39, -95, -33, -94, 25, 120, 118, -34, 105,
};
const TfArray<2, int> tensor_dimension5 = { 2, { 10,20 } };
const TfArray<1, float> quant5_scale = { 1, { 0.0036247593816369772, } };
const TfArray<1, int> quant5_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant5 = { (TfLiteFloatArray*)&quant5_scale, (TfLiteIntArray*)&quant5_zero, 0 };
const ALIGN(8) int8_t tensor_data6[2*10] = {
-36, -127, -16, -118, 11, -83, 59, 80, 4, 51,
73, -117, -7, 109, 101, 66, 59, -3, 27, -6,
};
const TfArray<2, int> tensor_dimension6 = { 2, { 2,10 } };
const TfArray<1, float> quant6_scale = { 1, { 0.0054330769926309586, } };
const TfArray<1, int> quant6_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant6 = { (TfLiteFloatArray*)&quant6_scale, (TfLiteIntArray*)&quant6_zero, 0 };
const TfArray<2, int> tensor_dimension7 = { 2, { 1,20 } };
const TfArray<1, float> quant7_scale = { 1, { 202.2373046875, } };
const TfArray<1, int> quant7_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant7 = { (TfLiteFloatArray*)&quant7_scale, (TfLiteIntArray*)&quant7_zero, 0 };
const TfArray<2, int> tensor_dimension8 = { 2, { 1,10 } };
const TfArray<1, float> quant8_scale = { 1, { 239.962158203125, } };
const TfArray<1, int> quant8_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant8 = { (TfLiteFloatArray*)&quant8_scale, (TfLiteIntArray*)&quant8_zero, 0 };
const TfArray<2, int> tensor_dimension9 = { 2, { 1,2 } };
const TfArray<1, float> quant9_scale = { 1, { 83.309806823730469, } };
const TfArray<1, int> quant9_zero = { 1, { -115 } };
const TfLiteAffineQuantization quant9 = { (TfLiteFloatArray*)&quant9_scale, (TfLiteIntArray*)&quant9_zero, 0 };
const TfArray<2, int> tensor_dimension10 = { 2, { 1,2 } };
const TfArray<1, float> quant10_scale = { 1, { 0.00390625, } };
const TfArray<1, int> quant10_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant10 = { (TfLiteFloatArray*)&quant10_scale, (TfLiteIntArray*)&quant10_zero, 0 };
const TfLiteFullyConnectedParams opdata0 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs0 = { 3, { 0,4,1 } };
const TfArray<1, int> outputs0 = { 1, { 7 } };
const TfLiteFullyConnectedParams opdata1 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs1 = { 3, { 7,5,2 } };
const TfArray<1, int> outputs1 = { 1, { 8 } };
const TfLiteFullyConnectedParams opdata2 = { kTfLiteActNone, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs2 = { 3, { 8,6,3 } };
const TfArray<1, int> outputs2 = { 1, { 9 } };
const TfLiteSoftmaxParams opdata3 = { 1 };
const TfArray<1, int> inputs3 = { 1, { 9 } };
const TfArray<1, int> outputs3 = { 1, { 10 } };
const TensorInfo_t tensorData[] = {
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension0, 33, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant0))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data1, (TfLiteIntArray*)&tensor_dimension1, 80, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant1))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data2, (TfLiteIntArray*)&tensor_dimension2, 40, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant2))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data3, (TfLiteIntArray*)&tensor_dimension3, 8, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant3))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data4, (TfLiteIntArray*)&tensor_dimension4, 660, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant4))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data5, (TfLiteIntArray*)&tensor_dimension5, 200, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant5))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data6, (TfLiteIntArray*)&tensor_dimension6, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant6))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 48, (TfLiteIntArray*)&tensor_dimension7, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant7))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension8, 10, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant8))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 16, (TfLiteIntArray*)&tensor_dimension9, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant9))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension10, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant10))}, },
};const NodeInfo_t nodeData[] = {
{ (TfLiteIntArray*)&inputs0, (TfLiteIntArray*)&outputs0, const_cast<void*>(static_cast<const void*>(&opdata0)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs1, (TfLiteIntArray*)&outputs1, const_cast<void*>(static_cast<const void*>(&opdata1)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs2, (TfLiteIntArray*)&outputs2, const_cast<void*>(static_cast<const void*>(&opdata2)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs3, (TfLiteIntArray*)&outputs3, const_cast<void*>(static_cast<const void*>(&opdata3)), OP_SOFTMAX, },
};
static std::vector<void*> overflow_buffers;
static TfLiteStatus AllocatePersistentBuffer(struct TfLiteContext* ctx,
size_t bytes, void** ptr) {
if (current_location - bytes < tensor_boundary) {
// OK, this will look super weird, but.... we have CMSIS-NN buffers which
// we cannot calculate beforehand easily.
*ptr = malloc(bytes);
if (*ptr == NULL) {
printf("ERR: Failed to allocate persistent buffer of size %u\n", bytes);
return kTfLiteError;
}
overflow_buffers.push_back(*ptr);
return kTfLiteOk;
}
current_location -= bytes;
*ptr = current_location;
return kTfLiteOk;
}
typedef struct {
size_t bytes;
void *ptr;
} scratch_buffer_t;
static std::vector<scratch_buffer_t> scratch_buffers;
static TfLiteStatus RequestScratchBufferInArena(struct TfLiteContext* ctx, size_t bytes,
int* buffer_idx) {
scratch_buffer_t b;
b.bytes = bytes;
TfLiteStatus s = AllocatePersistentBuffer(ctx, b.bytes, &b.ptr);
if (s != kTfLiteOk) {
return s;
}
scratch_buffers.push_back(b);
*buffer_idx = scratch_buffers.size() - 1;
return kTfLiteOk;
}
static void* GetScratchBuffer(struct TfLiteContext* ctx, int buffer_idx) {
if (buffer_idx > static_cast<int>(scratch_buffers.size()) - 1) {
return NULL;
}
return scratch_buffers[buffer_idx].ptr;
}
} // namespace
TfLiteStatus trained_model_init( void*(*alloc_fnc)(size_t,size_t) ) {
tensor_arena = (uint8_t*) alloc_fnc(16, kTensorArenaSize);
current_location = tensor_arena + kTensorArenaSize;
tensor_boundary = tensor_arena;
ctx.AllocatePersistentBuffer = &AllocatePersistentBuffer;
ctx.RequestScratchBufferInArena = &RequestScratchBufferInArena;
ctx.GetScratchBuffer = &GetScratchBuffer;
ctx.tensors = tflTensors;
ctx.tensors_size = 11;
for(size_t i = 0; i < 11; ++i) {
tflTensors[i].type = tensorData[i].type;
tflTensors[i].is_variable = 0;
tflTensors[i].allocation_type = tensorData[i].allocation_type;
tflTensors[i].bytes = tensorData[i].bytes;
tflTensors[i].dims = tensorData[i].dims;
if(tflTensors[i].allocation_type == kTfLiteArenaRw){
uint8_t* start = (uint8_t*) ((uintptr_t)tensorData[i].data + (uintptr_t) tensor_arena);
uint8_t* end = start + tensorData[i].bytes;
tflTensors[i].data.data = start;
if (end > tensor_boundary) {
tensor_boundary = end;
}
}
else{
tflTensors[i].data.data = tensorData[i].data;
}
tflTensors[i].quantization = tensorData[i].quantization;
if (tflTensors[i].quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization const* quant = ((TfLiteAffineQuantization const*)(tensorData[i].quantization.params));
tflTensors[i].params.scale = quant->scale->data[0];
tflTensors[i].params.zero_point = quant->zero_point->data[0];
}
}
registrations[OP_FULLY_CONNECTED] = *tflite::ops::micro::Register_FULLY_CONNECTED();
registrations[OP_SOFTMAX] = *tflite::ops::micro::Register_SOFTMAX();
for(size_t i = 0; i < 4; ++i) {
tflNodes[i].inputs = nodeData[i].inputs;
tflNodes[i].outputs = nodeData[i].outputs;
tflNodes[i].builtin_data = nodeData[i].builtin_data;
tflNodes[i].custom_initial_data = nullptr;
tflNodes[i].custom_initial_data_size = 0;
if (registrations[nodeData[i].used_op_index].init) {
tflNodes[i].user_data = registrations[nodeData[i].used_op_index].init(&ctx, (const char*)tflNodes[i].builtin_data, 0);
}
}
for(size_t i = 0; i < 4; ++i) {
if (registrations[nodeData[i].used_op_index].prepare) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].prepare(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
}
return kTfLiteOk;
}
static const int inTensorIndices[] = {
0,
};
TfLiteTensor* trained_model_input(int index) {
return &ctx.tensors[inTensorIndices[index]];
}
static const int outTensorIndices[] = {
10,
};
TfLiteTensor* trained_model_output(int index) {
return &ctx.tensors[outTensorIndices[index]];
}
TfLiteStatus trained_model_invoke() {
for(size_t i = 0; i < 4; ++i) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].invoke(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
return kTfLiteOk;
}
TfLiteStatus trained_model_reset( void (*free_fnc)(void* ptr) ) {
free_fnc(tensor_arena);
scratch_buffers.clear();
for (size_t ix = 0; ix < overflow_buffers.size(); ix++) {
free(overflow_buffers[ix]);
}
overflow_buffers.clear();
return kTfLiteOk;
}
| 55.52439
| 180
| 0.652152
|
LetsOKdo
|
2a5ad1457cc8348ebe8d3ce6d5a3492f80578b89
| 2,210
|
cc
|
C++
|
nucleus/io/vcf_roundtrip_test.cc
|
gaybro8777/nucleus
|
3bd27ac076a6f3f93e49a27ed60661858e727dda
|
[
"BSD-3-Clause"
] | 721
|
2018-03-30T14:34:17.000Z
|
2022-03-23T00:09:18.000Z
|
nucleus/io/vcf_roundtrip_test.cc
|
aktaseren/nucleus
|
3cc9412be81ed86a99fd7eb086ee94afe852759b
|
[
"Apache-2.0"
] | 38
|
2018-03-31T09:02:23.000Z
|
2022-03-23T21:16:41.000Z
|
nucleus/io/vcf_roundtrip_test.cc
|
aktaseren/nucleus
|
3cc9412be81ed86a99fd7eb086ee94afe852759b
|
[
"Apache-2.0"
] | 123
|
2018-03-30T21:51:18.000Z
|
2021-12-13T06:59:31.000Z
|
/*
* Copyright 2019 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 <memory>
#include <vector>
#include <gmock/gmock-generated-matchers.h>
#include <gmock/gmock-matchers.h>
#include <gmock/gmock-more-matchers.h>
#include "tensorflow/core/platform/test.h"
#include "nucleus/io/vcf_reader.h"
#include "nucleus/io/vcf_writer.h"
#include "nucleus/platform/types.h"
#include "nucleus/protos/variants.pb.h"
#include "nucleus/testing/protocol-buffer-matchers.h"
#include "nucleus/testing/test_utils.h"
#include "nucleus/vendor/status_matchers.h"
namespace nucleus {
namespace {
using genomics::v1::Variant;
} // namespace
// Read from a vcf file and write to a bcf file. The bcf file should have the
// same contents as the vcf file.
TEST(VcfRoundtripTest, ReadVCFWriteBCF) {
string input_file = GetTestData("test_sites.vcf");
string output_file = MakeTempFile("output.bcf.gz");
auto reader = std::move(
VcfReader::FromFile(input_file, genomics::v1::VcfReaderOptions())
.ValueOrDie());
auto writer = std::move(VcfWriter::ToFile(output_file, reader->Header(),
genomics::v1::VcfWriterOptions())
.ValueOrDie());
std::vector<Variant> expected_variants = as_vector(reader->Iterate());
for (const auto& v : expected_variants) {
ASSERT_THAT(writer->Write(v), IsOK());
}
writer = nullptr;
auto output_reader = std::move(
VcfReader::FromFile(output_file, genomics::v1::VcfReaderOptions())
.ValueOrDie());
EXPECT_THAT(as_vector(output_reader->Iterate()),
testing::Pointwise(EqualsProto(), expected_variants));
}
} // namespace nucleus
| 34.53125
| 77
| 0.701357
|
gaybro8777
|
2a5b1d43a6c5dbb0d6a6fa542e67d6192c1ef1f8
| 2,458
|
cpp
|
C++
|
clients/cpp-pistache-server/generated/model/StringParameterValue.cpp
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 23
|
2017-08-01T12:25:26.000Z
|
2022-01-25T03:44:11.000Z
|
clients/cpp-pistache-server/generated/model/StringParameterValue.cpp
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 35
|
2017-06-14T03:28:15.000Z
|
2022-02-14T10:25:54.000Z
|
clients/cpp-pistache-server/generated/model/StringParameterValue.cpp
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 11
|
2017-08-31T19:00:20.000Z
|
2021-12-19T12:04:12.000Z
|
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "StringParameterValue.h"
namespace org {
namespace openapitools {
namespace server {
namespace model {
StringParameterValue::StringParameterValue()
{
m__class = "";
m__classIsSet = false;
m_Name = "";
m_NameIsSet = false;
m_Value = "";
m_ValueIsSet = false;
}
StringParameterValue::~StringParameterValue()
{
}
void StringParameterValue::validate()
{
// TODO: implement validation
}
nlohmann::json StringParameterValue::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m__classIsSet)
{
val["_class"] = ModelBase::toJson(m__class);
}
if(m_NameIsSet)
{
val["name"] = ModelBase::toJson(m_Name);
}
if(m_ValueIsSet)
{
val["value"] = ModelBase::toJson(m_Value);
}
return val;
}
void StringParameterValue::fromJson(nlohmann::json& val)
{
if(val.find("_class") != val.end())
{
setClass(val.at("_class"));
}
if(val.find("name") != val.end())
{
setName(val.at("name"));
}
if(val.find("value") != val.end())
{
setValue(val.at("value"));
}
}
std::string StringParameterValue::getClass() const
{
return m__class;
}
void StringParameterValue::setClass(std::string const& value)
{
m__class = value;
m__classIsSet = true;
}
bool StringParameterValue::classIsSet() const
{
return m__classIsSet;
}
void StringParameterValue::unset_class()
{
m__classIsSet = false;
}
std::string StringParameterValue::getName() const
{
return m_Name;
}
void StringParameterValue::setName(std::string const& value)
{
m_Name = value;
m_NameIsSet = true;
}
bool StringParameterValue::nameIsSet() const
{
return m_NameIsSet;
}
void StringParameterValue::unsetName()
{
m_NameIsSet = false;
}
std::string StringParameterValue::getValue() const
{
return m_Value;
}
void StringParameterValue::setValue(std::string const& value)
{
m_Value = value;
m_ValueIsSet = true;
}
bool StringParameterValue::valueIsSet() const
{
return m_ValueIsSet;
}
void StringParameterValue::unsetValue()
{
m_ValueIsSet = false;
}
}
}
}
}
| 17.941606
| 91
| 0.663548
|
PankTrue
|
2a5fa2c4b14955a5b98a9a263ce85d4c4965dfb4
| 412
|
cpp
|
C++
|
PTA/GPLT/L1-C/010.cpp
|
cnsteven/online-judge
|
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
|
[
"MIT"
] | 1
|
2019-05-04T10:28:32.000Z
|
2019-05-04T10:28:32.000Z
|
PTA/GPLT/L1-C/010.cpp
|
cnsteven/online-judge
|
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
|
[
"MIT"
] | null | null | null |
PTA/GPLT/L1-C/010.cpp
|
cnsteven/online-judge
|
60ee841a97e2bc0dc9c7b23fe5daa186898ab8b7
|
[
"MIT"
] | 3
|
2020-12-31T04:36:38.000Z
|
2021-07-25T07:39:31.000Z
|
#include <iostream>
using namespace std;
int main() {
int a[3], i, j, t;
for (i = 0; i < 3; i++) {
cin >> a[i];
}
for (i = 0; i < 3; i++) {
for (j = i + 1; j < 3; j++) {
if (a[i] > a[j]) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
cout << a[0] << "->" << a[1] << "->" << a[2];
return 0;
}
| 18.727273
| 49
| 0.26699
|
cnsteven
|
2a664c5cf5e630d6683e8571819067dd25e5e2cf
| 1,044
|
cpp
|
C++
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 9
|
2019-07-03T13:11:33.000Z
|
2021-10-06T13:55:31.000Z
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 1
|
2019-07-09T09:04:59.000Z
|
2019-08-06T13:23:47.000Z
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 4
|
2019-07-02T15:03:43.000Z
|
2019-09-28T14:33:03.000Z
|
#include "chrono.h"
using namespace std::chrono;
Chrono::Chrono()
: _paused(false)
{
}
Chrono::~Chrono()
{
}
void Chrono::start()
{
// reset chrono if already running
_startTime = ClockT::now();
_current_duration = DurationT::zero();
}
void Chrono::pause()
{
if(!_paused)
{
_current_duration = ClockT::now() - _startTime;
_paused = true;
}
}
void Chrono::resume()
{
if(_paused == true)
{
_startTime = ClockT::now();
_paused = false;
}
}
float Chrono::ellapsed(DurationType dt)
{
if(!_paused)
{
_current_duration += ClockT::now() - _startTime;
_startTime = ClockT::now();
}
float ellapsed = 0;
switch(dt)
{
case MINUTES :
ellapsed = duration_cast<minutes>(_current_duration).count();
break;
case SECONDS :
ellapsed = duration_cast<seconds>(_current_duration).count();
break;
case MILLISECONDS :
ellapsed = duration_cast<milliseconds>(_current_duration).count();
break;
case NANOSECONDS :
ellapsed = duration_cast<nanoseconds>(_current_duration).count();
}
return ellapsed;
}
| 15.58209
| 69
| 0.675287
|
Ymagis
|
2a67473bd414db7b92dafbc301b5b719af1fa3eb
| 1,372
|
cpp
|
C++
|
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | 1
|
2019-08-16T07:10:24.000Z
|
2019-08-16T07:10:24.000Z
|
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | null | null | null |
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | null | null | null |
#include <ros/ros.h>
#include <tf2/LinearMath/Vector3.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <tf2_ros/transform_listener.h>
#include <geometry_msgs/TransformStamped.h>
#include <tf2_ros/transform_broadcaster.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "tps_base_link");
ros::NodeHandle n;
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener tfListener(tfBuffer);
tf2_ros::TransformBroadcaster tb;
geometry_msgs::TransformStamped ts;
ros::Rate r(25.0);
while(ros::ok()){
geometry_msgs::TransformStamped transform;
try{
transform = tfBuffer.lookupTransform("map", "base_link", ros::Time(0));
}
catch (tf2::TransformException &ex){
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
continue;
}
ts.header.stamp = transform.header.stamp;
ts.header.frame_id = "map";
ts.child_frame_id = "tps_base_link";
ts.transform.translation.x = transform.transform.translation.x;
ts.transform.translation.y = transform.transform.translation.y;
ts.transform.translation.z = 0;
tf2::Quaternion rotation;
rotation.setRPY(0, 0, 0);
ts.transform.rotation.x = rotation.x();
ts.transform.rotation.y = rotation.y();
ts.transform.rotation.z = rotation.z();
ts.transform.rotation.w = rotation.w();
tb.sendTransform(ts);
r.sleep();
}
return 0;
}
| 24.945455
| 74
| 0.710641
|
WRS-TNK
|
2a6a133a0da6177d07c15430399e586a273213c1
| 5,355
|
cpp
|
C++
|
src/Q3D/Core/QMaterial.cpp
|
565353780/opengl-automaskobj
|
bae7c35a0aece5a09ec67b02241aff58932c6daf
|
[
"MIT"
] | null | null | null |
src/Q3D/Core/QMaterial.cpp
|
565353780/opengl-automaskobj
|
bae7c35a0aece5a09ec67b02241aff58932c6daf
|
[
"MIT"
] | null | null | null |
src/Q3D/Core/QMaterial.cpp
|
565353780/opengl-automaskobj
|
bae7c35a0aece5a09ec67b02241aff58932c6daf
|
[
"MIT"
] | null | null | null |
#include "QMaterial.h"
#include <qgl.h>
#include <cmath>
namespace GCL
{
QMaterial::QMaterial(QObject *parent) : QOpenGLShaderProgram(parent)
{
this->initializeOpenGLFunctions();
}
QMaterial::~QMaterial()
{
this->clearTextures();
}
void QMaterial::clearTextures()
{
foreach (auto texture, local_textures_)
{
if(texture->isCreated())
{
texture->destroy();
}
}
local_textures_.clear();
for(auto tid : local_texture_ids_)
{
if(glIsTexture(tid))
{
glDeleteTextures(1, &tid);
}
}
local_texture_ids_.clear();
}
void QMaterial::linkShaders(const QString &vert_filename, const QString &frag_filename)
{
this->addShaderFromSourceFile(QOpenGLShader::Vertex, vert_filename);
this->addShaderFromSourceFile(QOpenGLShader::Fragment, frag_filename);
this->link();
}
void QMaterial::addUniformValue(const char *name, GLfloat f)
{
UniformType ut;
ut.f_val_ = f;
ut.type_ = UniformType::Float;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, GLint val)
{
UniformType ut;
ut.i_val_ = val;
ut.type_ = UniformType::Int;
uniform_map_[name] = ut;
}
void QMaterial::addUniformTexture(const char *name, GLuint tex_id, bool add_to_local)
{
UniformType ut;
ut.tex_id_ = tex_id;
ut.type_ = UniformType::Texture;
uniform_map_[name] = ut;
if(add_to_local)
{
local_texture_ids_.push_back(tex_id);
}
}
GLuint QMaterial::addUniformTextureImage(const char *name, const QImage &image, QOpenGLTexture::Filter minfilter, QOpenGLTexture::Filter magfilter, QOpenGLTexture::WrapMode warpmode)
{
std::shared_ptr< QOpenGLTexture > texture(new QOpenGLTexture(image));
texture->create();
texture->bind();
texture->setMinificationFilter(minfilter);
texture->setMagnificationFilter(magfilter);
texture->setWrapMode(warpmode);
addUniformTexture(name, texture->textureId());
local_textures_.push_back(texture);
return texture->textureId();
}
QVector4D QMaterial::packInt(uint val)
{
QVector4D v;
v.setX(val % 256);
val /= 256;
v.setY(val % 256);
val /= 256;
v.setZ(val % 256);
val /= 256;
v.setW(255 - val % 256);
return v / 255.0;
}
uint QMaterial::unpackInt(QVector4D v)
{
uint sum = 0;
v *= 255.0;
sum += int(v.x());
sum += int(v.y()) * 256;
sum += int(v.z()) * 256 * 256;
sum += (255 - int(v.w())) * 256 * 256 * 256;
return sum;
}
QVector4D QMaterial::pack(double val)
{
if(val >= 1.0) val = 0.999999;
if(val < 0) val = 0;
QVector4D bit_shift(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
QVector4D bit_mask(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
QVector4D res = (val * bit_shift);
for(int i = 0; i < 4; i++)
{
res[i] = res[i] - floor(res[i]);
}
res -= QVector4D(res.x(), res.x(), res.y(), res.z()) * bit_mask;
return QVector4D(res.w(), res.z(), res.y(), res.x());
}
double QMaterial::unpack(QVector4D v)
{
QVector4D bit_shift(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
double depth = QVector4D::dotProduct(QVector4D(v.w(), v.z(), v.y(), v.x()), bit_shift);
return depth;
}
void QMaterial::setUniforms(int &active_texture_count)
{
for(auto iter = uniform_map_.cbegin(); iter != uniform_map_.cend(); iter++)
{
const UniformType& ut = iter.value();
if(ut.type_ == UniformType::Float)
{
this->setUniformValue(iter.key().toLocal8Bit().data(), ut.f_val_);
}
else if(ut.type_ == UniformType::Int)
{
this->setUniformValue(iter.key().toLocal8Bit().data(), ut.i_val_);
}
else if(ut.type_ == UniformType::Texture)
{
glActiveTexture(GL_TEXTURE0 + active_texture_count);
glBindTexture(GL_TEXTURE_2D, ut.tex_id_);
this->setUniformValue(iter.key().toLocal8Bit().data(), active_texture_count);
active_texture_count++;
}
else if(ut.type_ == UniformType::Vec2)
{
QVector2D v;
v[0] = ut.v_val_[0];
v[1] = ut.v_val_[1];
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
else if(ut.type_ == UniformType::Vec3)
{
QVector3D v;
v[0] = ut.v_val_[0];
v[1] = ut.v_val_[1];
v[2] = ut.v_val_[2];
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
else if(ut.type_ == UniformType::Vec4)
{
QVector4D v;
v = ut.v_val_;
this->setUniformValue(iter.key().toLocal8Bit().data(), v);
}
}
}
void QMaterial::addUniformValue(const char *name, QVector2D v)
{
UniformType ut;
ut.v_val_[0] = v[0];
ut.v_val_[1] = v[1];
ut.type_ = UniformType::Vec2;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, QVector3D v)
{
UniformType ut;
ut.v_val_[0] = v[0];
ut.v_val_[1] = v[1];
ut.v_val_[2] = v[2];
ut.type_ = UniformType::Vec3;
uniform_map_[name] = ut;
}
void QMaterial::addUniformValue(const char *name, QVector4D v)
{
UniformType ut;
ut.v_val_ = v;
ut.type_ = UniformType::Vec4;
uniform_map_[name] = ut;
}
}
| 25.140845
| 182
| 0.596078
|
565353780
|
2a716f151aa21b1f2c44232d9976c37867ed224e
| 981
|
cpp
|
C++
|
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | 1
|
2018-12-14T07:51:26.000Z
|
2018-12-14T07:51:26.000Z
|
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | null | null | null |
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | 1
|
2019-06-23T10:34:19.000Z
|
2019-06-23T10:34:19.000Z
|
/*
PROG: COW
LANG: C++
ID: nibnalin
*/
//USACO February Contest
#include <fstream>
#include <vector>
#include <climits>
using namespace std;
vector<vector<int> > grid;
vector< vector<long> > memtable;
int ans(long x, long y) {
if(memtable[x][y] == INT_MIN)
{
long paths = 0;
for(long i = (x-1);i >= 0;i--)
{
for(long j = (y-1);j >= 0;j--)
{
if(grid[x][y] != grid[i][j])
{
paths += ans(i, j);
}
}
}
memtable[x][y] = paths;
return paths;
}
else
return memtable[x][y];
}
int main(void)
{
ifstream fin ("hopscotch.in");
ofstream fout ("hopscotch.out");
long r, c;
fin >> r >> c;
grid.clear();
grid.resize(r, vector<int>(c));
memtable.clear();
memtable.resize(r, vector<long>(c, INT_MIN));
for(int i = 0;i < r;i++)
{
string tmp;
fin >> tmp;
for(int j = 0;j < c;j++)
{
if(tmp[j] == 'R')
grid[i][j] = 1;
else
grid[i][j] = 0;
}
}
memtable[0][0] = 1;
fout << ans(r-1, c-1) << endl; //Recurse, memoize
}
| 16.081967
| 50
| 0.540265
|
nalinbhardwaj
|
2a7337f9cdbf75041e5ccc49cc0a2c08423d85b3
| 21,980
|
cpp
|
C++
|
src/prod/src/systemservices/ServiceRoutingAgent.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 2,542
|
2018-03-14T21:56:12.000Z
|
2019-05-06T01:18:20.000Z
|
src/prod/src/systemservices/ServiceRoutingAgent.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 994
|
2019-05-07T02:39:30.000Z
|
2022-03-31T13:23:04.000Z
|
src/prod/src/systemservices/ServiceRoutingAgent.cpp
|
gridgentoo/ServiceFabricAzure
|
c3e7a07617e852322d73e6cc9819d266146866a4
|
[
"MIT"
] | 300
|
2018-03-14T21:57:17.000Z
|
2019-05-06T20:07:00.000Z
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Federation;
using namespace Hosting2;
using namespace Naming;
using namespace Transport;
using namespace ServiceModel;
using namespace SystemServices;
// *** Private ServiceRoutingAgent::Impl
StringLiteral const TraceComponent("ServiceRoutingAgent");
class ServiceRoutingAgent::Impl
: public RootedObject
, private NodeTraceComponent<Common::TraceTaskCodes::SystemServices>
{
public:
Impl(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
: RootedObject(root)
, NodeTraceComponent(federation.Instance)
, ipcServer_(ipcServer)
, federation_(federation)
, hosting_(hosting)
, naming_(naming)
{
REGISTER_MESSAGE_HEADER(SystemServiceFilterHeader);
WriteInfo(TraceComponent, "{0} ctor", this->TraceId);
}
virtual ~Impl()
{
WriteInfo(TraceComponent, "{0} ~dtor", this->TraceId);
}
ErrorCode Open();
ErrorCode Close();
void Abort();
private:
class RequestAsyncOperationBase
: public TimedAsyncOperation
, public NodeActivityTraceComponent<TraceTaskCodes::SystemServices>
{
public:
RequestAsyncOperationBase(
Impl & owner,
MessageUPtr && message,
ErrorCodeValue::Enum error,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: TimedAsyncOperation(timeout, callback, root)
, NodeActivityTraceComponent(owner.NodeInstance, FabricActivityHeader::FromMessage(*message).ActivityId)
, owner_(owner)
, request_(move(message))
, error_(error)
, reply_()
{
}
virtual ~RequestAsyncOperationBase() { }
MessageUPtr && TakeReply() { return move(reply_); }
protected:
virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { this->TryComplete(thisSPtr, error_); }
void SetReply(MessageUPtr && reply) { reply_.swap(reply); }
Impl & owner_;
MessageUPtr request_;
ErrorCodeValue::Enum error_;
private:
MessageUPtr reply_;
};
class ServiceToNodeAsyncOperation : public RequestAsyncOperationBase
{
public:
ServiceToNodeAsyncOperation(
Impl & owner,
MessageUPtr && message,
IpcReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
move(message),
ErrorCodeValue::Success,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
ServiceToNodeAsyncOperation(
Impl & owner,
ErrorCodeValue::Enum error,
IpcReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
MessageUPtr(),
error,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
virtual ~ServiceToNodeAsyncOperation() { }
__declspec (property(get=get_IpcReceiverContext)) IpcReceiverContext const & ReceiverContext;
IpcReceiverContext const & get_IpcReceiverContext() const { return *receiverContext_; }
protected:
virtual void OnStart(AsyncOperationSPtr const &);
private:
void OnNodeProcessingComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
IpcReceiverContextUPtr receiverContext_;
};
class NodeToServiceAsyncOperation : public RequestAsyncOperationBase
{
public:
NodeToServiceAsyncOperation(
Impl & owner,
MessageUPtr && message,
RequestReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
move(message),
ErrorCodeValue::Success,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
NodeToServiceAsyncOperation(
Impl & owner,
ErrorCodeValue::Enum error,
RequestReceiverContextUPtr && receiverContext,
TimeSpan const timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & root)
: RequestAsyncOperationBase(
owner,
MessageUPtr(),
error,
timeout,
callback,
root)
, receiverContext_(move(receiverContext))
{
}
virtual ~NodeToServiceAsyncOperation() { }
__declspec (property(get=get_RequestReceiverContext)) RequestReceiverContext & ReceiverContext;
RequestReceiverContext & get_RequestReceiverContext() { return *receiverContext_; }
protected:
virtual void OnStart(AsyncOperationSPtr const &);
private:
ErrorCode GetHostId(ServiceTypeIdentifier const &, __out wstring & clientId);
void OnForwardToServiceComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
RequestReceiverContextUPtr receiverContext_;
};
void Cleanup();
bool IsValidRequest(MessageUPtr const &);
void ProcessIpcRequest(MessageUPtr &&, IpcReceiverContextUPtr &&);
void OnIpcRequestComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
void SendIpcReply(MessageUPtr &&, IpcReceiverContext const &);
void OnIpcFailure(ErrorCode const &, IpcReceiverContext const &, ActivityId const & activityId);
void ProcessFederationRequest(MessageUPtr &&, RequestReceiverContextUPtr &&);
void OnFederationRequestComplete(AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
void SendFederationReply(MessageUPtr &&, RequestReceiverContext &);
void OnFederationFailure(ErrorCode const &, RequestReceiverContext &);
AsyncOperationSPtr BeginRouteGatewayMessage(
MessageUPtr & message,
TimeSpan,
AsyncCallback const &,
AsyncOperationSPtr const & );
ErrorCode EndRouteGatewayMessage(
AsyncOperationSPtr const &,
_Out_ Transport::MessageUPtr & );
IpcServer & ipcServer_;
FederationSubsystem & federation_;
IHostingSubsystem & hosting_;
IGateway & naming_;
}; // end class Impl
ServiceRoutingAgent::~ServiceRoutingAgent()
{
}
ErrorCode ServiceRoutingAgent::Impl::Open()
{
WriteInfo(
TraceComponent,
"{0} registering federation",
this->TraceId);
ComponentRootSPtr root = this->Root.CreateComponentRoot();
ipcServer_.RegisterMessageHandler(
Actor::ServiceRoutingAgent,
[this, root] (MessageUPtr & message, IpcReceiverContextUPtr & receiverContext)
{
this->ProcessIpcRequest(move(message), move(receiverContext));
},
false);
federation_.RegisterMessageHandler(
Actor::ServiceRoutingAgent,
[] (MessageUPtr &, OneWayReceiverContextUPtr &)
{
Assert::CodingError("ServiceRoutingAgent does not support oneway messages");
},
[this, root] (MessageUPtr & message, RequestReceiverContextUPtr & receiverContext)
{
this->ProcessFederationRequest(move(message), move(receiverContext));
},
false);
naming_.RegisterGatewayMessageHandler(
Actor::ServiceRoutingAgent,
[this, root] (MessageUPtr &message, TimeSpan timeout, AsyncCallback const& callback, AsyncOperationSPtr const& parent)
{
return BeginRouteGatewayMessage(message, timeout, callback, parent);
},
[this, root](AsyncOperationSPtr const& operation, _Out_ MessageUPtr & reply)
{
return EndRouteGatewayMessage(operation, reply);
});
return ErrorCodeValue::Success;
}
ErrorCode ServiceRoutingAgent::Impl::Close()
{
this->Cleanup();
return ErrorCodeValue::Success;
}
void ServiceRoutingAgent::Impl::Abort()
{
this->Cleanup();
}
void ServiceRoutingAgent::Impl::Cleanup()
{
federation_.UnRegisterMessageHandler(Actor::ServiceRoutingAgent);
ipcServer_.UnregisterMessageHandler(Actor::ServiceRoutingAgent);
naming_.UnRegisterGatewayMessageHandler(Actor::ServiceRoutingAgent);
}
bool ServiceRoutingAgent::Impl::IsValidRequest(MessageUPtr const & message)
{
if (!message)
{
WriteInfo(TraceComponent, "{0} null request", this->TraceId);
return false;
}
if (message->Actor != Actor::ServiceRoutingAgent)
{
WriteInfo(TraceComponent, "{0} invalid actor: {1}", this->TraceId, message->Actor);
return false;
}
TimeoutHeader timeoutHeader;
if (!message->Headers.TryReadFirst(timeoutHeader))
{
WriteInfo(TraceComponent, "{0} missing timeout header: {1}", this->TraceId, message->Action);
return false;
}
return true;
}
//
// *** IPC
//
void ServiceRoutingAgent::Impl::ProcessIpcRequest(MessageUPtr && message, IpcReceiverContextUPtr && receiverContext)
{
if (!IsValidRequest(message))
{
this->OnIpcFailure(ErrorCodeValue::InvalidMessage, *receiverContext, ActivityId(Guid::Empty()));
return;
}
auto timeoutHeader = TimeoutHeader::FromMessage(*message);
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
auto operation = AsyncOperation::CreateAndStart<ServiceToNodeAsyncOperation>(
*this,
move(message),
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnIpcRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnIpcRequestComplete(operation, true);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action: {1}", this->TraceId, message->Action);
auto operation = AsyncOperation::CreateAndStart<ServiceToNodeAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnIpcRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnIpcRequestComplete(operation, true);
}
}
void ServiceRoutingAgent::Impl::OnIpcRequestComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
auto casted = AsyncOperation::End<ServiceToNodeAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
MessageUPtr reply = casted->TakeReply();
// There used to be an IpcServer/IpcClient bug that miscalculates the message header signature
// when there are deleted headers. Preserve the Compact() here anyway as good practice.
//
reply->Headers.Compact();
this->SendIpcReply(move(reply), casted->ReceiverContext);
}
else
{
this->OnIpcFailure(casted->Error, casted->ReceiverContext, casted->ActivityId);
}
}
void ServiceRoutingAgent::Impl::SendIpcReply(MessageUPtr && reply, IpcReceiverContext const & receiverContext)
{
receiverContext.Reply(move(reply));
}
void ServiceRoutingAgent::Impl::OnIpcFailure(ErrorCode const & error, IpcReceiverContext const & receiverContext, ActivityId const & activityId)
{
auto reply = ServiceRoutingAgentMessage::CreateIpcFailureMessage(IpcFailureBody(error.ReadValue()), activityId);
this->SendIpcReply(move(reply), receiverContext);
}
//
// *** Federation
//
void ServiceRoutingAgent::Impl::ProcessFederationRequest(MessageUPtr && message, RequestReceiverContextUPtr && receiverContext)
{
if (!IsValidRequest(message))
{
this->OnFederationFailure(ErrorCodeValue::InvalidMessage, *receiverContext);
return;
}
auto timeoutHeader = TimeoutHeader::FromMessage(*message);
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
auto operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
move(message),
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnFederationRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnFederationRequestComplete(operation, true);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action: {1}", this->TraceId, message->Action);
auto operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
move(receiverContext),
timeoutHeader.Timeout,
[this](AsyncOperationSPtr const & operation) { this->OnFederationRequestComplete(operation, false); },
this->Root.CreateAsyncOperationRoot());
this->OnFederationRequestComplete(operation, true);
}
}
void ServiceRoutingAgent::Impl::OnFederationRequestComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
auto casted = AsyncOperation::End<NodeToServiceAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
this->SendFederationReply(casted->TakeReply(), casted->ReceiverContext);
}
else
{
this->OnFederationFailure(casted->Error, casted->ReceiverContext);
}
}
void ServiceRoutingAgent::Impl::SendFederationReply(MessageUPtr && reply, RequestReceiverContext & receiverContext)
{
receiverContext.Reply(move(reply));
}
void ServiceRoutingAgent::Impl::OnFederationFailure(ErrorCode const & error, RequestReceiverContext & receiverContext)
{
receiverContext.Reject(error);
}
// ** Gateway
AsyncOperationSPtr ServiceRoutingAgent::Impl::BeginRouteGatewayMessage(
MessageUPtr & message,
TimeSpan timeout,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
{
AsyncOperationSPtr operation;
if (message->Action == ServiceRoutingAgentMessage::ServiceRouteRequestAction)
{
operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
move(message),
nullptr, // RequestReceiverContextUPtr
timeout,
callback,
parent);
}
else
{
WriteInfo(TraceComponent, "{0} invalid action in Gateway routing message: {1}", this->TraceId, message->Action);
operation = AsyncOperation::CreateAndStart<NodeToServiceAsyncOperation>(
*this,
ErrorCodeValue::InvalidMessage,
nullptr, // RequestReceiverContextUPtr
timeout,
callback,
parent);
}
return operation;
}
ErrorCode ServiceRoutingAgent::Impl::EndRouteGatewayMessage(
AsyncOperationSPtr const& operation,
MessageUPtr &reply)
{
auto casted = AsyncOperation::End<NodeToServiceAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
reply = casted->TakeReply();
}
return casted->Error;
}
// *** ServiceToNodeAsyncOperation
void ServiceRoutingAgent::Impl::ServiceToNodeAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr)
{
if (error_ != ErrorCodeValue::Success)
{
RequestAsyncOperationBase::OnStart(thisSPtr);
return;
}
ErrorCode error = ServiceRoutingAgentMessage::UnwrapFromIpc(*request_);
if (error.IsSuccess())
{
WriteNoise(
TraceComponent,
"{0} forwarding request {1}:{2} to Naming",
this->TraceId,
request_->Actor,
request_->Action);
auto operation = owner_.naming_.BeginProcessRequest(
request_->Clone(),
this->RemainingTime,
[this](AsyncOperationSPtr const & operation) { this->OnNodeProcessingComplete(operation, false); },
thisSPtr);
this->OnNodeProcessingComplete(operation, true);
}
else
{
this->TryComplete(thisSPtr, error);
}
}
void ServiceRoutingAgent::Impl::ServiceToNodeAsyncOperation::OnNodeProcessingComplete(
AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
MessageUPtr reply;
ErrorCode error = owner_.naming_.EndProcessRequest(operation, reply);
if (error.IsSuccess())
{
this->SetReply(move(reply));
}
this->TryComplete(operation->Parent, error);
}
// *** NodeToServiceAsyncOperation
void ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr)
{
if (error_ != ErrorCodeValue::Success)
{
RequestAsyncOperationBase::OnStart(thisSPtr);
return;
}
ServiceRoutingAgentHeader routingAgentHeader;
if (!request_->Headers.TryReadFirst(routingAgentHeader))
{
TRACE_ERROR_AND_TESTASSERT(TraceComponent, "ServiceRoutingAgentHeader missing: {0}", request_->MessageId);
this->TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage);
return;
}
wstring hostId;
ErrorCode error = this->GetHostId(routingAgentHeader.TypeId, hostId);
if (error.IsSuccess())
{
error = ServiceRoutingAgentMessage::RewrapForRoutingAgentProxy(*request_, routingAgentHeader);
}
if (error.IsSuccess())
{
WriteNoise(
TraceComponent,
"{0} forwarding request {1} to host {2}",
this->TraceId,
routingAgentHeader,
hostId);
// There used to be an IpcServer/IpcClient bug that miscalculates the message header signature
// when there are deleted headers. Preserve the Compact() here anyway as good practice.
//
request_->Headers.Compact();
auto operation = owner_.ipcServer_.BeginRequest(
request_->Clone(),
hostId,
this->RemainingTime,
[this](AsyncOperationSPtr const & operation) { this->OnForwardToServiceComplete(operation, false); },
thisSPtr);
this->OnForwardToServiceComplete(operation, true);
}
else
{
this->TryComplete(thisSPtr, error);
}
}
ErrorCode ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::GetHostId(
ServiceTypeIdentifier const & serviceTypeId,
__out wstring & hostId)
{
auto error = owner_.hosting_.GetHostId(
VersionedServiceTypeIdentifier(serviceTypeId, ServicePackageVersionInstance()),
SystemServiceApplicationNameHelper::SystemServiceApplicationName,
hostId);
if (!error.IsSuccess())
{
WriteInfo(
TraceComponent,
"{0} host Id for service type {1} not found: {2}",
this->TraceId,
serviceTypeId,
error);
}
return error;
}
void ServiceRoutingAgent::Impl::NodeToServiceAsyncOperation::OnForwardToServiceComplete(
AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously)
{
return;
}
MessageUPtr reply;
ErrorCode error = owner_.ipcServer_.EndRequest(operation, reply);
if (error.IsError(ErrorCodeValue::CannotConnectToAnonymousTarget))
{
// Translate to an error that is retryable at the gateway.
// It will re-resolve and resend the request.
//
error = ErrorCodeValue::MessageHandlerDoesNotExistFault;
}
if (error.IsSuccess())
{
error = ServiceRoutingAgentMessage::ValidateIpcReply(*reply);
if (error.IsSuccess())
{
this->SetReply(move(reply));
}
}
this->TryComplete(operation->Parent, error);
}
// *** Public ServiceRoutingAgent
ServiceRoutingAgent::ServiceRoutingAgent(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
: implUPtr_(make_unique<Impl>(
ipcServer,
federation,
hosting,
naming,
root))
{
}
ServiceRoutingAgentUPtr ServiceRoutingAgent::Create(
__in IpcServer & ipcServer,
__in FederationSubsystem & federation,
__in IHostingSubsystem & hosting,
__in IGateway & naming,
ComponentRoot const & root)
{
return unique_ptr<ServiceRoutingAgent>(new ServiceRoutingAgent(ipcServer, federation, hosting, naming, root));
}
ErrorCode ServiceRoutingAgent::OnOpen()
{
return implUPtr_->Open();
}
ErrorCode ServiceRoutingAgent::OnClose()
{
return implUPtr_->Close();
}
void ServiceRoutingAgent::OnAbort()
{
implUPtr_->Abort();
}
| 30.698324
| 144
| 0.655096
|
gridgentoo
|
2a75e213076961ba296d5a5866f686977fed0115
| 1,045
|
hpp
|
C++
|
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | 2
|
2021-09-30T06:23:29.000Z
|
2022-03-09T09:59:09.000Z
|
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | null | null | null |
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | 1
|
2021-08-20T13:56:14.000Z
|
2021-08-20T13:56:14.000Z
|
#ifndef AMC_READSKELETON_HPP
#define AMC_READSKELETON_HPP
#include <string>
#include <vector>
#include "Skeleton.hpp"
using std::string;
using std::vector;
bool ReadSkeleton(string filename, Library::Skeleton& into);
bool ReadSkeletonV(string filename, Library::Skeleton& into);
// read 'amc' file format (automatically will call below on '.bmc' and '.v',
// though):
bool ReadAnimation(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the 'bmc' binary format (somewhat faster, probably):
bool ReadAnimationBin(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the '.v' file format:
bool ReadAnimationV(
string filename, Library::Skeleton const& on, vector<double>& positions);
// copies skel into transformer, but making it into an euler-angle skeleton
// pose.skeleton = &transformer;
// pose.to_angles(angles);
// angles.to_pose(pose);
void get_euler_skeleton(
Library::Skeleton& transformer, const Library::Skeleton& skel);
#endif // READSKELETON_HPP
| 30.735294
| 77
| 0.747368
|
jyf588
|
2a760ab3d73648d5df9057572aa0c23fb98e8d87
| 9,193
|
cpp
|
C++
|
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "storage/http/StorageHttpDownloadHandler.h"
#include "webservice/Common.h"
#include "process/ProcessUtils.h"
#include "fs/FileUtils.h"
#include "hdfs/HdfsHelper.h"
#include "kvstore/Part.h"
#include "thread/GenericThreadPool.h"
#include <proxygen/httpserver/RequestHandler.h>
#include <proxygen/lib/http/ProxygenErrorEnum.h>
#include <proxygen/httpserver/ResponseBuilder.h>
#include <mutex>
DEFINE_int32(download_thread_num, 3, "download thread number");
namespace nebula {
namespace storage {
using proxygen::HTTPMessage;
using proxygen::HTTPMethod;
using proxygen::ProxygenError;
using proxygen::UpgradeProtocol;
using proxygen::ResponseBuilder;
void StorageHttpDownloadHandler::init(nebula::hdfs::HdfsHelper *helper,
nebula::thread::GenericThreadPool *pool,
nebula::kvstore::KVStore *kvstore,
std::vector<std::string> paths) {
helper_ = helper;
pool_ = pool;
kvstore_ = kvstore;
paths_ = paths;
CHECK_NOTNULL(helper_);
CHECK_NOTNULL(pool_);
CHECK_NOTNULL(kvstore_);
CHECK(!paths_.empty());
}
void StorageHttpDownloadHandler::onRequest(std::unique_ptr<HTTPMessage> headers) noexcept {
if (headers->getMethod().value() != HTTPMethod::GET) {
// Unsupported method
err_ = HttpCode::E_UNSUPPORTED_METHOD;
return;
}
if (!headers->hasQueryParam("host") ||
!headers->hasQueryParam("port") ||
!headers->hasQueryParam("path") ||
!headers->hasQueryParam("parts") ||
!headers->hasQueryParam("space")) {
LOG(ERROR) << "Illegal Argument";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
hdfsHost_ = headers->getQueryParam("host");
hdfsPort_ = headers->getIntQueryParam("port");
hdfsPath_ = headers->getQueryParam("path");
if (headers->hasQueryParam("options")) {
options_.assign(headers->getQueryParam("options"));
}
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPath_, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
}
bool exist = existStatus.value();
if (!exist) {
LOG(ERROR) << "Hdfs non exist. hdfs://" << hdfsHost_ << ":" << hdfsPort_ << hdfsPath_;
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
spaceID_ = headers->getIntQueryParam("space");
auto partitions = headers->getQueryParam("parts");
folly::split(",", partitions, parts_, true);
if (parts_.empty()) {
LOG(ERROR) << "Partitions should be not empty";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
if (headers->hasQueryParam("tag")) {
auto& tag = headers->getQueryParam("tag");
tag_.assign(folly::to<TagID>(tag));
}
if (headers->hasQueryParam("edge")) {
auto& edge = headers->getQueryParam("edge");
edge_.assign(folly::to<EdgeType>(edge));
}
for (auto &path : paths_) {
std::string downloadRootPath = folly::stringPrintf(
"%s/nebula/%d/download", path.c_str(), spaceID_);
std::string downloadRootPathEdge = downloadRootPath + "/edge";
std::string downloadRootPathTag = downloadRootPath + "/tag";
std::string downloadRootPathGeneral = downloadRootPath + "/general";
std::string downloadPath;
if (edge_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathEdge.c_str(), edge_.value());
} else if (tag_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathTag.c_str(), tag_.value());
} else {
downloadPath = downloadRootPathGeneral;
}
fs::FileUtils::remove(downloadPath.c_str(), true);
fs::FileUtils::makeDir(downloadPath);
}
}
void StorageHttpDownloadHandler::onBody(std::unique_ptr<folly::IOBuf>) noexcept {
// Do nothing, we only support GET
}
void StorageHttpDownloadHandler::onEOM() noexcept {
switch (err_) {
case HttpCode::E_UNSUPPORTED_METHOD:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::METHOD_NOT_ALLOWED),
WebServiceUtils::toString(HttpStatusCode::METHOD_NOT_ALLOWED))
.sendWithEOM();
return;
case HttpCode::E_ILLEGAL_ARGUMENT:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::BAD_REQUEST),
WebServiceUtils::toString(HttpStatusCode::BAD_REQUEST))
.sendWithEOM();
return;
default:
break;
}
if (helper_->checkHadoopPath()) {
if (downloadSSTFiles()) {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::OK),
WebServiceUtils::toString(HttpStatusCode::OK))
.body("SSTFile download successfully")
.sendWithEOM();
} else {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::FORBIDDEN),
WebServiceUtils::toString(HttpStatusCode::FORBIDDEN))
.body("SSTFile download failed")
.sendWithEOM();
}
} else {
LOG(ERROR) << "HADOOP_HOME not exist";
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::NOT_FOUND),
WebServiceUtils::toString(HttpStatusCode::NOT_FOUND))
.sendWithEOM();
}
}
void StorageHttpDownloadHandler::onUpgrade(UpgradeProtocol) noexcept {
// Do nothing
}
void StorageHttpDownloadHandler::requestComplete() noexcept {
delete this;
}
void StorageHttpDownloadHandler::onError(ProxygenError error) noexcept {
LOG(ERROR) << "Web Service StorageHttpDownloadHandler got error: "
<< proxygen::getErrorString(error);
}
bool StorageHttpDownloadHandler::downloadSSTFiles() {
std::vector<folly::SemiFuture<bool>> futures;
for (auto& part : parts_) {
PartitionID partId;
try {
partId = folly::to<PartitionID>(part);
} catch (const std::exception& ex) {
LOG(ERROR) << "Invalid part: \"" << part << "\"";
return false;
}
auto hdfsPartPath = folly::stringPrintf("%s/%d", hdfsPath_.c_str(), partId);
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPartPath, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
return false;
}
bool exist = existStatus.value();
if (!exist) {
LOG(WARNING) << "Hdfs path non exist. hdfs://"
<< hdfsHost_ << ":" << hdfsPort_ << hdfsPartPath;
continue;
}
auto partResult = kvstore_->part(spaceID_, partId);
if (!ok(partResult)) {
LOG(ERROR) << "Can't found space: " << spaceID_ << ", part: " << partId;
return false;
}
auto partDataRoot = value(partResult)->engine()->getDataRoot();
std::string localPath;
if (edge_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/edge/%d", partDataRoot, edge_.value());
} else if (tag_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/tag/%d", partDataRoot, tag_.value());
} else {
localPath = folly::stringPrintf(
"%s/download/general", partDataRoot);
}
auto downloader = [this, hdfsPartPath, localPath] {
auto resultStatus = this->helper_->copyToLocal(
hdfsHost_, hdfsPort_, hdfsPartPath, localPath, options_);
if (!resultStatus.ok()) {
LOG(ERROR) << "Run Hdfs CopyToLocal failed. "
<< resultStatus.status().toString();
return false;
}
auto result = std::move(resultStatus).value();
return result.empty();
};
auto future = pool_->addTask(downloader);
futures.push_back(std::move(future));
}
bool successfully{true};
folly::collectAll(futures).thenValue([&](const std::vector<folly::Try<bool>>& tries) {
for (const auto& t : tries) {
if (t.hasException()) {
LOG(ERROR) << "Download Failed: " << t.exception();
successfully = false;
break;
}
if (!t.value()) {
successfully = false;
break;
}
}
}).wait();
LOG(INFO) << "Download tasks have finished";
return successfully;
}
} // namespace storage
} // namespace nebula
| 34.82197
| 94
| 0.589579
|
xuguruogu
|
2a76f8f4ffcc98ceb57bede3502eab783f260a31
| 562
|
hh
|
C++
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 24
|
2015-01-19T16:38:24.000Z
|
2022-01-15T01:25:30.000Z
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 2
|
2017-01-07T10:47:06.000Z
|
2018-01-16T07:19:57.000Z
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 7
|
2015-01-19T16:38:31.000Z
|
2020-12-12T19:10:30.000Z
|
#pragma once
# include <git2.h>
# include "../mimosa/mimosa/non-copyable.hh"
namespace mimosa
{
namespace git
{
class Commit : public NonCopyable
{
public:
inline Commit() : commit_(nullptr) {}
inline Commit(git_repository *repo, const git_oid *id) {
git_commit_lookup(&commit_, repo, id);
}
inline ~Commit() { git_commit_free(commit_); }
inline git_commit** ref() { return &commit_; }
inline operator git_commit *() const { return commit_; }
private:
git_commit *commit_;
};
}
}
| 19.37931
| 62
| 0.617438
|
abique
|
2a7787d11a1172271f751bacc12720ae9cb1f8aa
| 5,069
|
cpp
|
C++
|
petanque/src/exprs.cpp
|
Liblor/arybo
|
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
|
[
"BSD-3-Clause"
] | 223
|
2016-09-12T16:31:12.000Z
|
2022-03-14T08:32:04.000Z
|
petanque/src/exprs.cpp
|
Liblor/arybo
|
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
|
[
"BSD-3-Clause"
] | 17
|
2016-11-02T15:20:15.000Z
|
2021-10-02T23:30:58.000Z
|
petanque/src/exprs.cpp
|
Liblor/arybo
|
9b98bda682ccd6d0c7e2ffd66281711b46ae23ed
|
[
"BSD-3-Clause"
] | 33
|
2016-09-13T07:28:31.000Z
|
2022-01-18T07:06:42.000Z
|
// Copyright (c) 2016 Adrien Guinet <adrien@guinet.me>
// 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <pa/algos.h>
#include <pa/exprs.h>
#include <pa/cast.h>
#include <pa/simps.h>
bool pa::Expr::ExprArgsStorage::args_less_than(pa::ExprArgs const& a, pa::ExprArgs const& b)
{
if (a.size() < b.size()) {
return true;
}
if (a.size() > b.size()) {
return false;
}
return std::lexicographical_compare(std::begin(a), std::end(a), std::begin(b), std::end(b));
}
bool pa::Expr::ExprArgsStorage::args_equal_with(pa::ExprArgs const& a, pa::ExprArgs const& b)
{
return a == b;
}
bool pa::Expr::operator==(Expr const& o) const
{
if (type() != o.type()) {
return false;
}
return call([&o] (auto const& t) { typedef decltype(t) E; return t == expr_assert_cast<E const&>(o); });
}
bool pa::Expr::operator<(Expr const& o) const
{
if (type() != o.type()) {
return type() < o.type();
}
return call([&o] (auto const& e) { typedef decltype(e) E; return e < expr_assert_cast<E const&>(o); });
}
bool pa::Expr::is_anf() const
{
auto const* add = expr_dynamic_cast<pa::ExprAdd const*>(this);
if (!add) {
return false;
}
for (Expr const& a: add->args()) {
if (auto const* mul = expr_dynamic_cast<pa::ExprMul const*>(&a)) {
for (Expr const& s: mul->args()) {
if (!s.is_sym()) {
return false;
}
}
}
else
if (auto const* imm = expr_dynamic_cast<pa::ExprImm const*>(&a)) {
if (imm->value() != true) {
return false;
}
}
else
if (!a.is_sym()) {
return false;
}
}
return true;
}
unsigned pa::Expr::anf_esf_max_degree() const
{
assert(is_anf());
for (auto it = args().rbegin(); it != args().rend(); ++it) {
if (it->is_mul()) {
return it->args().size();
}
}
return 0;
}
bool pa::Expr::contains(Expr const& o) const
{
if (type() != o.type()) {
if (has_args()) {
return args().find(o) != args().cend();
}
return false;
}
if ((!has_args()) || (o.args().size() == args().size())) {
return (*this == o);
}
// If this is the same type, checks that arguments of 'o' are inside our expression.
// Assumes than 'o' and ourself are sorted
assert(std::is_sorted(args().begin(), args().end()));
assert(std::is_sorted(o.args().begin(), o.args().end()));
if (o.args().size() > args().size()) {
return false;
}
auto it_o = o.args().begin();
const auto it_o_end = o.args().end();
const auto it_end = args().end();
auto it_find = args().begin();
while (it_o != it_o_end) {
it_find = args().find(*it_o, it_find);
if (it_find == it_end) {
return false;
}
++it_o;
++it_find;
}
return true;
}
uint64_t pa::Expr::hash() const
{
return call([](auto const& e) { return e.hash(); });
}
void pa::ExprESF::expand()
{
if (degree() == 1) {
// Fast path, just transform it into an addition
set_type(expr_type_id::add_type);
return;
}
ExprAdd ret;
ExprArgs& args_ret = ret.args();
ExprArgs const& args_ = args();
draw_without_replacement<size_t>(degree(), nargs(),
[&args_ret,&args_](size_t const* idxes, size_t const n)
{
if (n == 0) {
return true;
}
Expr tmp = args_[idxes[0]];
for (size_t i = 1; i < n; i++) {
Expr const& cur_a = args_[idxes[i]];
if (cur_a.is_imm()) {
ExprImm const& cur_imm = cur_a.as<ExprImm>();
if (cur_imm.value() == false) {
return true;
}
}
else {
tmp *= cur_a;
}
}
args_ret.insert_dup(std::move(tmp));
return true;
});
if (args_ret.size() == 1) {
static_cast<Expr&>(*this) = std::move(args_ret[0]);
}
else {
set<ExprAdd>(std::move(ret));
}
}
| 27.252688
| 105
| 0.642336
|
Liblor
|
2a7a17eb32aa76f1824c22d26b9978c1c654c6b4
| 1,152
|
cpp
|
C++
|
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | 13
|
2015-06-07T09:26:26.000Z
|
2019-05-01T13:23:38.000Z
|
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | null | null | null |
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | 4
|
2016-03-05T06:21:05.000Z
|
2017-02-17T15:34:18.000Z
|
// http://algospot.com/judge/problem/read/STARFORCE
#include <cstdio>
#include <iostream>
using namespace std;
int n, m, s, best;
int in[200];
int pre[200][200]; // pre processed : or
void input() {
scanf("%d %d", &n, &m);
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
for (i = 0; i < n; i++) {
pre[i][i] = in[i];
for (j = i + 1; j < n; j++) {
pre[i][j] = pre[i][j-1] | in[j];
}
}
}
bool possible(int all, int start, int remain) {
if (remain == 0) return true;
for (int i = start; i <= n - remain; i++) {
if ((all & pre[start][i]) == all) {
return possible(all, i+1, remain-1);
}
}
return false;
}
int next(int v) {
unsigned int t = (v | (v - 1)) + 1;
return t | ((((t & -t) / (v & -v)) >> 1) - 1);
}
void solve() {
int now = 0xFFFF;
while (now > 0) {
if (possible(now, 0, m)) break;
now = next(now) & 0xFFFF;
}
printf("%d\n", __builtin_popcount(now));
}
int main() {
int num;
scanf("%d", &num);
for (int i = 0; i < num; i++) {input(); solve();}
return 0;
}
| 19.525424
| 53
| 0.454861
|
seirion
|
2a7cc699bef9f1b012901b82f1de0ee85c925214
| 2,241
|
cpp
|
C++
|
archives/problemset/acm.hdu.edu.cn/4727.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 6
|
2019-03-23T21:06:25.000Z
|
2021-06-27T05:22:41.000Z
|
archives/problemset/acm.hdu.edu.cn/4727.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 1
|
2020-10-11T08:14:00.000Z
|
2020-10-11T08:14:00.000Z
|
archives/problemset/acm.hdu.edu.cn/4727.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 3
|
2019-03-23T21:06:31.000Z
|
2021-10-24T01:44:01.000Z
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
//const double eps=1e-8;
//struct P
//{
// double x,y;
// void in(){scanf("%lf%lf",&x,&y);}
//};
//double dis(P a,P b)
//{
// return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
//}
//int sgn(double x)
//{
// return (x>eps)-(x<-eps);
//}
//P a,b,c,T,p[6];
//int main()
//{
// int cas,i,j;
// scanf("%d",&cas);
// P cp;
// bool flag;
// pair<int,int>t;
// for(int k=1;k<=cas;k++)
// {
// a.in();
// b.in();
// c.in();
// T.in();
// double a1=b.x-a.x,b1=b.y-a.y,c1=(a1*a1+b1*b1)/2;
// double a2=c.x-a.x,b2=c.y-a.y,c2=(a2*a2+b2*b2)/2;
// double d=a1*b2-a2*b1;
// if(fabs(d)<1e-8)
// {
// p[0]=a;p[1]=b;p[2]=c;
// t=make_pair(0,1);
// for(i=0;i<3;i++)
// for(j=i+1;j<3;j++)
// if(dis(p[i],p[j])>dis(p[t.first],p[t.second]))
// t=make_pair(i,j);
// cp.x=(p[t.first].x+p[t.second].x)/2;
// cp.y=(p[t.first].y+p[t.second].y)/2;
// if(sgn(dis(T,cp)-dis(cp,a))<=0)flag=true;
// else flag=false;
// }
// else
// {
// cp.x=a.x+(c1*b2-c2*b1)/d;
// cp.y=a.y+(a1*c2-a2*c1)/d;
// printf("%f %f\n",dis(T,cp),dis(cp,a));
// if(sgn(dis(T,cp)-dis(cp,a))<=0)flag=true;
// else flag=false;
// }
// printf("Case #%d: ",k);
// if(flag)puts("Danger");
// else puts("Safe");
//
// }
//}
int a[129299],n;
int main()
{
int cas;
scanf("%d",&cas);
int k,i,ans;
for(k=1;k<=cas;k++)
{
scanf("%d",&n);
ans=-1;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(i>1&&a[i]!=a[i-1]+1)ans=i;
}
if(ans==-1)ans=1;
printf("Case #%d: %d\n",k,ans);
}
}
//int main()
//{
// int T;
// scanf("%d",&T);
// for (int t=1;t<=T;t++)
// {
// int ans=0;
// printf("Case #%d: %d\n",t,ans);
// }
//}
| 23.34375
| 69
| 0.374386
|
BoleynSu
|
2a81a4b4521f2e21d16f437712949fd2c3b8bc93
| 1,105
|
cpp
|
C++
|
src/erase_remove.cpp
|
ebayboy/cpp_demos
|
b01df202c0285bf232900662d336505520d5d24d
|
[
"Apache-2.0"
] | null | null | null |
src/erase_remove.cpp
|
ebayboy/cpp_demos
|
b01df202c0285bf232900662d336505520d5d24d
|
[
"Apache-2.0"
] | null | null | null |
src/erase_remove.cpp
|
ebayboy/cpp_demos
|
b01df202c0285bf232900662d336505520d5d24d
|
[
"Apache-2.0"
] | null | null | null |
/*
erase && remove
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int args, char **argv)
{
vector<int> v;
for (size_t i = 0; i < 10; i++)
{
v.push_back(i);
if (i == 5 || i == 8)
v.push_back(i);
}
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
for (auto it = v.begin(); it != v.end(); it++)
{
if (*it == 5)
{
//test erase
v.erase(it--); //元素删除后迭代器需要退1,保证不丢掉重复的元素5
}
}
//erase删除后, v的元素减少
cout << "after erase size:" << v.size() << endl;
cout << "after remove show:================" << endl;
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
auto it = std::remove(v.begin(),v.end(), 8);
if (it != v.end()) {
cout << "remove:" << *it << endl;
}
//remove后size没减少, 而是将删除的元素放到end后面
cout << "after remove: size:" << v.size() << endl;
cout << "end:" << *v.end() << endl;
for (auto &&i : v)
{
cout << "i:" << i << endl;
}
return 0;
}
| 18.416667
| 57
| 0.420814
|
ebayboy
|
2a83cb520267fb9b00cd17a3bf6acc4d462c2568
| 2,453
|
cpp
|
C++
|
examples/undocumented/libshogun/features_copy_subset_simple_features.cpp
|
srgnuclear/shogun
|
33c04f77a642416376521b0cd1eed29b3256ac13
|
[
"Ruby",
"MIT"
] | 1
|
2015-11-05T18:31:14.000Z
|
2015-11-05T18:31:14.000Z
|
examples/undocumented/libshogun/features_copy_subset_simple_features.cpp
|
waderly/shogun
|
9288b6fa38e001d63c32188f7f847dadea66e2ae
|
[
"Ruby",
"MIT"
] | null | null | null |
examples/undocumented/libshogun/features_copy_subset_simple_features.cpp
|
waderly/shogun
|
9288b6fa38e001d63c32188f7f847dadea66e2ae
|
[
"Ruby",
"MIT"
] | null | null | null |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011-2012 Heiko Strathmann
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include <shogun/base/init.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/features/Subset.h>
using namespace shogun;
void test()
{
SGMatrix<float64_t> data(3, 10);
CDenseFeatures<float64_t>* f=new CDenseFeatures<float64_t>(data);
SGVector<float64_t>::range_fill_vector(data.matrix, data.num_cols*data.num_rows, 1.0);
SGMatrix<float64_t>::display_matrix(data.matrix, data.num_rows, data.num_cols,
"original feature data");
index_t offset_subset=1;
SGVector<index_t> feature_subset(8);
SGVector<index_t>::range_fill_vector(feature_subset.vector, feature_subset.vlen,
offset_subset);
SGVector<index_t>::display_vector(feature_subset.vector, feature_subset.vlen,
"feature subset");
f->add_subset(feature_subset);
SG_SPRINT("feature vectors after setting subset on original data:\n");
for (index_t i=0; i<f->get_num_vectors(); ++i)
{
SGVector<float64_t> vec=f->get_feature_vector(i);
SG_SPRINT("%i: ", i);
SGVector<float64_t>::display_vector(vec.vector, vec.vlen);
f->free_feature_vector(vec, i);
}
index_t offset_copy=2;
SGVector<index_t> feature_copy_subset(4);
SGVector<index_t>::range_fill_vector(feature_copy_subset.vector,
feature_copy_subset.vlen, offset_copy);
SGVector<index_t>::display_vector(feature_copy_subset.vector, feature_copy_subset.vlen,
"indices that are to be copied");
CDenseFeatures<float64_t>* subset_copy=
(CDenseFeatures<float64_t>*)f->copy_subset(feature_copy_subset);
SGMatrix<float64_t> subset_copy_matrix=subset_copy->get_feature_matrix();
SGMatrix<float64_t>::display_matrix(subset_copy_matrix.matrix,
subset_copy_matrix.num_rows, subset_copy_matrix.num_cols,
"copy matrix");
index_t num_its=subset_copy_matrix.num_rows*subset_copy_matrix.num_cols;
for (index_t i=0; i<num_its; ++i)
{
index_t idx=i+(offset_copy+offset_subset)*subset_copy_matrix.num_rows;
ASSERT(subset_copy_matrix.matrix[i]==data.matrix[idx]);
}
SG_UNREF(f);
SG_UNREF(subset_copy);
}
int main(int argc, char **argv)
{
init_shogun_with_defaults();
test();
exit_shogun();
return 0;
}
| 31.050633
| 88
| 0.766001
|
srgnuclear
|
2a8472d1cf692179f88f0bd648b65ffcadde02f4
| 532
|
cc
|
C++
|
003-xoxoxo-tcp/xoxoxo.cc
|
gynvael/stream
|
2d1a3f25b2f83241b39dab931d9ff03fca81d26e
|
[
"MIT"
] | 152
|
2016-02-04T10:40:46.000Z
|
2022-03-03T18:25:54.000Z
|
003-xoxoxo-tcp/xoxoxo.cc
|
gynvael/stream
|
2d1a3f25b2f83241b39dab931d9ff03fca81d26e
|
[
"MIT"
] | 4
|
2016-03-11T23:49:46.000Z
|
2017-06-16T18:58:53.000Z
|
003-xoxoxo-tcp/xoxoxo.cc
|
gynvael/stream
|
2d1a3f25b2f83241b39dab931d9ff03fca81d26e
|
[
"MIT"
] | 48
|
2016-01-31T19:13:36.000Z
|
2021-09-03T19:50:17.000Z
|
#include <cstdio>
#include "NetSock.h"
void usage() {
printf("usage: xoxoxo <host> <port>\n");
}
int main(int argc, char **argv) {
if (argc != 3) {
usage();
return 1;
}
unsigned short port;
if (sscanf(argv[2], "%hu", &port) != 1) {
usage();
return 2;
}
const char *host = argv[1];
NetSock::InitNetworking();
NetSock s;
if (!s.Connect(host, port)) {
fprintf(stderr, "Could not connect!\n");
return 3;
}
s.Disconnect();
return 0;
}
| 14.777778
| 45
| 0.511278
|
gynvael
|
2a84f22684d7b564d74896a34f15a6aa02daef67
| 4,930
|
cpp
|
C++
|
Libraries/libvitaboy/vbparse.cpp
|
daddesio/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | 10
|
2017-04-28T08:09:25.000Z
|
2022-03-28T11:08:18.000Z
|
Libraries/libvitaboy/vbparse.cpp
|
Fatbag/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | null | null | null |
Libraries/libvitaboy/vbparse.cpp
|
Fatbag/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | 4
|
2015-06-23T11:06:34.000Z
|
2017-01-17T03:50:08.000Z
|
/*
libvitaboy - Open source OpenGL TSO character animation library
vbparse.cpp - Copyright (c) 2012 Niotso Project <http://niotso.org/>
Author(s): Fatbag <X-Fi6@phppoll.org>
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 <stdio.h>
#include <strings.h>
#include <FileHandler.hpp>
#include "libvitaboy.hpp"
enum VBFileType {
VBFILE_ANIM,
VBFILE_APR,
VBFILE_BND,
VBFILE_COL,
VBFILE_HAG,
VBFILE_MESH,
VBFILE_OFT,
VBFILE_PO,
VBFILE_SKEL
};
int main(int argc, char *argv[]){
int type;
char * InFile;
if(argc == 1 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
printf("Usage: vbparse [-t type] infile\n"
"Parse a TSO VitaBoy file.\n"
"\n"
"Supported types:\n"
" (*) ANIM - Animation\n"
" (*) APR - Appearance\n"
" (*) BND - Binding\n"
" (*) COL - Collection\n"
" (*) HAG - Hand group\n"
" (*) MESH - Mesh\n"
" (*) OFT - Outfit\n"
" (*) PO - Purchasable object\n"
" (*) SKEL - Skeleton\n"
"\n"
"Report bugs to <X-Fi6@phppoll.org>.\n"
"vbparse is maintained by the Niotso project.\n"
"Home page: <http://www.niotso.org/>");
return 0;
}
if(argc >= 4 && !strcmp(argv[1], "-t")){
if(!stricmp(argv[2], "anim")) type = 0;
else if(!stricmp(argv[2], "apr")) type = 1;
else if(!stricmp(argv[2], "bnd")) type = 2;
else if(!stricmp(argv[2], "col")) type = 3;
else if(!stricmp(argv[2], "hag")) type = 4;
else if(!stricmp(argv[2], "mesh")) type = 5;
else if(!stricmp(argv[2], "oft")) type = 6;
else if(!stricmp(argv[2], "po")) type = 7;
else if(!stricmp(argv[2], "skel")) type = 8;
else{
printf("%sUnrecognized type '%s'", "vbparse: Error: ", argv[2]);
return -1;
}
InFile = argv[3];
}else{
char * pos = strrchr(argv[1], '.') + 1;
if(!stricmp(pos, "anim")) type = 0;
else if(!stricmp(pos, "apr")) type = 1;
else if(!stricmp(pos, "bnd")) type = 2;
else if(!stricmp(pos, "col")) type = 3;
else if(!stricmp(pos, "hag")) type = 4;
else if(!stricmp(pos, "mesh")) type = 5;
else if(!stricmp(pos, "oft")) type = 6;
else if(!stricmp(pos, "po")) type = 7;
else if(!stricmp(pos, "skel")) type = 8;
else{
printf("%sUnrecognized type", "vbparse: Error: ");
return -1;
}
InFile = argv[1];
}
uint8_t *InData = File::ReadFile(InFile);
if(InData == NULL){
const char * Message;
switch(File::Error){
case FERR_NOT_FOUND:
Message = "%s does not exist.";
break;
case FERR_OPEN:
Message = "%s could not be opened for reading.";
break;
case FERR_BLANK:
Message = "%s is corrupt or invalid.";
break;
case FERR_MEMORY:
Message = "Memory for %s could not be allocated.";
break;
default:
Message = "%s could not be read.";
break;
}
printf(Message, InFile);
return -1;
}
VBFile.set(InData, File::FileSize);
switch(type){
case VBFILE_ANIM:
Animation_t Animation;
ReadAnimation(Animation);
break;
case VBFILE_APR:
Appearance_t Appearance;
ReadAppearance(Appearance);
break;
case VBFILE_BND:
Binding_t Binding;
ReadBinding(Binding);
break;
case VBFILE_COL:
Collection_t Collection;
ReadCollection(Collection);
break;
case VBFILE_HAG:
HandGroup_t HandGroup;
ReadHandGroup(HandGroup);
break;
case VBFILE_MESH:
Mesh_t Mesh;
ReadMesh(Mesh);
break;
case VBFILE_OFT:
Outfit_t Outfit;
ReadOutfit(Outfit);
break;
case VBFILE_PO:
PurchasableOutfit_t PurchasableOutfit;
ReadPurchasableOutfit(PurchasableOutfit);
break;
case VBFILE_SKEL:
Skeleton_t Skeleton;
ReadSkeleton(Skeleton);
}
return 0;
}
| 30.8125
| 76
| 0.558621
|
daddesio
|
2a899caff1f02550a918d0971f15bf607f12f8d8
| 2,453
|
cc
|
C++
|
src/body.cc
|
wgtdkp/apollonia
|
0e57af431818bc9a19e9952f4d4b2a294e1c9d8b
|
[
"MIT"
] | 126
|
2017-10-11T04:39:45.000Z
|
2022-03-05T23:16:06.000Z
|
src/body.cc
|
FrostDescent/apollonia
|
18f15102b1620d38de1b7de0939c9e93d8449f69
|
[
"MIT"
] | 1
|
2020-11-08T15:01:28.000Z
|
2020-11-08T15:01:28.000Z
|
src/body.cc
|
FrostDescent/apollonia
|
18f15102b1620d38de1b7de0939c9e93d8449f69
|
[
"MIT"
] | 24
|
2018-08-22T06:25:54.000Z
|
2022-01-08T05:31:52.000Z
|
#include "body.h"
#include <algorithm>
namespace apollonia {
using std::abs;
void Body::set_mass(Float mass) {
mass_ = mass;
inv_mass_ = 1 / mass;
}
void Body::set_inertia(Float inertia) {
inertia_ = inertia;
inv_inertia_ = 1 / inertia;
}
bool Body::ShouldCollide(const Body& other) const {
return !(mass_ == kInf && other.mass_ == kInf);
}
void Body::ApplyImpulse(const Vec2& impulse, const Vec2& r) {
velocity_ += impulse * inv_mass_;
angular_velocity_ += inv_inertia_ * Cross(r, impulse);
}
void Body::Integrate(const Vec2& gravity, Float dt) {
if (mass_ == kInf) {
return;
}
velocity_ += (gravity + force_ * inv_mass_) * dt;
angular_velocity_ += (torque_ * inv_inertia_) * dt;
position_ += velocity_ * dt;
rotation_ = Mat22(angular_velocity_ * dt) * rotation_;
}
static Float PolygonArea(const std::vector<Vec2>& vertices) {
Float area = 0;
for (size_t i = 0; i < vertices.size(); ++i) {
auto j = (i+1) % vertices.size();
area += Cross(vertices[i], vertices[j]);
}
return area / 2;
}
static Vec2 PolygonCentroid(const std::vector<Vec2>& vertices) {
Vec2 gc {0, 0};
for (size_t i = 0; i < vertices.size(); ++i) {
auto j = (i+1) % vertices.size();
gc += (vertices[i] + vertices[j]) * Cross(vertices[i], vertices[j]);
}
return gc / 6 / PolygonArea(vertices);
}
static Float PolygonInertia(Float mass, const PolygonBody::VertexList& vertices) {
Float acc0 = 0, acc1 = 0;
for (size_t i = 0; i < vertices.size(); ++i) {
auto a = vertices[i], b = vertices[(i+1)%vertices.size()];
auto cross = abs(Cross(a, b));
acc0 += cross * (Dot(a, a) + Dot(b, b) + Dot(a, b));
acc1 += cross;
}
return mass * acc0 / 6 / acc1;
}
PolygonBody::PolygonBody(Float mass, const VertexList& vertices)
: Body(mass), vertices_(vertices) {
set_inertia(PolygonInertia(mass, vertices));
set_centroid(PolygonCentroid(vertices));
}
Float PolygonBody::FindMinSeparatingAxis(size_t& idx, const PolygonBody& other) const {
Float separation = -kInf;
for (size_t i = 0; i < this->Count(); ++i) {
auto va = this->LocalToWorld((*this)[i]);
auto normal = this->EdgeAt(i).Normal();
auto min_sep = kInf;
for (size_t j = 0; j < other.Count(); ++j) {
auto vb = other.LocalToWorld(other[j]);
min_sep = std::min(min_sep, Dot(vb - va, normal));
}
if (min_sep > separation) {
separation = min_sep;
idx = i;
}
}
return separation;
}
}
| 26.956044
| 87
| 0.630656
|
wgtdkp
|
2a8c25a01728f4ae28a96fee151383affdcce969
| 6,100
|
cpp
|
C++
|
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "Rendering/Text/Internal/Font.h"
#include "Core/Application.h"
#include "Rendering/ShaderManager.h"
#include "Rendering/Shader.h"
#include "Rendering/Window.h"
#include <glm/gtc/type_ptr.hpp>
using namespace TE;
#ifdef TRICKSTER_OPENGL
void Font::Initialize()
{
// configure VAO/VBO for texture quads
// -----------------------------------
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
/*
* The size of each vertex
* Position: x, y, z = 3
* Color: r, g, b, a = 4
* TODO: implement batch rendering
*
*/
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 9, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(5 * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Font::LoadFromFile(const std::string& a_FileName)
{
FT_Error m_Error;
FT_Library m_Library;
FT_Face m_Face;
if (FT_Init_FreeType(&m_Library))
{
LOG_ERROR("[Font] " + a_FileName + " Could not init FreeType Library");
return;
}
if (FT_New_Face(m_Library, ("Resources/Fonts/" + a_FileName + ".ttf").c_str(), 0, &m_Face)) {
LOG_ERROR("[Font] " + a_FileName + " Failed to load font");
return;
}
// set size to load glyphs as
FT_Set_Pixel_Sizes(m_Face, 0, 48);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction
FT_GlyphSlot g = m_Face->glyph;
int w = 0;
int h = 0;
for (int i = 0; i < 128; i++) {
if (FT_Load_Char(m_Face, i, FT_LOAD_RENDER)) {
fprintf(stderr, "Loading character %c failed!\n", i);
continue;
}
w += g->bitmap.width;
h = max(h, static_cast<int>(g->bitmap.rows));
}
/* you might as well save this value as it is needed later on */
atlas_width = static_cast<float>(w);
atlas_height = static_cast<float>(h);
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
int x = 0;
for (unsigned char c = 0; c < 128; c++) {
if (FT_Load_Char(m_Face, c, FT_LOAD_RENDER))
continue;
m_Characters[c].ax = g->advance.x >> 6;
m_Characters[c].ay = g->advance.y >> 6;
m_Characters[c].bw = g->bitmap.width;
m_Characters[c].bh = g->bitmap.rows;
m_Characters[c].bl = g->bitmap_left;
m_Characters[c].bt = g->bitmap_top;
m_Characters[c].tx = static_cast<float>(x) / static_cast<float>(w);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, 0, g->bitmap.width, g->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer);
x += g->bitmap.width;
}
glBindTexture(GL_TEXTURE_2D, 0);
// destroy FreeType once we're finished
FT_Done_Face(m_Face);
FT_Done_FreeType(m_Library);
}
void Font::Render()
{
Shader* shader = ShaderManager::GetShader("BasicFont");
shader->Bind();
glm::mat4 projection = glm::ortho(0.0f, static_cast<float>(Application::Get()->GetWindow()->GetWidth()), 0.0f, static_cast<float>(Application::Get()->GetWindow()->GetHeight()));
// activate corresponding render state
glUniformMatrix4fv(shader->GetUniformLocation("projection"), 1, GL_FALSE, glm::value_ptr(projection));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, coords.size() * 9 * sizeof(float), &coords[0], GL_DYNAMIC_DRAW);
glDrawArrays(GL_TRIANGLES, 0, coords.size());
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
coords.clear();
}
bool Font::operator==(const Font& other)
{
return m_FileName == other.m_FileName;
}
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
// iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character* ch = &m_Characters[*c];
float x2 = x + ch->bl * scale;
float y2 = -y - ch->bt * scale;
float w = ch->bw * scale;
float h = ch->bh * scale;
/* Advance the cursor to the start of the next character */
x += ch->ax * scale;
y += ch->ay * scale;
float z = 0.f;
coords.push_back({ x2, -y2 , z, ch->tx, 0, color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 , z,ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height, color.r, color.g, color.b, color.a }); //remember: each glyph occupies a different amount of vertical space
coords.push_back({ x2 + w, -y2 , z, ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 - h, z, ch->tx + ch->bw / atlas_width, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
}
}
#endif
#ifdef TRICKSTER_VULKAN
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
}
void Font::Initialize()
{
}
void Font::LoadFromFile(const std::string& a_FileName)
{
}
void Font::Render()
{
}
bool Font::operator==(const Font& other)
{
return true;
}
#endif
Font::Font()
{
Initialize();
}
Font::~Font()
{
}
| 28.240741
| 187
| 0.62623
|
Trickje
|
2a9033e59bc54cb6063e2e3a1ef32b17cc82f547
| 2,105
|
cpp
|
C++
|
extras/cpp/main.cpp
|
skn123/DeslantImg
|
b7183ff31067e51d8dcba581c6241b15ceb87f28
|
[
"MIT"
] | 115
|
2018-07-19T16:37:54.000Z
|
2022-03-28T09:22:04.000Z
|
extras/cpp/main.cpp
|
skn123/DeslantImg
|
b7183ff31067e51d8dcba581c6241b15ceb87f28
|
[
"MIT"
] | 5
|
2018-08-06T14:38:08.000Z
|
2021-11-21T10:12:43.000Z
|
extras/cpp/main.cpp
|
skn123/DeslantImg
|
b7183ff31067e51d8dcba581c6241b15ceb87f28
|
[
"MIT"
] | 36
|
2018-01-26T03:56:44.000Z
|
2022-03-07T22:32:05.000Z
|
#ifdef USE_GPU
#include "DeslantImgGPU.hpp"
#else
#include "DeslantImgCPU.hpp"
#endif
#include <opencv2/imgcodecs.hpp>
#include <iostream>
int main(int argc, const char *argv[])
{
const cv::String opts =
"{help h usage ? | | print this message }"
"{@imagein |- | path name to read the input image from (or stdin) }"
"{@imageout |- | path name to write the output image to (or stdout) }"
"{lower_bound |-1.0 | lower bound of shear values }"
"{upper_bound |1.0 | upper bound of shear values }"
"{bg_color |255 | color to fill the gaps of the sheared image that is returned }"
;
cv::CommandLineParser parser(argc, argv, opts);
#ifdef USE_GPU
parser.about("DeslantImg GPU");
#else
parser.about("DeslantImg CPU");
#endif
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
if (!parser.check())
{
parser.printErrors();
return 1;
}
cv::String inpath = parser.get<cv::String>("@imagein");
cv::String outpath = parser.get<cv::String>("@imageout");
float lower_bound = parser.get<float>("lower_bound");
float upper_bound = parser.get<float>("upper_bound");
int bg_color = parser.get<int>("bg_color");
#ifdef USE_GPU
htr::CLWrapper clWrapper; // setup OpenCL, the same instance should be used for all following calls to deslantImg
#endif
// load input image
cv::Mat img;
if (inpath == "-")
{
char c;
std::vector<char> data;
std::cin >> std::noskipws;
while (std::cin >> c)
data.push_back(c);
const cv::Mat rawimg(data);
img = cv::imdecode(rawimg, cv::IMREAD_GRAYSCALE);
}
else
img = cv::imread(inpath, cv::IMREAD_GRAYSCALE);
#ifdef USE_GPU
// deslant on GPU
const cv::Mat res = htr::deslantImg(img, bg_color, clWrapper);
#else
// deslant on CPU
cv::Mat res = htr::deslantImg(img, bg_color, lower_bound, upper_bound);
#endif
// write result to file
if (outpath == "-")
{
std::vector<unsigned char> data;
if (cv::imencode(".png", res, data))
{
std::string out(data.begin(), data.end());
std::cout << out;
}
else
return 1;
}
else
cv::imwrite(outpath, res);
return 0;
}
| 25.361446
| 114
| 0.651781
|
skn123
|
2a90974d03cbd0acc93682c3cb5ca024d5f5cc92
| 3,348
|
cc
|
C++
|
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
#include "statement.hpp"
#include <sstream>
#include <stack>
#include <memory>
#include <utility>
#include <typeinfo>
namespace statement
{
std::ostream &operator<< (std::ostream &os, const statement &x)
{
x.print(os);
return os;
}
std::ostream &operator<< (std::ostream &os, const assignment &x)
{
x.print(os);
return os;
}
program_type read_program(std::istream &is)
{
std::map<line_num, std::unique_ptr<statement>> ret;
line_num line;
std::stack<std::pair<line_num, std::string>> FOR_stack;
while (is >> line)
{
auto attemp_insert
= ret.insert(std::make_pair(line, std::unique_ptr<statement>()));
if (!attemp_insert.second)
throw "Line number repeated.";
std::string statement_type;
is >> statement_type;
std::unique_ptr<statement> sentence;
std::string sentence_str;
getline(is, sentence_str);
if (statement_type == "REM")
sentence = std::make_unique<REM>();
else if (statement_type == "LET")
sentence = std::make_unique<LET>(sentence_str);
else if (statement_type == "INPUT")
sentence = std::make_unique<INPUT>(sentence_str);
else if (statement_type == "EXIT")
sentence = std::make_unique<EXIT>(sentence_str);
else if (statement_type == "GOTO")
sentence = std::make_unique<GOTO>(sentence_str);
else if (statement_type == "IF")
sentence = std::make_unique<IF>(sentence_str);
else if (statement_type == "FOR")
{
FOR_stack.push(std::make_pair(line, sentence_str));
continue;
}
else if (statement_type == "END")
{
std::istringstream iss(sentence_str);
std::string for_expected;
iss >> for_expected;
if (for_expected != "FOR")
throw "Unknown token.";
char tmp;
if (iss >> tmp)
throw "Extra trailing characters.";
if (FOR_stack.empty())
throw "Unpaired \"END FOR\".";
auto &&FOR_info = FOR_stack.top();
const auto &str = FOR_info.second;
ret[FOR_info.first] = std::make_unique<FOR>(str, line);
sentence = std::make_unique<END_FOR>(FOR_info.first,
assignment(std::string(str, 0, str.find(';'))));
FOR_stack.pop();
}
else
throw "Unknown token.";
attemp_insert.first->second = std::move(sentence);
}
for (auto &[line, sent] : ret)
{
const auto &sent_type = typeid(*sent);
if (sent_type == typeid(IF))
{
line_num &target_line = static_cast<IF&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
if (sent_type == typeid(GOTO))
{
line_num &target_line = static_cast<GOTO&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
}
if (!is.eof())
throw "Error when reading program. Probably caused by missing line number.";
if (!FOR_stack.empty())
throw "Unpaired \"FOR\".";
if (ret.count(INT_MAX) != 0)
throw ":-( Line number too big.";
ret[additional_exit_line]
= std::make_unique<EXIT>(std::make_unique<expr::imm_num>(0));
return ret;
}
void print_program(std::ostream &os, const program_type &prog)
{
for (const auto &[line, sent] : prog)
os << '#' << line << ":\t" << *sent << std::endl;
}
}
| 28.615385
| 78
| 0.660992
|
xukl
|
2a914457d6f2022d1e593143d3b2c188989b1327
| 5,715
|
cc
|
C++
|
elements/analysis/aggcountervector.cc
|
timmytimj/fastclick
|
260dfa7285e5fff3c916b8272249d6d393e61179
|
[
"BSD-3-Clause-Clear"
] | 129
|
2015-10-08T14:38:35.000Z
|
2022-03-06T14:54:44.000Z
|
elements/analysis/aggcountervector.cc
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | 241
|
2016-02-17T16:17:58.000Z
|
2022-03-15T09:08:33.000Z
|
elements/analysis/aggcountervector.cc
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | 61
|
2015-12-17T01:46:58.000Z
|
2022-02-07T22:25:19.000Z
|
/*
* aggcountervector.{cc,hh} -- count packets/bytes with given aggregate
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "aggcountervector.hh"
#include <click/handlercall.hh>
#include <click/args.hh>
#include <click/error.hh>
#include <click/packet_anno.hh>
#include <click/integers.hh> // for first_bit_set
#include <click/router.hh>
CLICK_DECLS
AggregateCounterVector::AggregateCounterVector() : _epoch(0)
{
}
AggregateCounterVector::~AggregateCounterVector()
{
}
int
AggregateCounterVector::configure(Vector<String> &conf, ErrorHandler *errh)
{
bool bytes = false;
bool ip_bytes = false;
bool packet_count = true;
bool extra_length = true;
uint32_t freeze_nnz, stop_nnz;
uint32_t mask = (uint32_t)-1;
uint64_t freeze_count, stop_count;
bool mark = false;
String call_nnz, call_count;
if (Args(conf, this, errh)
.read_mp("MASK", mask)
.read("MARK", mark)
.read("BYTES", bytes)
.read("IP_BYTES", ip_bytes)
.read("MULTIPACKET", packet_count)
.read("EXTRA_LENGTH", extra_length)
.complete() < 0)
return -1;
_bytes = bytes;
_ip_bytes = ip_bytes;
_use_packet_count = packet_count;
_use_extra_length = extra_length;
_mask = mask;
_mark = mark;
_nodes.resize(mask + 1);
return 0;
}
int
AggregateCounterVector::initialize(ErrorHandler *errh)
{
_active = true;
return 0;
}
void
AggregateCounterVector::cleanup(CleanupStage)
{
}
inline bool
AggregateCounterVector::update_batch(PacketBatch *batch)
{
if (!_active)
return false;
uint32_t last_agg = 0;
Node *n = 0;
FOR_EACH_PACKET(batch,p) {
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
if (agg == last_agg && n) {
} else {
bool outdated =false;
n = &find_node(last_agg,p,outdated);
if (outdated)
return true;
if (!n)
return false;
last_agg = agg;
}
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
n->count += amount;
#if COUNT_FLOWS
n->add_flow(AGGREGATE_ANNO(p));
#endif
}
return true;
}
inline bool
AggregateCounterVector::update(Packet *p)
{
if (!_active)
return false;
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
bool outdated = false;
Node &n = find_node(agg, p, outdated);
if (outdated)
return true;
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
#if COUNT_FLOWS
n.add_flow(AGGREGATE_ANNO(p));
#endif
n.count += amount;
return true;
}
void
AggregateCounterVector::push(int port, Packet *p)
{
port = !update(p);
output(noutputs() == 1 ? 0 : port).push(p);
}
Packet *
AggregateCounterVector::pull(int)
{
Packet *p = input(0).pull();
if (p && _active)
update(p);
return p;
}
#if HAVE_BATCH
void
AggregateCounterVector::push_batch(int port, PacketBatch *batch)
{
auto fnt = [this,port](Packet*p){return !update(p);};
CLASSIFY_EACH_PACKET(2,fnt,batch,[this](int port, PacketBatch* batch){ output(0).push_batch(batch);});
}
PacketBatch *
AggregateCounterVector::pull_batch(int port,unsigned max)
{
PacketBatch *batch = input(0).pull_batch(max);
if (batch && _active) {
FOR_EACH_PACKET(batch,p) {
update(p);
}
}
return batch;
}
#endif
enum {
AC_ACTIVE, AC_STOP,
};
String
AggregateCounterVector::read_handler(Element *e, void *thunk)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
switch ((intptr_t)thunk) {
default:
return "<error>";
}
}
int
AggregateCounterVector::write_handler(const String &data, Element *e, void *thunk, ErrorHandler *errh)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
String s = cp_uncomment(data);
switch ((intptr_t)thunk) {
case AC_ACTIVE: {
bool val;
if (!BoolArg().parse(s, val))
return errh->error("type mismatch");
ac->_active = val;
return 0;
}
case AC_STOP:
ac->_active = false;
ac->router()->please_stop_driver();
return 0;
default:
return errh->error("internal error");
}
}
void
AggregateCounterVector::add_handlers()
{
add_data_handlers("active", Handler::f_read | Handler::f_checkbox, &_active);
add_write_handler("active", write_handler, AC_ACTIVE);
add_write_handler("stop", write_handler, AC_STOP, Handler::f_button);
}
ELEMENT_REQUIRES(userlevel int64)
EXPORT_ELEMENT(AggregateCounterVector)
ELEMENT_MT_SAFE(AggregateCounterVector)
CLICK_ENDDECLS
| 22.951807
| 106
| 0.665267
|
timmytimj
|
2a91841d2ecf5ba60689bdd71a926067f8f69011
| 12,043
|
cpp
|
C++
|
psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp
|
maoa3/scalpel
|
2e7381b516cded28996d290438acc618d00b2aa7
|
[
"Unlicense"
] | 15
|
2018-06-28T01:11:25.000Z
|
2021-09-27T15:57:18.000Z
|
psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp
|
maoa3/scalpel
|
2e7381b516cded28996d290438acc618d00b2aa7
|
[
"Unlicense"
] | 7
|
2018-06-29T04:08:23.000Z
|
2019-10-17T13:57:22.000Z
|
psx/_dump_/43/_dump_c_src_/diabpsx/source/inv.cpp
|
maoa3/scalpel
|
2e7381b516cded28996d290438acc618d00b2aa7
|
[
"Unlicense"
] | 7
|
2018-06-28T01:11:34.000Z
|
2020-05-23T09:21:48.000Z
|
// C:\diabpsx\SOURCE\INV.CPP
#include "types.h"
// address: 0x801558DC
// line start: 434
// line end: 435
void FreeInvGFX__Fv() {
}
// address: 0x801558E4
// line start: 440
// line end: 447
void InvDrawSlot__Fiii(int X, int Y, int Frame) {
// register: 2
// size: 0x28
register struct POLY_FT4 *Ft4;
}
// address: 0x80155968
// line start: 452
// line end: 483
void InvDrawSlotBack__FiiiiUc(int X, int Y, int W, int H, int Flag) {
// register: 4
// size: 0x28
register struct POLY_FT4 *Ft4;
}
// address: 0x80155BBC
// line start: 489
// line end: 502
void InvDrawItem__FiiiUci(int ItemX, int ItemY, int ItemNo, unsigned char StatFlag, int TransFlag) {
// register: 3
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 4
// size: 0x6C
register struct TextDat *TData;
}
// address: 0x80155C8C
// line start: 507
// line end: 552
void InvDrawSlots__Fv() {
// register: 16
register int Bx;
// register: 17
register int By;
}
// address: 0x80155F64
// line start: 562
// line end: 564
void PrintStat__FiiPcUc(int Y, int Txt0, char *Txt1, unsigned char Col) {
}
// address: 0x80156030
// line start: 569
// line end: 720
void DrawInvStats__Fv() {
// address: 0xFFFFFFC8
// size: 0x10
auto struct Dialog InvBack;
// register: 18
register char c;
// address: 0xFFFFFFD8
// size: 0xA
auto char chrstr[10];
// register: 17
register long mind;
// register: 16
register long maxd;
// register: 16
register int hper;
// register: 16
register int ac;
}
// address: 0x80156B4C
// line start: 725
// line end: 732
void DrawInvBack__Fv() {
// address: 0xFFFFFFE8
// size: 0x10
auto struct Dialog InvBack;
}
// address: 0x80156BD4
// line start: 737
// line end: 840
void DrawInvCursor__Fv() {
// register: 6
register int ItemX;
// register: 8
register int ItemY;
// register: 4
register int LoopX;
// register: 5
register int LoopY;
// register: 4
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 4
// size: 0x6C
register struct TextDat *TData;
}
// address: 0x801570B0
// line start: 846
// line end: 877
void DrawInvMsg__Fv() {
// register: 2
// size: 0x28
register struct POLY_FT4 *Ft4;
// address: 0xFFFFFFD8
// size: 0x8
auto struct RECT InfoRect;
// register: 3
register int InfoX;
// register: 16
register int InfoY;
// address: 0xFFFFFFE0
// size: 0x10
auto struct Dialog InvBack;
}
// address: 0x80157278
// line start: 883
// line end: 914
void DrawInvUnique__Fv() {
// register: 19
// size: 0x6C
register struct TextDat *ThisDat;
// register: 10
// size: 0x28
register struct POLY_FT4 *Ft4;
// register: 17
register int x;
// register: 16
register int y;
// register: 18
register int flip;
}
// address: 0x8015739C
// line start: 931
// line end: 935
void DrawInv__Fv() {
}
// address: 0x801573DC
// line start: 942
// line end: 1046
void DrawInvTSK__FP4TASK(struct TASK *T) {
// register: 18
register int omp;
// register: 19
register int osel;
// register: 16
// size: 0xE0
register struct CBlocks *BgBlocks;
}
// address: 0x80157720
// line start: 1052
// line end: 1256
void DoThatDrawInv__Fv() {
// register: 16
register int Loop;
// register: 3
register int ii;
// register: 9
register int ItemX;
// register: 5
register int ItemY;
// register: 6
register int ItemNo;
}
// address: 0x80157EE8
// line start: 1261
// line end: 1308
unsigned char AutoPlace__FiiiiUc(int pnum, int ii, int sx, int sy, int saveflag) {
// register: 5
register int i;
// register: 11
register int j;
// register: 4
register int xx;
// register: 10
register int yy;
// register: 16
register unsigned char done;
}
// address: 0x80158208
// line start: 1313
// line end: 1377
unsigned char SpecialAutoPlace__FiiiiUc(int pnum, int ii, int sx, int sy, int saveflag) {
// register: 5
register int i;
// register: 11
register int j;
// register: 4
register int xx;
// register: 10
register int yy;
// register: 16
register unsigned char done;
}
// address: 0x801585A4
// line start: 1382
// line end: 1475
unsigned char GoldAutoPlace__Fi(int pnum) {
// register: 16
register int i;
// register: 19
register int ii;
// register: 10
register int xx;
// register: 8
register int yy;
// register: 3
register long gt;
// register: 6
register unsigned char done;
}
// address: 0x80158A74
// line start: 1480
// line end: 1507
unsigned char WeaponAutoPlace__Fi(int pnum) {
}
// address: 0x80158D00
// line start: 1513
// line end: 1519
int SwapItem__FP10ItemStructT0(struct ItemStruct *a, struct ItemStruct *b) {
// address: 0xFFFFFF68
// size: 0x98
auto struct ItemStruct h;
}
// address: 0x80158DFC
// line start: 1526
// line end: 1933
void CheckInvPaste__Fiii(int pnum, int mx, int my) {
// register: 21
register int r;
// register: 23
register int sx;
// register: 30
register int sy;
// register: 16
register int i;
// register: 9
register int j;
// register: 7
register int xx;
// register: 10
register int yy;
// register: 8
register int ii;
// register: 17
register unsigned char done;
// register: 17
register unsigned char done2h;
// register: 20
register int il;
// register: 22
register int cn;
// register: 2
register int it;
// register: 19
register int iv;
// register: 5
register int ig;
// register: 5
register long gt;
// address: 0xFFFFFED8
// size: 0x98
auto struct ItemStruct tempitem;
}
// address: 0x8015AAE8
// line start: 1975
// line end: 2091
void CheckInvCut__Fiii(int pnum, int mx, int my) {
// register: 18
register int r;
// register: 8
register int ii;
// register: 8
register int iv;
}
// address: 0x8015B598
// line start: 2116
// line end: 2137
void RemoveInvItem__Fii(int pnum, int iv) {
}
// address: 0x8015B840
// line start: 2145
// line end: 2149
void RemoveSpdBarItem__Fii(int pnum, int iv) {
}
// address: 0x8015B934
// line start: 2157
// line end: 2161
void CheckInvScrn__Fv() {
}
// address: 0x8015B9AC
// line start: 2175
// line end: 2184
void CheckItemStats__Fi(int pnum) {
// register: 4
// size: 0x23A8
register struct PlayerStruct *p;
}
// address: 0x8015BA30
// line start: 2190
// line end: 2202
void CheckBookLevel__Fi(int pnum) {
// register: 6
register int slvl;
}
// address: 0x8015BB64
// line start: 2208
// line end: 2266
void CheckQuestItem__Fi(int pnum) {
}
// address: 0x8015BF8C
// line start: 2276
// line end: 2335
void InvGetItem__Fii(int pnum, int ii) {
// register: 5
register int j;
// register: 4
register int jj;
}
// address: 0x8015C288
// line start: 2342
// line end: 2477
void AutoGetItem__Fii(int pnum, int ii) {
// register: 16
register int i;
// register: 2
register int g;
// register: 20
register int w;
// register: 21
register int h;
// register: 4
register int idx;
// register: 17
register unsigned char done;
{
{
// register: 5
register int j;
// register: 2
register int jj;
}
}
}
// address: 0x8015CCF8
// line start: 2521
// line end: 2535
int FindGetItem__FiUsi(int idx, unsigned short ci, int iseed) {
// register: 8
register int i;
// register: 7
register int ii;
}
// address: 0x8015CDAC
// line start: 2541
// line end: 2602
void SyncGetItem__FiiiUsi(int x, int y, int idx, unsigned short ci, int iseed) {
// register: 16
register int ii;
{
{
// register: 5
register int j;
// register: 4
register int jj;
}
}
}
// address: 0x8015CF38
// line start: 2617
// line end: 2639
unsigned char TryInvPut__Fv() {
{
{
}
}
}
// address: 0x8015D100
// line start: 2669
// line end: 2769
int InvPutItem__Fiii(int pnum, int x, int y) {
// register: 16
register int ii;
// register: 23
register unsigned char done;
{
// register: 21
register int d;
{
// register: 16
register int dy;
{
{
{
{
{
{
{
// register: 18
register int l;
{
{
// register: 19
register int j;
{
// register: 20
register int yy;
{
// register: 17
register int i;
{
// register: 16
register int xx;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
// address: 0x8015D5A8
// line start: 2781
// line end: 2885
int SyncPutItem__FiiiiUsiUciiiiiUl(int pnum, int x, int y, int idx, int icreateinfo, int iseed, int Id, int dur, int mdur, int ch, int mch, int ivalue, unsigned long ibuff) {
// register: 16
register int ii;
// register: 17
register int d;
// register: 16
register int dy;
{
{
{
{
{
{
// register: 21
register unsigned char done;
{
// register: 18
register int l;
{
{
// register: 20
register int j;
{
// register: 19
register int yy;
{
// register: 17
register int i;
{
// register: 16
register int xx;
}
}
}
}
}
}
}
}
}
}
}
}
}
// address: 0x8015DB04
// line start: 2890
// line end: 2999
char CheckInvHLight__Fv() {
// register: 16
register int r;
// register: 19
register char rv;
// register: 17
// size: 0x98
register struct ItemStruct *pi;
// register: 18
// size: 0x23A8
register struct PlayerStruct *p;
{
{
// register: 17
register int nGold;
}
}
}
// address: 0x8015DE4C
// line start: 3006
// line end: 3029
void RemoveScroll__Fi(int pnum) {
// register: 5
register int i;
}
// address: 0x8015E030
// line start: 3035
// line end: 3057
unsigned char UseScroll__Fv() {
// register: 5
register int i;
}
// address: 0x8015E298
// line start: 3064
// line end: 3071
void UseStaffCharge__FP12PlayerStruct(struct PlayerStruct *ptrplr) {
}
// address: 0x8015E300
// line start: 3079
// line end: 3087
unsigned char UseStaff__Fv() {
}
// address: 0x8015E3C0
// line start: 3138
// line end: 3152
void StartGoldDrop__Fv() {
}
// address: 0x8015E4BC
// line start: 3161
// line end: 3247
unsigned char UseInvItem__Fii(int pnum, int cii) {
// register: 18
register int c;
// register: 3
register int idata;
// register: 3
register int it;
// register: 17
// size: 0x98
register struct ItemStruct *Item;
// register: 19
register unsigned char speedlist;
}
// address: 0x8015E9E0
// line start: 3253
// line end: 3265
void DoTelekinesis__Fv() {
}
// address: 0x8015EB08
// line start: 3272
// line end: 3291
long CalculateGold__Fi(int pnum) {
// register: 6
register int i;
// register: 9
register long gold;
}
// address: 0x8015EC40
// line start: 3305
// line end: 3312
unsigned char DropItemBeforeTrig__Fv() {
}
// address: 0x8015EC98
// line start: 3428
// line end: 3506
void ControlInv__Fv() {
}
// address: 0x8015EFA4
// line start: 3512
// line end: 3521
void InvGetItemWH__Fi(int Pos) {
}
// address: 0x8015F098
// line start: 3527
// line end: 3546
void InvAlignObject__Fv() {
}
// address: 0x8015F24C
// line start: 3553
// line end: 3573
void InvSetItemCurs__Fv() {
// register: 6
register int ItemNo;
}
// address: 0x8015F3DC
// line start: 3580
// line end: 3675
void InvMoveCursLeft__Fv() {
// register: 5
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015F584
// line start: 3681
// line end: 3784
void InvMoveCursRight__Fv() {
// register: 4
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015F838
// line start: 3789
// line end: 3882
void InvMoveCursUp__Fv() {
// register: 4
register int ItemInc;
// register: 16
register int OldPos;
}
// address: 0x8015FA30
// line start: 3887
// line end: 3987
void InvMoveCursDown__Fv() {
// register: 17
register int ItemInc;
// register: 16
register int OldPos;
}
| 16.633978
| 174
| 0.630242
|
maoa3
|
2a95e492aa69efa777e391e9c118fc572e339acd
| 7,859
|
cc
|
C++
|
Replicator/Worker.cc
|
bjornd/couchbase-lite-core
|
5da4cc825021bb90be591ae4ab835be201333a0a
|
[
"Apache-2.0"
] | null | null | null |
Replicator/Worker.cc
|
bjornd/couchbase-lite-core
|
5da4cc825021bb90be591ae4ab835be201333a0a
|
[
"Apache-2.0"
] | null | null | null |
Replicator/Worker.cc
|
bjornd/couchbase-lite-core
|
5da4cc825021bb90be591ae4ab835be201333a0a
|
[
"Apache-2.0"
] | null | null | null |
//
// Worker.cc
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "Worker.hh"
#include "Replicator.hh"
#include "ReplicatorTypes.hh"
#include "c4Private.h"
#include "Logging.hh"
#include "StringUtil.hh"
#include "PlatformCompat.hh"
#include "BLIP.hh"
#include <sstream>
#if defined(__clang__) && !defined(__ANDROID__)
#include <cxxabi.h>
#endif
using namespace std;
using namespace fleece;
using namespace fleeceapi;
using namespace litecore::blip;
namespace litecore {
LogDomain SyncLog("Sync");
}
namespace litecore { namespace repl {
LogDomain SyncBusyLog("SyncBusy", LogLevel::Warning);
static void writeRedacted(Dict dict, stringstream &s) {
s << "{";
int n = 0;
for (Dict::iterator i(dict); i; ++i) {
if (n++ > 0)
s << ", ";
slice key = i.keyString();
s << key << ":";
if (key == slice(C4STR(kC4ReplicatorAuthPassword))) {
s << "\"********\"";
} else if (i.value().asDict()) {
writeRedacted(i.value().asDict(), s);
} else {
alloc_slice json( i.value().toJSON5() );
s << json;
}
}
s << "}";
}
Worker::Options::operator string() const {
static const char* kModeNames[] = {"disabled", "passive", "one-shot", "continuous"};
stringstream s;
if (push != kC4Disabled)
s << "Push=" << kModeNames[push] << ", ";
if (pull != kC4Disabled)
s << "Pull=" << kModeNames[pull] << ", ";
s << "Options={";
writeRedacted(properties, s);
s << "}";
return s.str();
}
Worker::Worker(blip::Connection *connection,
Worker *parent,
const Options &options,
const char *namePrefix)
:Actor( string(namePrefix) + connection->name() )
,Logging(SyncLog)
,_connection(connection)
,_parent(parent)
,_options(options)
,_status{(connection->state() >= Connection::kConnected) ? kC4Idle : kC4Connecting}
,_loggingID(connection->name())
{ }
Worker::Worker(Worker *parent,
const char *namePrefix)
:Worker(parent->_connection, parent, parent->_options, namePrefix)
{
}
Worker::~Worker() {
if (_important)
logStats();
logDebug("deleting %s [%p]", actorName().c_str(), this);
}
void Worker::sendRequest(blip::MessageBuilder& builder, MessageProgressCallback callback) {
if (callback) {
increment(_pendingResponseCount);
builder.onProgress = asynchronize([=](MessageProgress progress) {
if (progress.state >= MessageProgress::kComplete)
decrement(_pendingResponseCount);
callback(progress);
});
} else {
if (!builder.noreply)
warn("Ignoring the response to a BLIP message!");
}
assert(_connection);
_connection->sendRequest(builder);
}
#pragma mark - ERRORS:
static const char* const kErrorDomainNames[] = {
nullptr, "LiteCore", "POSIX", nullptr, "SQLite", "Fleece", "Network", "WebSocket"};
blip::ErrorBuf Worker::c4ToBLIPError(C4Error err) {
//FIX: Map common errors to more standard domains
if (!err.code)
return { };
return {slice(kErrorDomainNames[err.domain]),
err.code,
alloc_slice(c4error_getMessage(err))};
}
C4Error Worker::blipToC4Error(const blip::Error &err) {
if (!err.domain)
return { };
C4ErrorDomain domain = LiteCoreDomain;
int code = kC4ErrorRemoteError;
string domainStr = err.domain.asString();
const char* domainCStr = domainStr.c_str();
for (uint32_t d = 0; d <= WebSocketDomain; d++) {
if (kErrorDomainNames[d] && strcmp(domainCStr, kErrorDomainNames[d]) == 0) {
domain = (C4ErrorDomain)d;
code = err.code;
break;
}
}
return c4error_make(domain, code, err.message);
}
void Worker::gotError(const MessageIn* msg) {
auto err = msg->getError();
logError("Got error response: %.*s %d '%.*s'",
SPLAT(err.domain), err.code, SPLAT(err.message));
onError(blipToC4Error(err));
}
void Worker::gotError(C4Error err) {
alloc_slice message = c4error_getMessage(err);
logError("Got LiteCore error: %.*s (%d/%d)", SPLAT(message), err.domain, err.code);
onError(err);
}
void Worker::caughtException(const std::exception &x) {
logError("Threw C++ exception: %s", x.what());
onError(c4error_make(LiteCoreDomain, kC4ErrorUnexpectedError, slice(x.what())));
}
void Worker::onError(C4Error err) {
_status.error = err;
_statusChanged = true;
}
void Worker::gotDocumentError(slice docID, C4Error error, bool pushing, bool transient) {
_parent->gotDocumentError(docID, error, pushing, transient);
}
void Worker::finishedDocument(slice docID, bool pushing) {
addProgress({0, 0, 1});
// if (_notifyAllDocuments) // experimental
// gotDocumentError(docID, {}, pushing, true);
}
#pragma mark - ACTIVITY / PROGRESS:
void Worker::setProgress(C4Progress p) {
addProgress(p - _status.progress);
}
void Worker::addProgress(C4Progress p) {
if (p.unitsCompleted || p.unitsTotal || p.documentCount) {
_status.progressDelta += p;
_status.progress += p;
_statusChanged = true;
}
}
Worker::ActivityLevel Worker::computeActivityLevel() const {
if (eventCount() > 1 || _pendingResponseCount > 0)
return kC4Busy;
else
return kC4Idle;
}
// Called after every event; updates busy status & detects when I'm done
void Worker::afterEvent() {
bool changed = _statusChanged;
_statusChanged = false;
if (changed && _important) {
logVerbose("progress +%llu/+%llu, %llu docs -- now %llu / %llu, %llu docs",
_status.progressDelta.unitsCompleted, _status.progressDelta.unitsTotal,
_status.progressDelta.documentCount,
_status.progress.unitsCompleted, _status.progress.unitsTotal,
_status.progress.documentCount);
}
auto newLevel = computeActivityLevel();
if (newLevel != _status.level) {
_status.level = newLevel;
changed = true;
if (_important) {
auto name = kC4ReplicatorActivityLevelNames[newLevel];
if (_important > 1)
log("now %-s", name);
else
logVerbose("now %-s", name);
}
}
if (changed)
changedStatus();
_status.progressDelta = {0, 0};
}
void Worker::changedStatus() {
if (_parent)
_parent->childChangedStatus(this, _status);
if (_status.level == kC4Stopped)
_parent = nullptr;
}
} }
| 29.882129
| 95
| 0.56992
|
bjornd
|
2a9962ad8459dd796b9b7bb9f7d2e9a7ff9d9fc4
| 9,610
|
cpp
|
C++
|
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
#include "../precompiled/stdafx.h"
#include "../engine/base.h"
#include "../../common/utility/ext_xml.h"
#include "../../common/utility/ext_util.h"
//////////////////////////////////////////////////////////////////////////
// CMap default constructor & destructor
//////////////////////////////////////////////////////////////////////////
CMap::CMap()
{
// sub-modules
m_pSky = NULL;
m_pSea = NULL;
m_pLandscape = NULL;
// variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
}
CMap::~CMap()
{
// free data
Free();
}
//////////////////////////////////////////////////////////////////////////
// Free() : Unloads all map-related data from memmory
//////////////////////////////////////////////////////////////////////////
void CMap::Free()
{
// destroy sky
delete m_pSky;
m_pSky = NULL;
// destroy sea
delete m_pSea;
m_pSea = NULL;
// destroy landscape
delete m_pLandscape;
m_pLandscape = NULL;
// reset variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
m_Timer.Update();
m_strTitle.erase();
// free players list
m_Players.clear();
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(int iMap, TMapWarp iProcedence)
{
// format the string
std::ostringstream temp;
temp << "maps/map" << iMap << ".pak";
// load the map
return Load(temp.str(), iProcedence);
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(const std::string & strFile, TMapWarp iProcedence)
{
// temporary variables
xmlDocPtr doc;
xmlNodePtr node;
std::string strTemp;
// map info variables
std::string name;
std::string music;
int length;
int hm_length;
int shoreline;
int min_stars;
int max_stars;
float fog_density;
float visibility;
float scale;
CVector3 vDayBaseColor;
CVector3 vNightBaseColor;
CVector3 vDayBaseAmbient;
CVector3 vNightBaseAmbient;
// PHASE 0: free everything
Free();
// PHASE 1: open xml file
strTemp = strFile + "/settings.xml";
doc = ext::xml_parse_file(strTemp);
// check for document
if(!doc) return false;
// get root element and check for map
node = xmlDocGetRootElement(doc);
if(!node || xmlStrcmp(node->name, (const xmlChar *) "map"))
{
xmlFreeDoc(doc);
return false;
}
// get directly to first node
node = node->children->next;
// retrieve map settings
name = ext::xml_get_string(doc, node, "name");
music = ext::xml_get_string(doc, node, "music");
length = ext::xml_get_int(doc, node, "length");
hm_length = ext::xml_get_int(doc, node, "heightmap_length");
shoreline = ext::xml_get_int(doc, node, "shoreline");
min_stars = ext::xml_get_int(doc, node, "min_stars");
max_stars = ext::xml_get_int(doc, node, "max_stars");
fog_density = ext::xml_get_float(doc, node, "fog_density");
visibility = ext::xml_get_float(doc, node, "visibility");
scale = ext::xml_get_float(doc, node, "scale");
// retrieve sky settings
vDayBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_day_color", "r");
vDayBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_day_color", "g");
vDayBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_day_color", "b");
vNightBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_night_color", "r");
vNightBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_night_color", "g");
vNightBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_night_color", "b");
vDayBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "r");
vDayBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "g");
vDayBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "b");
vNightBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "r");
vNightBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "g");
vNightBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "b");
// free file
xmlFreeDoc(doc);
// PHASE 2: Sky allocation
m_pSky = new CSky();
if(!m_pSky) return false;
// place slightly under the player
CVector3 vCenter = CVector3(0.0f, 20.0f, 0.0f);
// create sky
m_pSky->Create(200, 200, 20,
min_stars, max_stars,
0.5f, vCenter,
vNightBaseColor, vDayBaseColor,
vNightBaseAmbient, vDayBaseAmbient);
// set null time (night)
m_pSky->SetDayTime(0.0f);
// PHASE 3: Landscape allocation
m_pLandscape = new CLandscape();
if(!m_pLandscape) return false;
// create landsape
strTemp = strFile + "/texture.tex";
std::string strHeightmap = strFile + "/heightmap.raw";
if(!m_pLandscape->Create(hm_length, scale,
strHeightmap.c_str(), strTemp.c_str())) return false;
// PHASE 5: create the sea
if(shoreline)
{
// allocate sea
m_pSea = new CSea();
if(!m_pSea) return false;
// create sea
if(!m_pSea->Create(length, shoreline * scale, m_pLandscape))
return false;
}
/*
// PHASE 6: player posistion
float py;
// where do we come from?
switch(iProcedence)
{
case FROM_NORTH:
py = m_pLandscape.HeightAt(vPosition.x, iMapLength - 300) + 2;
g_Player->SetPosition(vPosition.x, py, 300 - iMapLength);
break;
case FROM_SOUTH:
py = m_pLandscape.HeightAt(vPosition.x, 300) + 2;
g_Player->SetPosition(vPosition.x, py, -300);
break;
case FROM_EAST:
py = m_pLandscape.HeightAt(iMapLength - 300, -vPosition.z) + 2;
g_Player->SetPosition(iMapLength - 300, py, vPosition.z);
break;
case FROM_WEST:
py = m_pLandscape.HeightAt(300, -vPosition.z) + 2;
g_Player->SetPosition(300, py, vPosition.z);
break;
}
*/
// PHASE 7: set local values
m_strTitle = name;
m_fVisibility = visibility;
m_fFogDensity = fog_density;
// no errors
return true;
}
//////////////////////////////////////////////////////////////////////////
// Render() : Renders the map
//////////////////////////////////////////////////////////////////////////
void CMap::Render()
{
float fFogColor[4];
bool bUnderWater = false;
// set fog parameters
if(bUnderWater)
{
// set fog color
fFogColor[0] = 0.1f;
fFogColor[1] = 0.1f;
fFogColor[2] = 0.3f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, 50.0f);
glFogf(GL_FOG_END, 100.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
glEnable(GL_FOG);
}
else
{
// set fog color
fFogColor[0] = 0.6f;
fFogColor[1] = 0.6f;
fFogColor[2] = 0.6f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, m_fVisibility * 200.0f);
glFogf(GL_FOG_END, 300.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
}
glEnable(GL_FOG);
// set player's viewpoint
g_Player->Look();
// update frustum
g_Frustum->CalculateFrustum();
// render sky
m_pSky->Render(g_Player->GetPosition(), m_pSea ? m_pSea->GetShoreLine() : 0.0f,
CVector3(fFogColor[0], fFogColor[1], fFogColor[2]));
// render landscape
m_pLandscape->Render();
// render sea
if(m_pSea) m_pSea->Render();
// render bar with name
if(m_fBarAlpha >= 0.0f) RenderBar();
glDisable(GL_FOG);
}
//////////////////////////////////////////////////////////////////////////
// RenderBar() : Draws the bar with the map title
//////////////////////////////////////////////////////////////////////////
void CMap::RenderBar()
{
static CFont barFont("blackletter", 20, FONT_TEXTURE);
// calculate alpha
if(m_fBarAlpha < 1.0f)
{
m_fBarAlpha += 0.01f;
m_Timer.Update();
}
else
{
if(m_Timer.GetTimePassed() >= 5000) m_fBarAlpha -= 0.01f;
}
// get width & height
static const int iWidth = ext::get_option_int("screen_width");
static const int iHeight = ext::get_option_int("screen_height");
// overlay begin
g_OpenGL->OverlayBegin(iWidth, iHeight, true);
// enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// set alpha
glColor4f(0.0f, 0.0f, 0.0f, m_fBarAlpha);
// draw bar background
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(iWidth, 35);
glVertex2i(0, 35);
glVertex2i(iWidth, 0);
glVertex2i(0, 0);
glEnd();
// set white
glColor4f(1.0f, 1.0f, 1.0f, m_fBarAlpha);
// draw map name
barFont.Print(10, 8, m_strTitle);
// disable blending
glDisable(GL_BLEND);
// overlay ending
g_OpenGL->OverlayEnd();
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::AddPlayer(unsigned long dwId, CPlayer *p)
{
// if we *DON'T* have the player
if(m_Players.find(dwId) == m_Players.end())
{
// add it
m_Players.insert(std::make_pair(dwId, p));
}
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::RemovePlayer(unsigned long dwId)
{
// if we *DO* have the player
if(m_Players.find(dwId) != m_Players.end())
{
// delete it
m_Players.erase(dwId);
}
}
//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////
| 25.695187
| 85
| 0.564828
|
fcarreiro
|
2a9aa099e30b5c5cf3dfc1440168e39eeb1f2bd9
| 9,750
|
cc
|
C++
|
tensorflow/compiler/xla/service/interpreter/executable_base.cc
|
Nyrio/tensorflow
|
c111a7e2f5a6ecd3a06d47c63ff552ee0373985d
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/compiler/xla/service/interpreter/executable_base.cc
|
Nyrio/tensorflow
|
c111a7e2f5a6ecd3a06d47c63ff552ee0373985d
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/compiler/xla/service/interpreter/executable_base.cc
|
Nyrio/tensorflow
|
c111a7e2f5a6ecd3a06d47c63ff552ee0373985d
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/xla/service/interpreter/executable_base.h"
#include <type_traits>
#include <vector>
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/maybe_owning_device_memory.h"
#include "tensorflow/compiler/xla/service/shaped_buffer.h"
#include "tensorflow/compiler/xla/service/transfer_manager.h"
#include "tensorflow/compiler/xla/shape_tree.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/platform.h"
#include "tensorflow/stream_executor/stream.h"
#include "tensorflow/stream_executor/stream_executor_pimpl.h"
namespace xla {
namespace interpreter {
InterpreterExecutableBase::InterpreterExecutableBase(
std::unique_ptr<HloModule> hlo_module)
: Executable(std::move(hlo_module), /*hlo_profile_printer_data=*/nullptr,
/*hlo_profile_index_map=*/nullptr) {}
StatusOr<ExecutionOutput> InterpreterExecutableBase::ExecuteAsyncOnStream(
const ServiceExecutableRunOptions* run_options,
std::vector<ExecutionInput> arguments,
HloExecutionProfile* hlo_execution_profile) {
se::Stream* stream = run_options->stream();
se::StreamExecutor* executor = stream->parent();
const se::Platform* platform = executor->platform();
// Convert the ShapeTree to a ShapedBuffer. We do this so we can call
// TransferManager methods below.
std::vector<ShapedBuffer> argument_buffers;
argument_buffers.reserve(arguments.size());
int device_ordinal = run_options->device_ordinal();
if (device_ordinal < 0) {
device_ordinal = 0;
}
for (auto& argument : arguments) {
const ShapeTree<MaybeOwningDeviceMemory>& buffers = argument.Buffers();
argument_buffers.push_back(ShapedBuffer(buffers.shape(),
/*device_ordinal=*/device_ordinal));
auto in_it = buffers.begin();
auto out_it = argument_buffers.back().buffers().begin();
for (; in_it != buffers.end(); ++in_it, ++out_it) {
out_it->second = in_it->second.AsDeviceMemoryBase();
}
}
VLOG(1) << "Execute " << module().name();
if (VLOG_IS_ON(2)) {
for (const auto& a : argument_buffers) {
VLOG(2) << "-- argument " << a;
}
}
uint64_t start_micros = tensorflow::Env::Default()->NowMicros();
const HloComputation* computation = module().entry_computation();
if (computation->num_parameters() != arguments.size()) {
return tensorflow::errors::Internal(
"Mismatch between argument count and graph parameter count.");
}
// Check that the args have the right shape.
for (int64_t i = 0; i < computation->num_parameters(); ++i) {
const auto& expected_shape = computation->parameter_instruction(i)->shape();
const auto& actual_shape = argument_buffers[i].on_device_shape();
bool shape_match = true;
if (expected_shape.is_dynamic()) {
if (!ShapeUtil::DynamicArrayShapeIsCompatible(actual_shape,
expected_shape)) {
shape_match = false;
}
} else if (!Shape::Equal().MinorToMajorOnlyInLayout()(expected_shape,
actual_shape)) {
shape_match = false;
}
if (!shape_match) {
return InvalidArgument(
"Shape mismatch on parameter %d. Expected %s, but was %s.", i,
ShapeUtil::HumanStringWithLayout(expected_shape),
ShapeUtil::HumanStringWithLayout(actual_shape));
}
}
TF_ASSIGN_OR_RETURN(TransferManager * transfer_manager,
TransferManager::GetForPlatform(platform));
// Transform the ShapedBuffer arguments into literals which the evaluator
// consumes.
std::vector<Literal> arg_literals;
const int64_t num_parameters = computation->num_parameters();
arg_literals.reserve(num_parameters);
for (int64_t p = 0; p < num_parameters; ++p) {
TF_ASSIGN_OR_RETURN(Literal arg_literal,
transfer_manager->TransferLiteralFromDevice(
run_options->stream(), argument_buffers[p]));
const auto& expected_shape = computation->parameter_instruction(p)->shape();
if (expected_shape.is_dynamic()) {
// Expand the input literal to expected shape.
arg_literal = arg_literal.ToBoundedDynamic(expected_shape);
}
arg_literals.push_back(std::move(arg_literal));
}
TF_ASSIGN_OR_RETURN(Literal result_literal,
Evaluate(run_options, *computation, arg_literals));
// Shrink the generated dynamic shape into static shape.
result_literal = result_literal.ToStatic();
// Transform the result literal back into a ShapedBuffer.
const HloInputOutputAliasConfig& alias_config =
hlo_module_ == nullptr ? HloInputOutputAliasConfig()
: hlo_module_->input_output_alias_config();
TF_ASSIGN_OR_RETURN(ExecutionOutput result,
AllocateOutputMemoryWithInputReuse(
result_literal.shape(), alias_config,
run_options->allocator(), &arguments, stream));
TF_RETURN_IF_ERROR(transfer_manager->TransferLiteralToDevice(
run_options->stream(), result_literal, result.Result()));
uint64_t end_micros = tensorflow::Env::Default()->NowMicros();
ExecutionProfile* profile = run_options->run_options().execution_profile();
if (profile) {
const double nanoseconds = (end_micros - start_micros) * 1000.0;
profile->set_compute_time_ns(std::max(nanoseconds, 1.0));
}
MarkToBeReleasedArguments(absl::MakeSpan(arguments), result);
return std::move(result);
}
StatusOr<ExecutionOutput>
InterpreterExecutableBase::AllocateOutputMemoryWithInputReuse(
const Shape& shape, const HloInputOutputAliasConfig& alias_config,
se::DeviceMemoryAllocator* allocator,
std::vector<ExecutionInput>* arguments, se::Stream* stream) {
TF_RETURN_IF_ERROR(alias_config.ForEachAliasWithStatus(
[&](const ShapeIndex& output_index,
std::optional<HloInputOutputAliasConfig::Alias> alias) {
if (alias && alias->must_alias()) {
VLOG(1) << alias->ToString();
const MaybeOwningDeviceMemory& original_input =
(*arguments)[alias->parameter_number].Buffers().element(
alias->parameter_index);
if (!original_input.HasOwnership()) {
return InvalidArgument(
"An input was configured to be must-alias at "
"compile time but not donated at runtime: %s",
alias->ToString());
}
}
return ::tensorflow::OkStatus();
}));
se::StreamExecutor* executor = stream->parent();
const se::Platform* platform = executor->platform();
TF_ASSIGN_OR_RETURN(TransferManager * transfer_manager,
TransferManager::GetForPlatform(platform));
ExecutionOutput result(shape, allocator, executor->device_ordinal());
for (auto& pair : result.MutableResult()->buffers()) {
const ShapeIndex& result_index = pair.first;
se::DeviceMemoryBase& result_buffer = pair.second;
int64_t allocation_bytes =
transfer_manager->GetByteSizeRequirement(ShapeUtil::GetSubshape(
result.Result().on_device_shape(), result_index));
if (!ShapeUtil::IndexIsValid(alias_config.shape(), result_index)) {
return InternalError("result_index is invalid: %s",
result_index.ToString());
}
std::optional<HloInputOutputAliasConfig::Alias> alias =
alias_config.GetAliasedParameter(result_index);
if (alias) {
TF_RET_CHECK(alias->parameter_number < arguments->size());
ExecutionInput& input = (*arguments)[alias->parameter_number];
MaybeOwningDeviceMemory* device_memory =
input.MutableBuffer(alias->parameter_index);
if (auto owning = device_memory->Release()) {
se::DeviceMemoryBase device_memory_base = owning->Release();
*device_memory = device_memory_base;
result_buffer = device_memory_base;
result.AddAliasedIndex(result_index);
} else {
VLOG(2) << "An input was not reused since it is not donated "
<< alias->ToString();
}
}
if (result_buffer.is_null()) {
const Shape& on_device_shape = result.Result().on_device_shape();
const Shape& on_device_subshape =
ShapeUtil::GetSubshape(on_device_shape, result_index);
TF_ASSIGN_OR_RETURN(
auto allocated_buffer,
allocator->Allocate(executor->device_ordinal(), allocation_bytes,
/*retry_on_failure=*/true,
on_device_subshape.layout().memory_space()));
result_buffer = allocated_buffer.Release();
}
TF_RET_CHECK(allocation_bytes == 0 || result_buffer != nullptr);
}
TF_RETURN_IF_ERROR(
transfer_manager->WriteTupleIndexTables(stream, result.Result()));
return std::move(result);
}
} // namespace interpreter
} // namespace xla
| 41.845494
| 80
| 0.679487
|
Nyrio
|
2a9aafba3c5d61dd0f6dbd47296f721c6961ab66
| 1,844
|
cpp
|
C++
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 39
|
2015-01-01T07:59:51.000Z
|
2021-10-01T18:11:46.000Z
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 1
|
2019-04-24T09:56:15.000Z
|
2019-04-24T14:45:46.000Z
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 18
|
2015-01-11T15:10:23.000Z
|
2022-02-24T20:02:10.000Z
|
/*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "InpaintingIterationRecord.h"
InpaintingIterationRecord::InpaintingIterationRecord()
{
}
NamedITKImageCollection& InpaintingIterationRecord::GetImages()
{
return this->Images;
}
// void InpaintingIterationRecord::SetDisplayed(const unsigned int imageId, const bool displayed)
// {
// this->Display[imageId] = displayed;
// }
//
// bool InpaintingIterationRecord::IsDisplayed(const unsigned int imageId) const
// {
// return this->Display[imageId];
// }
void InpaintingIterationRecord::AddImage(const NamedITKImage& namedImage, const bool display)
{
this->Images.push_back(namedImage);
this->Display.push_back(display);
}
// NamedITKImage InpaintingIterationRecord::GetImage(const unsigned int imageId) const
// {
// return this->Images[imageId];
// }
//
// NamedITKImage InpaintingIterationRecord::GetImageByName(const std::string& imageName) const
// {
// return this->Images.FindImageByName(imageName);
// }
//
// unsigned int InpaintingIterationRecord::GetNumberOfImages() const
// {
// return this->Images.size();
// }
| 30.229508
| 97
| 0.677332
|
jingtangliao
|
2a9aeaa398ef199bf8d61594d1cedc358518551e
| 211
|
hpp
|
C++
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 2
|
2022-01-14T06:10:31.000Z
|
2022-02-28T23:30:26.000Z
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 1
|
2022-01-31T07:44:04.000Z
|
2022-01-31T07:44:04.000Z
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 1
|
2021-10-31T01:32:43.000Z
|
2021-10-31T01:32:43.000Z
|
#pragma once
#include "engine/surface.hpp"
namespace devilution {
void InitSpellBook();
void FreeSpellBook();
void CheckSBook();
void DrawSpellBook(const Surface &out);
} // namespace devilution
| 16.230769
| 40
| 0.71564
|
stefanmielke
|
2a9d40e665f2116b536fe4cc3d176f4edcc1ec46
| 413
|
cpp
|
C++
|
Dataset/Leetcode/valid/48/348.cpp
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null |
Dataset/Leetcode/valid/48/348.cpp
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null |
Dataset/Leetcode/valid/48/348.cpp
|
kkcookies99/UAST
|
fff81885aa07901786141a71e5600a08d7cb4868
|
[
"MIT"
] | null | null | null |
class Solution {
public:
void XXX(vector<vector<int>>& matrix) {
int m=matrix.size(),n=matrix[0].size();
for(int i=0;i<m/2;++i)
for(int j=0;j<n;++j)
{
swap(matrix[i][j],matrix[m-i-1][j]);
}
for(int i=0;i<m;++i)
for(int j=i+1;j<n;++j)
{
swap(matrix[i][j],matrix[j][i]);
}
}
};
| 22.944444
| 52
| 0.389831
|
kkcookies99
|
2a9dfbd70b1bbcdbe68b98864c70517cf93dc2e7
| 10,703
|
cpp
|
C++
|
tests/src/library.cpp
|
kstenerud/c-compact-time
|
b128d1298af83c7d37e3d055b7742d668863a26a
|
[
"MIT"
] | 1
|
2019-09-30T16:54:46.000Z
|
2019-09-30T16:54:46.000Z
|
tests/src/library.cpp
|
kstenerud/c-compact-time
|
b128d1298af83c7d37e3d055b7742d668863a26a
|
[
"MIT"
] | null | null | null |
tests/src/library.cpp
|
kstenerud/c-compact-time
|
b128d1298af83c7d37e3d055b7742d668863a26a
|
[
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <compact_time/compact_time.h>
// #define KSLog_LocalMinLevel KSLOG_LEVEL_TRACE
#include <kslog/kslog.h>
TEST(Library, version)
{
const char* expected = "1.0.0";
const char* actual = ct_version();
ASSERT_STREQ(expected, actual);
}
static void fill_date(ct_date* date, int year, int month, int day)
{
memset(date, 0, sizeof(*date));
date->year = year;
date->month = month;
date->day = day;
}
static void fill_time(ct_time* time, int hour, int minute, int second, int nanosecond)
{
memset(time, 0, sizeof(*time));
time->hour = hour;
time->minute = minute;
time->second = second;
time->nanosecond = nanosecond;
}
static void fill_timestamp(ct_timestamp* timestamp, int year, int month, int day, int hour, int minute, int second, int nanosecond)
{
memset(timestamp, 0, sizeof(*timestamp));
fill_date(×tamp->date, year, month, day);
fill_time(×tamp->time, hour, minute, second, nanosecond);
}
static void fill_timezone_utc(ct_timezone* timezone)
{
timezone->type = CT_TZ_ZERO;
}
static void fill_timezone_named(ct_timezone* timezone, const char* name)
{
timezone->type = CT_TZ_STRING;
strcpy(timezone->as_string, name);
}
static void fill_timezone_loc(ct_timezone* timezone, const int latitude, const int longitude)
{
timezone->type = CT_TZ_LATLONG;
timezone->latitude = latitude;
timezone->longitude = longitude;
}
#define ASSERT_TIMEZONE_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ((EXPECTED).type, (ACTUAL).type); \
if((EXPECTED).type == CT_TZ_STRING) { \
ASSERT_STREQ((EXPECTED).as_string, (ACTUAL).as_string); \
} else if((EXPECTED).type == CT_TZ_LATLONG) { \
ASSERT_EQ((EXPECTED).latitude, (ACTUAL).latitude); \
ASSERT_EQ((EXPECTED).longitude, (ACTUAL).longitude); \
}
#define ASSERT_DATE_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ(EXPECTED.year, ACTUAL.year); \
ASSERT_EQ(EXPECTED.month, ACTUAL.month); \
ASSERT_EQ(EXPECTED.day, ACTUAL.day)
#define ASSERT_TIME_EQ(ACTUAL, EXPECTED) \
ASSERT_EQ(EXPECTED.hour, ACTUAL.hour); \
ASSERT_EQ(EXPECTED.minute, ACTUAL.minute); \
ASSERT_EQ(EXPECTED.second, ACTUAL.second); \
ASSERT_EQ(EXPECTED.nanosecond, ACTUAL.nanosecond); \
ASSERT_TIMEZONE_EQ(EXPECTED.timezone, ACTUAL.timezone)
#define ASSERT_DATE_ENCODE_DECODE(EXPECTED_DATE, ACTUAL_DATE, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_date_encoded_size(&EXPECTED_DATE)); \
int bytes_encoded = ct_date_encode(&EXPECTED_DATE, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_date ACTUAL_DATE; \
memset(&ACTUAL_DATE, 0, sizeof(ACTUAL_DATE)); \
int bytes_decoded = ct_date_decode(actual.data(), actual.size(), &ACTUAL_DATE); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_DATE_EQ(ACTUAL_DATE, EXPECTED_DATE)
#define ASSERT_TIME_ENCODE_DECODE(EXPECTED_TIME, ACTUAL_TIME, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_time_encoded_size(&EXPECTED_TIME)); \
int bytes_encoded = ct_time_encode(&EXPECTED_TIME, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_time ACTUAL_TIME; \
memset(&ACTUAL_TIME, 0, sizeof(ACTUAL_TIME)); \
int bytes_decoded = ct_time_decode(actual.data(), actual.size(), &ACTUAL_TIME); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_TIME_EQ(ACTUAL_TIME, EXPECTED_TIME)
#define ASSERT_TIMESTAMP_ENCODE_DECODE(EXPECTED_TIMESTAMP, ACTUAL_TIMESTAMP, ...) \
std::vector<uint8_t> expected = __VA_ARGS__; \
std::vector<uint8_t> actual(ct_timestamp_encoded_size(&EXPECTED_TIMESTAMP)); \
int bytes_encoded = ct_timestamp_encode(&EXPECTED_TIMESTAMP, actual.data(), actual.size()); \
ASSERT_EQ(expected, actual); \
ASSERT_EQ(bytes_encoded, expected.size()); \
ct_timestamp ACTUAL_TIMESTAMP; \
memset(&ACTUAL_TIMESTAMP, 0, sizeof(ACTUAL_TIMESTAMP)); \
int bytes_decoded = ct_timestamp_decode(actual.data(), actual.size(), &ACTUAL_TIMESTAMP); \
ASSERT_EQ(bytes_decoded, expected.size()); \
ASSERT_DATE_EQ(ACTUAL_TIMESTAMP.date, EXPECTED_TIMESTAMP.date); \
ASSERT_TIME_EQ(ACTUAL_TIMESTAMP.time, EXPECTED_TIMESTAMP.time)
#define TEST_DATE(SIGN, YEAR, MONTH, DAY, ...) \
TEST(CDate, date_utc_ ## YEAR ## _ ## MONTH ## _ ## DAY) \
{ \
ct_date date; \
fill_date(&date, SIGN YEAR, MONTH, DAY); \
ASSERT_DATE_ENCODE_DECODE(date, actual_date, __VA_ARGS__); \
}
#define TEST_TIME_TZ_UTC(HOUR, MINUTE, SECOND, NANOSECOND, ...) \
TEST(CDate, time_utc_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_utc(&time.timezone); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
}
#define TEST_TIME_TZ_NAMED(HOUR, MINUTE, SECOND, NANOSECOND, TZ, ...) \
TEST(CDate, time_named_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_named(&time.timezone, TZ); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
ASSERT_STREQ(actual_time.timezone.as_string, TZ); \
}
#define TEST_TIME_TZ_LOC(HOUR, MINUTE, SECOND, NANOSECOND, LAT, LONG, ...) \
TEST(CDate, time_loc_ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_time time; \
fill_time(&time, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_loc(&time.timezone, LAT, LONG); \
ASSERT_TIME_ENCODE_DECODE(time, actual_time, __VA_ARGS__); \
ASSERT_EQ(time.timezone.latitude, LAT); \
ASSERT_EQ(time.timezone.longitude, LONG); \
}
#define TEST_TIMESTAMP_TZ_UTC(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, ...) \
TEST(CDate, timestamp_utc_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_utc(×tamp.time.timezone); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
}
#define TEST_TIMESTAMP_TZ_NAMED(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, TZ, ...) \
TEST(CDate, timestamp_named_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_named(×tamp.time.timezone, TZ); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
ASSERT_STREQ(actual_timestamp.time.timezone.as_string, TZ); \
}
#define TEST_TIMESTAMP_TZ_LOC(SIGN, YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND, LAT, LONG, ...) \
TEST(CDate, timestamp_loc_ ## YEAR ## _ ## MONTH ## _ ## DAY ## _ ## HOUR ## _ ## MINUTE ## _ ## SECOND ## _ ## NANOSECOND) \
{ \
ct_timestamp timestamp; \
fill_timestamp(×tamp, SIGN YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NANOSECOND); \
fill_timezone_loc(×tamp.time.timezone, LAT, LONG); \
ASSERT_TIMESTAMP_ENCODE_DECODE(timestamp, actual_timestamp, __VA_ARGS__); \
ASSERT_EQ(timestamp.time.timezone.latitude, LAT); \
ASSERT_EQ(timestamp.time.timezone.longitude, LONG); \
}
// ----
// Date
// ----
TEST_DATE( , 2000,1,1, {0x21, 0x00, 0x00})
TEST_DATE(-, 2000,12,21, {0x95, 0x7d, 0x3f})
// ----
// Time
// ----
TEST_TIME_TZ_UTC(8, 41, 05, 999999999, {0x47, 0x69, 0xf1, 0x9f, 0xac, 0xb9, 0x03})
TEST_TIME_TZ_UTC(14, 18, 30, 43000000, {0x73, 0x92, 0xb7, 0x02})
TEST_TIME_TZ_UTC(23, 6, 55, 8000, {0xbd, 0xc6, 0x8d, 0x00, 0x00})
TEST_TIME_TZ_NAMED(10, 10, 10, 0, "S/Tokyo", {0x50, 0x8a, 0x02, 0x0e, 'S','/','T','o','k','y','o'})
TEST_TIME_TZ_LOC(7, 45, 0, 1000000, -3876, 2730, {0x3a, 0x2d, 0x10, 0x00, 0xb9, 0xe1, 0xaa, 0x0a})
TEST_TIME_TZ_LOC(7, 45, 0, 2000000, -9000, -18000, {0x3a, 0x2d, 0x20, 0x00, 0xb1, 0xb9, 0xb0, 0xb9})
TEST_TIME_TZ_LOC(7, 45, 0, 3000000, 9000, 18000, {0x3a, 0x2d, 0x30, 0x00, 0x51, 0x46, 0x50, 0x46})
// ---------
// Timestamp
// ---------
TEST_TIMESTAMP_TZ_NAMED( , 2000,1,1,0,0,0,0, "Europe/Berlin", {0x00, 0x00, 0x08, 0x01, 00, 0x1a, 'E','u','r','o','p','e','/','B','e','r','l','i','n'})
TEST_TIMESTAMP_TZ_NAMED( , 2020,8,30,15,33,14,19577323, "S/Singapore", {0x3b, 0xe1, 0xf3, 0xb8, 0x9e, 0xab, 0x12, 0x00, 0x50, 0x16, 'S', '/', 'S', 'i', 'n', 'g', 'a', 'p', 'o', 'r', 'e'})
TEST_TIMESTAMP_TZ_LOC( , 2000,1,1,1,0,0,0,100,200, {0x00, 0x40, 0x08, 0x01, 0x00, 0xc9, 0x00, 0xc8, 0x00})
TEST_TIMESTAMP_TZ_LOC( , 2000,1,1,2,0,0,0,-100,-200, {0x00, 0x80, 0x08, 0x01, 0x00, 0x39, 0xff, 0x38, 0xff})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,1,0,0, 0, {0x00, 0x40, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,1,0, 0, {0x00, 0x01, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,1, 0, {0x04, 0x00, 0x08, 0x01, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 1000000, {0x01, 0x00, 0x08, 0x11, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0,999000000, {0x01, 0x00, 0x08, 0x71, 0x3e, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 999000, {0x02, 0x00, 0x08, 0x71, 0x3e, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2000,1,1,0,0,0, 999, {0x03, 0x00, 0x08, 0x71, 0x3e, 0x00, 0x00, 0x00, 0x01})
TEST_TIMESTAMP_TZ_UTC( , 2009,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x25})
TEST_TIMESTAMP_TZ_UTC( , 3009,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0x01, 0x9f, 0x45})
TEST_TIMESTAMP_TZ_UTC(-, 50000,1,1,0,0,0, 0, {0x00, 0x00, 0x08, 0xc1, 0xd8, 0x7f})
// -------------
// Spec Examples
// -------------
// June 24, 2019, 17:53:04.180
TEST_TIMESTAMP_TZ_UTC(, 2019,6,24,17,53,4,180000000, {0x11, 0x75, 0xc4, 0x46, 0x0b, 0x4d})
// January 7, 1998, 08:19:20, Europe/Rome
TEST_TIMESTAMP_TZ_NAMED(, 1998,1,7,8,19,20,0, "E/Rome", {0x50, 0x13, 0x3a, 0x01, 0x06, 0x0c, 'E', '/', 'R', 'o', 'm', 'e'})
// August 31, 3190, 00:54:47.394129, location 59.94, 10.71
TEST_TIMESTAMP_TZ_LOC(, 3190,8,31,0,54,47,394129000, 5994, 1071, {0xbe, 0x36, 0xf8, 0x18, 0x39, 0x60, 0xa5, 0x18, 0xd5, 0x2e, 0x2f, 0x04})
// ------------
// CBE Examples
// ------------
TEST_DATE( , 2051,10,22, {0x56, 0x01, 0x66})
TEST_TIME_TZ_NAMED(13, 15, 59, 529435422, "E/Berlin", {0x6e, 0xcf, 0xee, 0xb1, 0xe8, 0xf8, 0x01, 0x10, 'E', '/', 'B', 'e', 'r', 'l', 'i', 'n'})
TEST_TIMESTAMP_TZ_LOC( , 1985, 10, 26, 1, 22, 16, 0, 3399, -11793, {0x40, 0x56, 0xd0, 0x0a, 0x3a, 0x8f, 0x1a, 0xef, 0xd1})
| 42.472222
| 187
| 0.669812
|
kstenerud
|
2aa173d69c8bd5fad30c1658343077bad18134fb
| 5,215
|
cpp
|
C++
|
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
/* dtkWidgetsTagCloudView.cpp ---
*
* Author: Julien Wintz
* Created: Mon Apr 15 14:39:34 2013 (+0200)
* Version:
* Last-Updated: Mon Apr 15 14:44:56 2013 (+0200)
* By: Julien Wintz
* Update #: 7
*/
/* Change Log:
*
*/
#include "dtkWidgetsTagCloudDesc.h"
#include "dtkWidgetsTagCloudList.h"
#include "dtkWidgetsTagCloudView.h"
class dtkWidgetsTagCloudViewPrivate
{
public:
QWidget *parent;
public:
QEasingCurve::Type type;
public:
bool vertical;
bool wrap;
bool active;
public:
int speed;
int now;
int next;
public:
QPoint pnow;
public:
dtkWidgetsTagCloudList *list;
dtkWidgetsTagCloudDesc *desc;
};
dtkWidgetsTagCloudView::dtkWidgetsTagCloudView(QWidget *parent) : QStackedWidget(parent), d(new dtkWidgetsTagCloudViewPrivate)
{
d->list = new dtkWidgetsTagCloudList(this);
d->desc = new dtkWidgetsTagCloudDesc(this);
if (parent != 0)
d->parent = parent;
else
d->parent = this;
d->vertical = false;
d->speed = 500;
d->type = QEasingCurve::OutBack;
d->now = 0;
d->next = 0;
d->wrap = false;
d->pnow = QPoint(0,0);
d->active = false;
this->addWidget(d->list);
this->addWidget(d->desc);
connect(d->list, SIGNAL(itemClicked(const QString&)), this, SLOT(onItemClicked(const QString&)));
connect(d->desc, SIGNAL(back()), this, SLOT(slideInPrev()));
}
dtkWidgetsTagCloudView::~dtkWidgetsTagCloudView(void)
{
delete d;
d = NULL;
}
dtkWidgetsTagCloudList *dtkWidgetsTagCloudView::list(void)
{
return d->list;
}
dtkWidgetsTagCloudDesc *dtkWidgetsTagCloudView::desc(void)
{
return d->desc;
}
void dtkWidgetsTagCloudView::setDark(void)
{
d->list->setDark();
}
void dtkWidgetsTagCloudView::onItemClicked(const QString& description)
{
d->desc->setDescription(description);
this->slideInNext();
}
void dtkWidgetsTagCloudView::setVerticalMode(bool vertical)
{
d->vertical = vertical;
}
void dtkWidgetsTagCloudView::setSpeed(int speed)
{
d->speed = speed;
}
void dtkWidgetsTagCloudView::setAnimation(QEasingCurve::Type type)
{
d->type = type;
}
void dtkWidgetsTagCloudView::setWrap(bool wrap)
{
d->wrap = wrap;
}
void dtkWidgetsTagCloudView::slideInNext(void)
{
int now = currentIndex();
if (d->wrap||(now<count()-1))
slideInIdx(now+1);
}
void dtkWidgetsTagCloudView::slideInPrev(void)
{
int now = currentIndex();
if (d->wrap||(now>0))
slideInIdx(now-1);
}
void dtkWidgetsTagCloudView::slideInIdx(int idx, Direction direction)
{
if (idx>count()-1) {
direction = d->vertical ? Top2Bottom : Right2Left;
idx = (idx)%count();
} else if (idx<0) {
direction = d->vertical ? Bottom2Top: Left2Right;
idx = (idx+count())%count();
}
slideInWgt(widget ( idx ),direction);
}
void dtkWidgetsTagCloudView::slideInWgt(QWidget *newwidget, Direction direction)
{
if (d->active)
return;
else
d->active = true;
Direction directionhint;
int now = currentIndex();
int next = indexOf(newwidget);
if (now==next) {
d->active = false;
return;
}
else if (now<next){
directionhint = d->vertical ? Top2Bottom : Right2Left;
}
else {
directionhint = d->vertical ? Bottom2Top : Left2Right;
}
if (direction == Automatic) {
direction = directionhint;
}
int offsetx = frameRect().width();
int offsety = frameRect().height();
widget(next)->setGeometry ( 0, 0, offsetx, offsety );
if (direction==Bottom2Top) {
offsetx = 0;
offsety = -offsety;
}
else if (direction==Top2Bottom) {
offsetx = 0;
}
else if (direction==Right2Left) {
offsetx = -offsetx;
offsety = 0;
}
else if (direction==Left2Right) {
offsety = 0;
}
QPoint pnext = widget(next)->pos();
QPoint pnow = widget(now)->pos();
d->pnow = pnow;
widget(next)->move(pnext.x()-offsetx,pnext.y()-offsety);
widget(next)->show();
widget(next)->raise();
QPropertyAnimation *animnow = new QPropertyAnimation(widget(now), "pos");
animnow->setDuration(d->speed);
animnow->setEasingCurve(d->type);
animnow->setStartValue(QPoint(pnow.x(), pnow.y()));
animnow->setEndValue(QPoint(offsetx+pnow.x(), offsety+pnow.y()));
QPropertyAnimation *animnext = new QPropertyAnimation(widget(next), "pos");
animnext->setDuration(d->speed);
animnext->setEasingCurve(d->type);
animnext->setStartValue(QPoint(-offsetx+pnext.x(), offsety+pnext.y()));
animnext->setEndValue(QPoint(pnext.x(), pnext.y()));
QParallelAnimationGroup *animgroup = new QParallelAnimationGroup;
animgroup->addAnimation(animnow);
animgroup->addAnimation(animnext);
QObject::connect(animgroup, SIGNAL(finished()),this,SLOT(animationDoneSlot()));
d->next = next;
d->now = now;
d->active = true;
animgroup->start();
}
void dtkWidgetsTagCloudView::animationDoneSlot(void)
{
setCurrentIndex(d->next);
widget(d->now)->hide();
widget(d->now)->move(d->pnow);
d->active = false;
emit animationFinished();
}
| 22.286325
| 126
| 0.635858
|
eti-nne
|
2aa2010afd6be7798a9d1041d28c63f6924839fd
| 1,777
|
hpp
|
C++
|
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2019-2020 Xenios SEZC
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#define ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#include <stdint.h>
#include <vector>
#include "veriblock/entities/atv.hpp"
#include "veriblock/entities/vtb.hpp"
#include "veriblock/serde.hpp"
#include "veriblock/slice.hpp"
namespace altintegration {
struct PopData {
int32_t version{};
std::vector<VbkBlock> vbk_context;
bool hasAtv{false};
ATV atv{};
std::vector<VTB> vtbs{};
/**
* Read VBK data from the stream and convert it to PopData
* @param stream data stream to read from
* @return PopData
*/
static PopData fromVbkEncoding(ReadStream& stream);
/**
* Read VBK data from the raw byte representation and convert it to PopData
* @param string data bytes to read from
* @return PopData
*/
static PopData fromVbkEncoding(Slice<const uint8_t> bytes);
/**
* Convert PopData to data stream using Vbk byte format
* @param stream data stream to write into
*/
void toVbkEncoding(WriteStream& stream) const;
/**
* Convert PopData to raw bytes data using Vbk byte format
* @return bytes data
*/
std::vector<uint8_t> toVbkEncoding() const;
/**
* Return true if contains endorsement data
* @return true if contains endorsement data
*/
bool containsEndorsements() const;
friend bool operator==(const PopData& a, const PopData& b) {
// clang-format off
return a.toVbkEncoding() == b.toVbkEncoding();
// clang-format on
}
};
} // namespace altintegration
#endif
| 25.385714
| 77
| 0.720878
|
overcookedpanda
|
2aa48b48ffb0b7acd42535b935e6941388b394ba
| 700
|
cpp
|
C++
|
cpp/utility_declval.cpp
|
rpuntaie/c-examples
|
385b3c792e5b39f81a187870100ed6401520a404
|
[
"MIT"
] | null | null | null |
cpp/utility_declval.cpp
|
rpuntaie/c-examples
|
385b3c792e5b39f81a187870100ed6401520a404
|
[
"MIT"
] | null | null | null |
cpp/utility_declval.cpp
|
rpuntaie/c-examples
|
385b3c792e5b39f81a187870100ed6401520a404
|
[
"MIT"
] | null | null | null |
/*
g++ --std=c++20 -pthread -o ../_build/cpp/utility_declval.exe ./cpp/utility_declval.cpp && (cd ../_build/cpp/;./utility_declval.exe)
https://en.cppreference.com/w/cpp/utility/declval
*/
#include <utility>
#include <iostream>
struct Default { int foo() const { return 1; } };
struct NonDefault
{
NonDefault() = delete;
int foo() const { return 1; }
};
int main()
{
decltype(Default().foo()) n1 = 1; // type of n1 is int
// decltype(NonDefault().foo()) n2 = n1; // error: no default constructor
decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int
std::cout << "n1 = " << n1 << '\n'
<< "n2 = " << n2 << '\n';
}
| 31.818182
| 132
| 0.568571
|
rpuntaie
|
2aa9c6bd380b1487f674bc761d7efc628e018703
| 7,631
|
cpp
|
C++
|
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
#include <Instance.hpp>
#include <PhysicalDevice.hpp>
#include <Device.hpp>
#include <Queue/Queue.hpp>
#include <Queue/Fence.hpp>
#include <Queue/Semaphore.hpp>
#include <Command/Pool.hpp>
#include <Command/Buffer.hpp>
#include <Memory.hpp>
#include <Buffer.hpp>
#include <Common.hpp>
#include <future>
#include <iostream>
#define FENCE_VERSION
#define CHUNK_SIZE 256
#define SENTENCE0 std::string("Hello World !")
#define SENTENCE1 std::string("All your base are belong to us")
#define SWAP_NBR 1
using namespace OCRA;
#ifdef FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
auto fence = Queue::Fence::Create(a_Device);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < 1; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo, fence] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo }, fence);
});
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
}
//test for function time itself
{
auto timer = Timer();
int waitNbr = 100000;
for (auto i = 0; i < waitNbr; ++i)
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
std::cout << "Already signaled Fence mean wait time : " << timer.Elapsed().count() / double(waitNbr) << " nanoseconds\n";
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#else //FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
Queue::Semaphore::Info semaphoreInfo;
semaphoreInfo.type = Queue::Semaphore::Type::Timeline;
semaphoreInfo.initialValue = 0;
Queue::Semaphore::Handle semaphore = Queue::Semaphore::Create(a_Device, semaphoreInfo);
Queue::TimelineSemaphoreSubmitInfo timelineValues;
timelineValues.waitSemaphoreValues.push_back(1);
timelineValues.signalSemaphoreValues.push_back(2);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < SWAP_NBR; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
submitInfo.waitSemaphores.push_back(semaphore);
submitInfo.signalSemaphores.push_back(semaphore);
submitInfo.timelineSemaphoreValues = timelineValues;
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo });
});
Queue::Semaphore::Signal(a_Device, semaphore, 1);
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Semaphore::Wait(a_Device, { semaphore }, { 2 }, std::chrono::nanoseconds(15000000));
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#endif
static inline void RecordSwapCommandBuffer(
const Command::Buffer::Handle& a_CommandBuffer,
const Buffer::Handle& a_Buffer0,
const Buffer::Handle& a_Buffer1,
const Buffer::Handle& a_BufferT)
{
Command::Buffer::BeginInfo bufferbeginInfo;
bufferbeginInfo.flags = Command::Buffer::UsageFlagBits::None;
Command::Buffer::Begin(a_CommandBuffer, bufferbeginInfo);
{
Command::BufferCopyRegion copyRegions;
copyRegions.size = CHUNK_SIZE;
Command::CopyBuffer(a_CommandBuffer, a_Buffer0, a_BufferT, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_Buffer1, a_Buffer0, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_BufferT, a_Buffer1, { copyRegions });
}
Command::Buffer::End(a_CommandBuffer);
}
int main()
{
const auto instance = CreateInstance("Test_CommandBuffer");
const auto physicalDevice = Instance::EnumeratePhysicalDevices(instance).front();
const auto device = CreateDevice(physicalDevice);
const auto queueFamily = FindQueueFamily(physicalDevice, PhysicalDevice::QueueFlagsBits::Transfer);
const auto queue = Device::GetQueue(device, queueFamily, 0); //Get first available queue
const auto memory = AllocateMemory(physicalDevice, device, CHUNK_SIZE * 3, PhysicalDevice::MemoryPropertyFlagBits::HostVisible | PhysicalDevice::MemoryPropertyFlagBits::HostCached);
const auto commandPool = CreateCommandPool(device, queueFamily);
const auto commandBuffer = CreateCommandBuffer(device, commandPool, Command::Pool::AllocateInfo::Level::Primary);
//create test buffers
Buffer::Info bufferInfo;
bufferInfo.size = CHUNK_SIZE;
bufferInfo.usage = Buffer::UsageFlagBits::TransferDst | Buffer::UsageFlagBits::TransferSrc;
const auto buffer0 = Buffer::Create(device, bufferInfo);
const auto buffer1 = Buffer::Create(device, bufferInfo);
const auto bufferT = Buffer::Create(device, bufferInfo);
Buffer::BindMemory(device, buffer0, memory, CHUNK_SIZE * 0);
Buffer::BindMemory(device, buffer1, memory, CHUNK_SIZE * 1);
Buffer::BindMemory(device, bufferT, memory, CHUNK_SIZE * 2);
//write some value to the buffer0
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE0.c_str(), SENTENCE0.size());
Memory::Unmap(device, memory);
}
//write some value to the buffer1
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE1.c_str(), SENTENCE1.size());
Memory::Unmap(device, memory);
}
RecordSwapCommandBuffer(commandBuffer, buffer0, buffer1, bufferT);
SubmitCommandBuffer(device, queue, commandBuffer);
std::cout << "========== Sentences to swap ==========\n";
std::cout << " Sentence 0 : " << SENTENCE0 << "\n";
std::cout << " Sentence 1 : " << SENTENCE1 << "\n";
std::cout << "=======================================\n";
std::cout << "\n";
std::cout << "===== Check if sentences were swapped =====\n";
int success = 0;
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
std::string buffer0String = (char*)Memory::Map(device, mappedRange);
success += buffer0String == SENTENCE1 ? 0 : 1;
std::cout << " Buffer 0 value : " << buffer0String << "\n";
Memory::Unmap(device, memory);
}
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
std::string buffer1String = (char*)Memory::Map(device, mappedRange);
success += buffer1String == SENTENCE0 ? 0 : 1;
std::cout << " Buffer 1 value : " << buffer1String << "\n";
Memory::Unmap(device, memory);
}
std::cout << " " << (success == 0 ? "***** Great success ! *****" : "XXXXX Failure will not be tolerated. XXXXX") << "\n";
std::cout << "===========================================\n";
return success;
}
| 42.394444
| 185
| 0.653781
|
Gpinchon
|
2aada408721b2630a046925c15f9e820d8849fe7
| 2,813
|
hpp
|
C++
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 6
|
2019-08-15T09:48:55.000Z
|
2021-07-25T14:40:59.000Z
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 43
|
2019-12-25T14:54:52.000Z
|
2022-02-24T17:22:48.000Z
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 2
|
2020-05-06T20:14:44.000Z
|
2020-06-02T21:21:10.000Z
|
/*
The MIT License (MIT)
Copyright (c) 2019 Cdec
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <type_traits>
#include <memory>
#include <boost/tti/has_member_function.hpp>
namespace minimal_serializer {
class serializer;
// Remove const, volatile and reference
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
BOOST_TTI_HAS_MEMBER_FUNCTION(on_serialize)
template <typename T>
constexpr bool has_member_on_serialize_v = has_member_function_on_serialize<T, void, boost::mpl::vector<serializer&>
, boost::function_types::non_cv>::value;
struct has_global_on_serialize_impl {
template <class T>
static auto check(T&& x) -> decltype(on_serialize(std::declval<T&>(), std::declval<serializer&>()), std::true_type());
template <class T>
static std::false_type check(...);
};
template <class T>
constexpr bool has_global_on_serialize_v
= decltype(has_global_on_serialize_impl::check<T>(std::declval<T>()))::value;
template <class T>
constexpr bool is_serializable_v = has_global_on_serialize_v<T> && std::is_trivial_v<T>;
struct is_fixed_array_container_impl {
template <class T>
static auto check(T&& x) -> decltype(x.operator[](std::declval<size_t>()), x.max_size(), std::true_type{});
template <class T>
static auto check(...)->std::false_type;
};
template <class T>
struct is_fixed_array_container final : decltype(is_fixed_array_container_impl::check<T>(std::declval<T>())) {};
template <class T>
constexpr bool is_fixed_array_container_v = is_fixed_array_container<T>::value;
template <typename T>
struct is_shared_ptr : std::false_type {};
template <typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T>
constexpr bool is_shared_ptr_v = is_shared_ptr<T>::value;
}
| 40.768116
| 460
| 0.766086
|
InstytutXR
|
2aaecd0f7cb573a49029330dd55990710e46610b
| 1,559
|
cpp
|
C++
|
src/cfiddle/resources/libcfiddle/cfiddle.cpp
|
NVSL/fiddle
|
5edffa92caa0894057a449ad5accb23af748e657
|
[
"MIT"
] | 2
|
2022-01-22T06:12:52.000Z
|
2022-01-24T07:29:44.000Z
|
src/cfiddle/resources/libcfiddle/cfiddle.cpp
|
NVSL/cfiddle
|
5edffa92caa0894057a449ad5accb23af748e657
|
[
"MIT"
] | null | null | null |
src/cfiddle/resources/libcfiddle/cfiddle.cpp
|
NVSL/cfiddle
|
5edffa92caa0894057a449ad5accb23af748e657
|
[
"MIT"
] | null | null | null |
#include"cfiddle.hpp"
#include<sstream>
#include<string>
#include<fstream>
#include"DataSet.hpp"
#include"PerfCounter.hpp"
#include"walltime.h"
double start_time = 0.0;
DataSet * get_dataset();
extern "C"
void write_stats(char * filename) {
//std::cerr << "Writing to " << filename << "\n";
std::ofstream out(filename);
get_dataset()->write_csv(out);
out.close();
}
extern "C"
void clear_stats() {
get_dataset()->clear();
}
extern "C"
void clear_perf_counters() {
get_perf_counter()->clear();
}
extern "C"
void add_perf_counter(char * perf_counter_spec) {
get_perf_counter()->add_counter(perf_counter_spec);
}
extern "C"
bool are_perf_counters_available() {
return get_perf_counter()->performance_counters_enabled();
}
extern "C"
void start_measurement(const char *tag)
{
get_dataset()->start_new_row();
if (tag) {
get_dataset()->set("tag", tag);
}
start_time = wall_time();
get_perf_counter()->start();
}
extern "C"
void end_measurement()
{
double end_time = wall_time();
auto perf_counter = get_perf_counter();
auto dataset = get_dataset();
perf_counter->stop();
dataset->set("ET", end_time - start_time);
for(auto & v: perf_counter->get_counters()) {
dataset->set(v.name, v.value);
}
}
extern "C"
void restart_measurement(const char *tag)
{
end_measurement();
start_measurement(tag);
}
DataSet *get_dataset() {
static DataSet *ds = new DataSet();
return ds;
}
PerfCounter *get_perf_counter() {
static PerfCounter *pc = new PerfCounter();
return pc;
}
void __attribute__ ((constructor)) my_init(void) {
}
| 17.131868
| 59
| 0.702373
|
NVSL
|
2aaf1393cc24731b2409395aefa6e0433686823d
| 15,716
|
cpp
|
C++
|
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | 4
|
2017-05-04T15:50:48.000Z
|
2020-07-30T03:52:07.000Z
|
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | null | null | null |
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | 2
|
2017-01-11T09:53:26.000Z
|
2020-07-30T03:52:09.000Z
|
/**********************************************************************
* CC0 License
**********************************************************************
* MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid.
* Written in 2015 by Samantha J.Zambo(samantha.zambo@gmail.com) while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory.
* To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty.
* You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
**********************************************************************/
#include "Bathy_Grid.h"
#include "GradientGrid.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <math.h>
#include <list>
#include <vector>
#include "../grid.h"
#include "pointList.h"
#include "sHullDelaunay.h"
void Bathy_Grid::clear()
{
if(ptl != NULL)
{
delete ptl;
ptl = NULL;
}
if(tin != NULL)
{
delete tin;
tin = NULL;
}
size_t sz = interpGrids.size();
for(size_t i = 0; i < sz; ++i){
delete interpGrids[i];
interpGrids[i] = NULL;
}
interpGrids.clear();
ensemble_X.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Y.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Z.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_H.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_V.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U2.clear();
ensemble_U3.clear();
ensemble_U4.clear();
ensemble_U5.clear();
}
void InterpGrid::clear()
{
if(ptlSurface != NULL)
{
delete ptlSurface;
ptlSurface = NULL;
}
if(grads != NULL)
{
delete grads;
grads = NULL;
}
triangles.clear();
e.clear();
e2.clear();
e3.clear();
e4.clear();
e5.clear();
z.clear();
s.clear();
//For Raster/Bag Interpolation SJZ
z0.clear();
e0.clear();
zK.clear();
eK.clear();
nei.clear();
rei.clear();
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit/*, *z0Init, *e0Init, *zKInit, *eKInit*/);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit, vector<double> *neiInit, vector<double> *reiInit, vector<double> *z0Init, vector<double> *e0Init, vector<double> *zKInit, vector<double> *eKInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit, *neiInit, *reiInit, *z0Init, *e0Init, *zKInit, *eKInit);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
//void InterpGrid::estimateRaster(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// z.reserve(pVec.size());
// //s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// z.push_back(pVec[i].z);
// //s.push_back(pVec[i].s);
// }
// }
//}
void Bathy_Grid::Construct_Tin(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *hInit, vector<double> *vInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectors(*xInit, *yInit, *zInit, *hInit, *vInit);
tin = new SHullDelaunay();
//std::cout << "Initializing triangle for error computation" << std::endl;
tin->insert(*ptl);
//std::cout << "Done initializing" << std::endl;
}
void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string depthInterpMethod, string errorInterpMethod, string extrapMethod)
{
ptlSurface = new PointList();
ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
grads = new GradientGrid();
//triangles = vector<Triangle>();
triangles.reserve(ptlSurface->size());
//Compute Gradients before-hand if depths are known.
//This catches if we pre-splined.
if(ptlSurface->getAvgZ() != 0.00)
(*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
//Compute Depths, Gradients, and uncertainties
this->scaleFactor = sH;
this->alpha = alpha;
this->deltaMin = deltaMin;
vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, depthInterpMethod, errorInterpMethod, extrapMethod));
e.reserve(pVec.size());
e2.reserve(pVec.size());
e3.reserve(pVec.size());
e4.reserve(pVec.size());
e5.reserve(pVec.size());
z.reserve(pVec.size());
s.reserve(pVec.size());
nei.reserve(pVec.size());
rei.reserve(pVec.size());
z0.reserve(pVec.size());
e0.reserve(pVec.size());
eK.reserve(pVec.size());
eK.reserve(pVec.size());
for (int i = 0; i < (int) pVec.size(); i++)
{
e.push_back(pVec[i].u);
e2.push_back(pVec[i].u2);
e3.push_back(pVec[i].u3);
e4.push_back(pVec[i].u4);
e5.push_back(pVec[i].u5);
z.push_back(pVec[i].z);
s.push_back(pVec[i].s);
// e.push_back(pVec[i].e);
nei.push_back(pVec[i].nei);
rei.push_back(pVec[i].rei);
z0.push_back(pVec[i].z0);
e0.push_back(pVec[i].e0);
zK.push_back(pVec[i].zK);
eK.push_back(pVec[i].eK);
}
}
//void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf,vector<double> *eSurf,vector<double> *hSurf,vector<double> *vSurf, vector<double> *nmseiSurf,vector<double> *reiSurf,const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// e2.reserve(pVec.size());
// e3.reserve(pVec.size());
// e4.reserve(pVec.size());
// e5.reserve(pVec.size());
// z.reserve(pVec.size());
// s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// e2.push_back(pVec[i].u2);
// e3.push_back(pVec[i].u3);
// e4.push_back(pVec[i].u4);
// e5.push_back(pVec[i].u5);
// z.push_back(pVec[i].z);
// s.push_back(pVec[i].s);
// }
// }
//}
bool Bathy_Grid::ensemble()
{
//This assumes that the correct grid is MBZ
//and the extra leading rows in GMT need to
//be ignored for calculations. These rows
//are in the beginning and provide extra lats for 1 extra lon.
//**This is believed to be fixed;verify before removing! SJZ 12/28/15.
int i, k, j, diff = 0;
double temp = 0;//,n,h;
InterpGrid *kInd;
int cnt = (const int)interpGrids.size();//3;// {MBZ,GMT,ALG} //
double sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0;
vector<int> row, js, jsInit;
vector<int> xcols, yrows;
row.reserve(cnt);
xcols.reserve(cnt); //# rows (x) in each grid
yrows.reserve(cnt); //#cols (y) in each grid
js.reserve(cnt);
jsInit.reserve(cnt); //last index pos at in the set of uniq. new starting index
vector<InterpGrid*>::iterator it = interpGrids.begin();
vector<InterpGrid*>::iterator kIt;
k = (const int)(*it)->e.size();
vector<double> sortGrid1;
vector<double> sortGrid2;
vector<double> sortGrid3;
//find the max grid in order to know the number of extra rows to skip in GMT beginning
for(it = interpGrids.begin()++; it != interpGrids.end(); it++)
{
j = (const int)(*it)->e.size();
if(j < k)
{
k = j;
diff = k - j;
kInd = *&*it;
kIt = it;
}
//xcols and yrows are indices starting at 0. Add +1 to get dimensions.
xcols.push_back((const int)(((*it)->ptlSurface->getPositions().back().x
- (*it)->ptlSurface->getPositions().front().x)/(*it)->deltaMin)+1);
yrows.push_back((const int)(abs(((*it)->ptlSurface->getPositions().back().y
- (*it)->ptlSurface->getPositions().front().y)/(*it)->deltaMin))+1);
js.push_back((const int)(*it)->e.size()-1);
jsInit.push_back((const int)(*it)->e.size()-1);//beginning row index
}
vector<Point> mbzItXY;
vector<Point> algItXY;
vector<Point> gmtItXY;
int mbzflag = 0;
int masterGrid = 0;;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
if(!mbzflag)
masterGrid = 1; //because there is only GMT then ALG
algItXY = (*it)->ptlSurface->getPositions();
break;
case GMT:
gmtItXY = (*it)->ptlSurface->getPositions();
break;//sorted by y min to max
case MBZ:
mbzflag = 1;
masterGrid = MBZ; //should be 0
mbzItXY = (*it)->ptlSurface->getPositions();
break;
}
}
it = interpGrids.begin();
ensemble_H.reserve(k);
ensemble_V.reserve(k);
ensemble_U.reserve(k);
ensemble_U2.reserve(k);
ensemble_U3.reserve(k);
ensemble_U4.reserve(k);
ensemble_U5.reserve(k);
vector<int> js2;
int j2;
js2.reserve(cnt);
int counter = 0;
int counter1 = 0, counter2 = 0;
int counter3 = 0, counter4 = 0;
js[0] = 0; //last visited index
jsInit[0] = 0; //index at beginning of current row visited
js2.assign(js.begin(),js.end());
//i = MBZ, k = GMT, j = same x,y loc in both
for(i =0; i < k; i++)
{
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
//ALGSpline j should be the same x,y as MBZ
//counter = 2;
j = xcols[counter]*(counter3)+counter4;
js[counter] = j;
counter3++;
if(counter3==abs(yrows[masterGrid]))
{
counter3=0;
counter4++;
}
if(counter4==xcols[masterGrid])
counter4=0;
break; //sorted by y max to min
case GMT:
//GMT j should be the same x,y as MBZ
//counter = 1;
j = xcols[counter]*(abs(yrows[counter])-counter1)-(xcols[counter]-counter2);
js[counter] = j;
counter1++;
if(counter1==abs(yrows[masterGrid]))
{
counter1=0;
counter2++;
}
if(counter2==xcols[masterGrid])
counter2=0;
break;//sorted by y min to max
case MBZ:
//j index is always i since MBZ is assumed to be correct.
//counter = 0;
j = i;
js[counter] = j;
break;//sorted by x min to max
}
if(mbzflag)
{
if(counter==ALGSpline){//2
if(! (mbzItXY[js[masterGrid]].x == algItXY[js[ALGSpline]].x && mbzItXY[js[masterGrid]].y == algItXY[js[ALGSpline]].y))
{
std::cout<< "Error: ALG and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
if(counter==GMT){//1
if(! (mbzItXY[js[masterGrid]].x == gmtItXY[js[GMT]].x && mbzItXY[js[masterGrid]].y == gmtItXY[js[GMT]].y))
{
std::cout<< "Error: GMT and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
}
else
{
if(counter==masterGrid){
if(! (algItXY[js[masterGrid]].x == gmtItXY[js[counter-1]].x && algItXY[js[masterGrid]].y == gmtItXY[js[counter-1]].y))
{
std::cout<< "Error: ALG and GMT X, Y locations do not align!" << std::endl;
return false;
}
}
}
sigma += (*it)->e[j];
sigma2 += (*it)->e2[j];
sigma3 += (*it)->e3[j];
sigma4 += (*it)->e4[j];
sigma5 += (*it)->e5[j];
counter++;
}
if(mbzflag)
{
ensemble_X.push_back(mbzItXY[js[masterGrid]].x);
ensemble_Y.push_back(mbzItXY[js[masterGrid]].y);
ensemble_Z.push_back(mbzItXY[js[masterGrid]].z);
}
else
{
ensemble_X.push_back(algItXY[js[masterGrid]].x);
ensemble_Y.push_back(algItXY[js[masterGrid]].y);
ensemble_Z.push_back(algItXY[js[masterGrid]].z);
}
ensemble_U.push_back(sigma/cnt);
ensemble_U2.push_back(sigma2/cnt);
ensemble_U3.push_back(sigma3/cnt);
ensemble_U4.push_back(sigma4/cnt);
ensemble_U5.push_back(sigma5/cnt);
//SJZ
temp = sqrt(pow(ensemble_U[i],2)/2);
ensemble_H.push_back(temp);
ensemble_V.push_back(temp);
sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0; counter = 0;
}
//printensemble("../Output_Files/ensemble_Test.txt");
return true;
}
void Bathy_Grid::printensemble(string z_OutputFileName)
{
std::ofstream outFile;
//vector<InterpGrid*>::iterator it = interpGrids.begin();
//vector<Point> ps;
outFile.open(z_OutputFileName.c_str());
outFile.precision(6);
outFile.setf(std::ios::fixed, std::ios::floatfield);
std::cout << "Writing file to " << z_OutputFileName.c_str() << std::endl;
if (outFile.is_open())
{
//it = interpGrids.begin();
//ps=(*it)->ptlSurface->getPositions();
for(int i = 0; i < (int) ensemble_X.size(); i++){
outFile << ensemble_X[i] << "\t" << ensemble_Y[i] << "\t" << ensemble_Z[i]
<< "\t" << ensemble_U[i] << "\t" << ensemble_U2[i]
<< "\t" << ensemble_U3[i]<< "\t" << ensemble_U4[i]
<< "\t" << ensemble_U5[i] << std::endl;
}
}
outFile.close();
}
void Bathy_Grid::addToList( InterpGrid* g)
{
interpGrids.push_back(&*g);
}
//Get the first interpGrid of type g
InterpGrid* Bathy_Grid::getGrid(GridType g)
{
vector<InterpGrid*>::iterator it;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
if((*it)->gtype == g) return *it;
}
//Get all interpGrids
vector<InterpGrid*> Bathy_Grid::getGrids()
{
return interpGrids;
}
| 31.62173
| 316
| 0.65042
|
Sammie-Jo
|
2ab0701e04a3d9f65ebe3b2ea06ed955efcc6494
| 713
|
cpp
|
C++
|
src/ck/core/customstream.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 23
|
2020-02-23T23:20:22.000Z
|
2021-12-30T16:09:23.000Z
|
src/ck/core/customstream.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 3
|
2020-03-17T05:50:40.000Z
|
2020-10-12T18:18:44.000Z
|
src/ck/core/customstream.cpp
|
opala-studios/ck
|
dff23ff3912de114ef0c7ca57da6506f0a9bee51
|
[
"Zlib"
] | 10
|
2020-03-02T15:07:32.000Z
|
2022-01-29T03:34:55.000Z
|
#include "ck/core/customstream.h"
namespace Cki
{
CustomStream::CustomStream(CkCustomFile* file) :
m_file(file)
{}
CustomStream::~CustomStream()
{
delete m_file;
}
bool CustomStream::isValid() const
{
return m_file->isValid();
}
int CustomStream::read(void* buf, int bytes)
{
return m_file->read(buf, bytes);
}
int CustomStream::write(const void* buf, int bytes)
{
return 0;
}
int CustomStream::getSize() const
{
return m_file->getSize();
}
int CustomStream::getPos() const
{
return m_file->getPos();
}
void CustomStream::setPos(int pos)
{
m_file->setPos(pos);
}
void CustomStream::close()
{
if (m_file)
{
delete m_file;
m_file = NULL;
}
}
}
| 12.963636
| 51
| 0.645161
|
opala-studios
|
2ab7d255232ba4334fef0c3c8039f8ab4d62b85e
| 23,760
|
cc
|
C++
|
pmlc/dialect/pxa/analysis/strides.cc
|
IsolatedMy/plaidml
|
34538a9224e770fd79151105399d8d7ea08678c0
|
[
"Apache-2.0"
] | null | null | null |
pmlc/dialect/pxa/analysis/strides.cc
|
IsolatedMy/plaidml
|
34538a9224e770fd79151105399d8d7ea08678c0
|
[
"Apache-2.0"
] | 65
|
2020-08-24T07:41:09.000Z
|
2021-07-19T09:13:49.000Z
|
pmlc/dialect/pxa/analysis/strides.cc
|
Flex-plaidml-team/plaidml
|
1070411a87b3eb3d94674d4d041ed904be3e7d87
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020, Intel Corporation
#include "pmlc/dialect/pxa/analysis/strides.h"
#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Support/DebugStringHelper.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
#include "pmlc/dialect/pxa/analysis/affine_expr.h"
#include "pmlc/util/bilp/ilp_solver.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/util.h"
using namespace mlir; // NOLINT
namespace pmlc::dialect::pxa {
const char *kBlockAndArgFormat = "^bb{0}:%arg{1}";
static std::string getUniqueName(Block *ref, BlockArgument arg) {
unsigned reverseDepth = 0;
while (arg.getOwner() != ref) {
ref = ref->getParentOp()->getBlock();
reverseDepth++;
}
return llvm::formatv(kBlockAndArgFormat, reverseDepth, arg.getArgNumber())
.str();
}
// Generally useful helper function
int64_t getIVStep(BlockArgument arg) {
// Check the kind of loop we are part of, and dispatch.
Operation *baseOp = arg.getOwner()->getParentOp();
size_t idx = arg.getArgNumber();
if (auto op = dyn_cast<AffineParallelOp>(baseOp)) {
auto steps = op.getSteps();
return steps[idx];
}
if (auto op = dyn_cast<AffineForOp>(baseOp)) {
return op.getStep();
}
llvm_unreachable("Get IV Step on non-IV");
}
static Optional<StrideInfo> flatten(MemRefType memRefType,
ArrayRef<StrideInfo> dimensional) {
assert(memRefType.getRank() == static_cast<int64_t>(dimensional.size()) &&
"memRef and dimensional rank mismatch");
// Get the memRef strides/offsets, and fail early if there is an issue.
int64_t offset;
SmallVector<int64_t, 4> strides;
if (failed(getStridesAndOffset(memRefType, strides, offset)))
return None;
// Fail if anything is dynamic.
if (ShapedType::isDynamicStrideOrOffset(offset) ||
llvm::any_of(strides, ShapedType::isDynamicStrideOrOffset))
return None;
StrideInfo flat{offset};
for (size_t i = 0; i < strides.size(); i++) {
flat += dimensional[i] * strides[i];
}
return flat;
}
// Multiply the offset and all strides by a constant.
StrideInfo &StrideInfo::operator*=(int64_t factor) {
offset *= factor;
if (factor == 0) {
strides.clear();
} else {
for (auto &kvp : strides) {
kvp.second *= factor;
}
}
return *this;
}
// StrideInfo addition operation.
StrideInfo &StrideInfo::operator+=(const StrideInfo &rhs) {
offset += rhs.offset;
for (const auto &kvp : rhs.strides) {
strides[kvp.first] += kvp.second;
}
// Remove entries with 0 for stride
for (auto &kvp : llvm::make_early_inc_range(strides)) {
if (kvp.second == 0) {
// DenseMap never resizes during erase, so iterators stay valid.
strides.erase(kvp.first);
}
}
return *this;
}
static BoundaryRegion getBoundaryRegion(Block *x, Block *y) {
while (x != y) {
Operation *parentOp = y->getParentOp();
if (!parentOp) {
return BoundaryRegion::Interior;
}
y = parentOp->getBlock();
if (!y) {
return BoundaryRegion::Interior;
}
}
return BoundaryRegion::Exterior;
}
StrideInfo StrideInfo::outer(BlockArgumentBoundaryFn fn) {
StrideInfo ret;
ret.offset = offset;
for (const auto &kvp : strides) {
if (fn(kvp.first) == BoundaryRegion::Exterior) {
ret.strides.insert(kvp);
}
}
return ret;
}
StrideInfo StrideInfo::inner(BlockArgumentBoundaryFn fn) {
StrideInfo ret;
ret.offset = 0;
for (const auto &kvp : strides) {
if (fn(kvp.first) == BoundaryRegion::Interior) {
ret.strides.insert(kvp);
}
}
return ret;
}
StrideInfo StrideInfo::outer(Block *block) {
return outer([block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
StrideInfo StrideInfo::inner(Block *block) {
return inner([block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
StrideRange StrideInfo::range() const {
StrideRange ret(offset);
for (const auto &kvp : strides) {
ret += StrideRange(kvp.first) * kvp.second;
}
return ret;
}
AffineValueExpr StrideInfo::toValueExpr(MLIRContext *ctx) const {
typedef std::pair<unsigned, unsigned> nestedArgNumber;
std::map<nestedArgNumber, BlockArgument> ordered;
for (auto kvp : strides) {
unsigned loopDepth = 0;
auto parent = kvp.first.getOwner()->getParentOp();
while (!dyn_cast<FuncOp>(parent)) {
loopDepth++;
parent = parent->getParentOp();
}
ordered.emplace(nestedArgNumber(loopDepth, kvp.first.getArgNumber()),
kvp.first);
}
auto tot = AffineValueExpr(ctx, offset);
for (auto item : llvm::enumerate(ordered)) {
auto blockArg = item.value().second;
Operation *baseOp = blockArg.getOwner()->getParentOp();
AffineValueExpr idx(blockArg);
if (auto op = dyn_cast<AffineParallelOp>(baseOp)) {
idx = idx - AffineValueExpr(op.getLowerBoundsValueMap(),
blockArg.getArgNumber());
} else if (auto op = dyn_cast<AffineForOp>(baseOp)) {
auto map = op.getLowerBoundMap();
idx = idx - AffineValueExpr(map.getResult(0), op.getLowerBoundOperands());
} else {
llvm_unreachable("Invalid op type in toValueMap");
}
int64_t step = getIVStep(blockArg);
auto si = strides.find(blockArg);
assert(si != strides.end());
assert(si->second % step == 0 && "Stride not divisible by step");
tot = tot + idx * (si->second / step);
}
return tot;
}
void StrideInfo::print(raw_ostream &os, Block *relative) const {
std::map<std::string, unsigned> ordered;
std::map<Block *, unsigned> blockIds;
for (auto kvp : strides) {
if (relative) {
ordered.emplace(getUniqueName(relative, kvp.first), kvp.second);
} else {
auto itNew = blockIds.emplace(kvp.first.getOwner(), blockIds.size());
ordered.emplace(llvm::formatv(kBlockAndArgFormat, itNew.first->second,
kvp.first.getArgNumber()),
kvp.second);
}
}
os << offset;
if (ordered.size()) {
os << ":[";
for (auto item : llvm::enumerate(ordered)) {
if (item.index())
os << ", ";
os << item.value().first << "=" << item.value().second;
}
os << ']';
}
}
std::ostream &operator<<(std::ostream &os, const StrideInfo &x) {
os << debugString(x);
return os;
}
AffineValueMap convertToValueMap(MLIRContext *ctx, ArrayRef<StrideInfo> dims) {
SmallVector<AffineValueExpr, 4> exprs;
for (const auto &si : dims) {
exprs.push_back(si.toValueExpr(ctx));
}
return jointValueMap(ctx, exprs);
}
static Optional<StrideInfo> computeStrideInfo(AffineParallelOp op,
BlockArgument arg) {
// Start at the lower bound, fail early if lower bound fails.
size_t idx = arg.getArgNumber();
auto out = computeStrideInfo(op.lowerBoundsMap().getResult(idx),
op.getLowerBoundsOperands());
if (!out)
return out;
// Otherwise add current index's contribution.
auto steps = op.getSteps();
out->strides[arg] += steps[idx];
return out;
}
static Optional<StrideInfo> computeStrideInfo(AffineForOp op,
BlockArgument arg) {
// Get lower bound
auto map = op.getLowerBoundMap();
// If it's not a simple lower bound, give up.
if (map.getNumResults() != 1)
return None;
// Compute the effect of the lower bound, fail early if needed.
auto out = computeStrideInfo(op.getLowerBoundMap().getResult(0),
op.getLowerBoundOperands());
if (!out)
return None;
// Otherwise add current index's contribution.
out->strides[arg] += op.getStep();
return out;
}
Optional<StrideInfo> computeStrideInfo(Value expr) {
// First, check for a block argument.
if (auto arg = expr.dyn_cast<BlockArgument>()) {
// Check the kind of loop we are part of, and dispatch.
Operation *baseOp = arg.getOwner()->getParentOp();
if (auto op = dyn_cast<AffineParallelOp>(baseOp))
return computeStrideInfo(op, arg);
if (auto op = dyn_cast<AffineForOp>(baseOp))
return computeStrideInfo(op, arg);
// Is this an assertable condition?
return None;
}
// Try for the affine apply case
if (auto op = dyn_cast_or_null<AffineApplyOp>(expr.getDefiningOp()))
return computeStrideInfo(op.getAffineMap().getResult(0),
op.getMapOperands());
IVLOG(1, "Failed stride info: op = " << debugString(expr));
return None;
}
Optional<StrideInfo> computeStrideInfo(AffineExpr expr, ValueRange args) {
// If we are a constant affine expression, it's a simple offset.
if (auto cexpr = expr.dyn_cast<AffineConstantExpr>())
return StrideInfo(cexpr.getValue());
// If we are a dim, it's just a Value.
if (auto dexpr = expr.dyn_cast<AffineDimExpr>())
return computeStrideInfo(args[dexpr.getPosition()]);
// Check the various binary ops.
if (auto bexpr = expr.dyn_cast<AffineBinaryOpExpr>()) {
if (bexpr.getKind() == AffineExprKind::Mul) {
// For multiplies, RHS should always be constant of symbolic, and symbols
// fail, so we cast to constant and give up if it doesn't work
auto rhs = bexpr.getRHS().dyn_cast<AffineConstantExpr>();
if (!rhs)
return None;
// Now compute the LHS via recursion
auto lhs = computeStrideInfo(bexpr.getLHS(), args);
if (!lhs)
return None;
// Multiply by the multiplier and return
*lhs *= rhs.getValue();
return lhs;
}
if (bexpr.getKind() == AffineExprKind::Add) {
// For add, we compute both sides and add them (presuming they both return
// valid outputs).
auto lhs = computeStrideInfo(bexpr.getLHS(), args);
if (!lhs)
return None;
auto rhs = computeStrideInfo(bexpr.getRHS(), args);
if (!rhs)
return None;
*lhs += *rhs;
return lhs;
}
}
// Fail for all other cases.
return None;
}
LogicalResult computeMultiDimStrideInfo(AffineMap map, ValueRange args,
SmallVectorImpl<StrideInfo> &results) {
for (auto expr : map.getResults()) {
auto dimStride = computeStrideInfo(expr, args);
if (!dimStride) {
return failure();
}
results.push_back(*dimStride);
}
return success();
}
LogicalResult computeMultiDimStrideInfo(const AffineValueMap &valueMap,
SmallVectorImpl<StrideInfo> &out) {
return computeMultiDimStrideInfo(valueMap.getAffineMap(),
valueMap.getOperands(), out);
}
Optional<StrideInfo> computeStrideInfo(MemRefType memRefType, AffineMap map,
ValueRange values) {
// Verify the in/out dimensions make sense.
assert(map.getNumResults() == memRefType.getRank());
assert(map.getNumInputs() == values.size());
// Get the memRef strides/offsets, and fail early if there is an issue.
int64_t memRefOffset;
SmallVector<int64_t, 4> memRefStrides;
if (failed(getStridesAndOffset(memRefType, memRefStrides, memRefOffset)))
return None;
// Fail if anything is dynamic.
if (ShapedType::isDynamicStrideOrOffset(memRefOffset))
return None;
for (size_t i = 0; i < memRefStrides.size(); i++) {
if (ShapedType::isDynamicStrideOrOffset(memRefStrides[i]))
return None;
}
StrideInfo out(memRefOffset);
for (size_t i = 0; i < map.getNumResults(); i++) {
// Collect the output for each dimension of the memRef.
auto perDim = computeStrideInfo(map.getResult(i), values);
// Fail if needed
if (!perDim)
return None;
// Otherwise multiply by memRef stride and add in
*perDim *= memRefStrides[i];
out += *perDim;
}
// Return the accumulated results
return out;
}
Optional<StrideInfo> computeStrideInfo(PxaLoadOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaReduceOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaVectorLoadOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<StrideInfo> computeStrideInfo(PxaVectorReduceOp op) {
return computeStrideInfo(op.getMemRefType(), op.getAffineMap(),
op.getMapOperands());
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Value memref, ArrayRef<StrideRange> internalRanges,
const AffineValueMap &valueMap, Block *block) {
return computeRelativeAccess(
memref, internalRanges, valueMap, [block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Value memref, ArrayRef<StrideRange> internalRanges,
const AffineValueMap &valueMap,
BlockArgumentBoundaryFn fn) {
SmallVector<StrideInfo> strides;
if (failed(computeMultiDimStrideInfo(valueMap, strides)))
return None;
RelativeAccessPattern ret(memref);
for (auto it : llvm::zip(strides, internalRanges)) {
StrideInfo &si = std::get<0>(it);
const StrideRange &internalRange = std::get<1>(it);
ret.outer.push_back(si.outer(fn));
StrideInfo inner = si.inner(fn);
ret.inner.push_back(inner);
StrideRange range = inner.range() + internalRange;
if (!range.valid || range.minVal != 0)
return None;
ret.innerRanges.push_back(range);
ret.wholeInnerCount.push_back(range.maxVal - range.minVal + 1);
ret.innerCount.push_back(range.count());
}
return ret;
}
Optional<RelativeAccessPattern>
computeRelativeAccess(Operation *op, BlockArgumentBoundaryFn fn) {
ArrayRef<int64_t> vecSize;
Value memref;
SmallVector<StrideInfo> strides;
LogicalResult ok =
TypeSwitch<Operation *, LogicalResult>(op)
.Case<PxaLoadOp>([&](auto op) {
memref = op.memref();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaReduceOp>([&](auto op) {
memref = op.memref();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaVectorLoadOp>([&](auto op) {
memref = op.memref();
vecSize = op.getVectorType().getShape();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Case<PxaVectorReduceOp>([&](auto op) {
memref = op.memref();
vecSize = op.getVectorType().getShape();
return computeMultiDimStrideInfo(op.getAffineMap(),
op.getMapOperands(), strides);
})
.Default([](auto op) { return failure(); });
if (failed(ok)) {
return None;
}
RelativeAccessPattern ret(memref);
for (size_t i = 0; i < strides.size(); i++) {
auto outer = strides[i].outer(fn);
ret.outer.push_back(outer);
auto inner = strides[i].inner(fn);
ret.inner.push_back(inner);
StrideRange range = inner.range();
if (i + vecSize.size() >= strides.size()) {
int64_t vecVal = vecSize[i + vecSize.size() - strides.size()];
if (vecVal > 1) {
StrideRange vecRange(0, vecVal - 1, 1);
range += vecRange;
}
}
if (!range.valid || range.minVal != 0) {
return None;
}
ret.innerRanges.push_back(range);
ret.wholeInnerCount.push_back(range.maxVal - range.minVal + 1);
ret.innerCount.push_back(range.count());
}
return ret;
}
Optional<RelativeAccessPattern> computeRelativeAccess(Operation *op,
Block *block) {
return computeRelativeAccess(op, [block](BlockArgument arg) {
return getBoundaryRegion(arg.getOwner(), block);
});
}
MemRefType RelativeAccessPattern::getMemRefType() const {
return memRef.getType().cast<MemRefType>();
}
SmallVector<int64_t, 4> RelativeAccessPattern::innerStride() const {
SmallVector<int64_t, 4> ret;
for (const StrideRange &range : innerRanges) {
ret.push_back(range.stride ? range.stride : 1);
}
return ret;
}
int64_t RelativeAccessPattern::totalInnerCount() const {
int64_t ret = 1;
for (auto range : innerRanges) {
ret *= range.count();
}
return ret;
}
int64_t RelativeAccessPattern::totalInnerBytes() const {
auto eltSize = llvm::divideCeil(getMemRefType().getElementTypeBitWidth(), 8);
return totalInnerCount() * eltSize;
}
Optional<StrideInfo> RelativeAccessPattern::flatOuter() const {
return flatten(getMemRefType(), outer);
}
Optional<StrideInfo> RelativeAccessPattern::flatInner() const {
return flatten(getMemRefType(), inner);
}
LogicalResult
RelativeAccessPattern::unionMerge(const RelativeAccessPattern &rhs) {
if (innerRanges.size() != rhs.innerRanges.size()) {
return failure();
}
for (unsigned i = 0; i < outer.size(); i++) {
if (outer[i] != rhs.outer[i]) {
return failure();
}
}
inner.clear();
innerCount.clear();
for (unsigned i = 0; i < innerRanges.size(); i++) {
innerRanges[i].unionEquals(rhs.innerRanges[i]);
innerCount.push_back(innerRanges[i].count());
}
return success();
}
// Use ILP to find out if two different iterations of the outer indexes (in
// allOuter) ever alias. To do this, we make a system with two copies of all
// the variable (outer + inner indexes) called _a and _b. Then we constrain the
// total effect of _a and the total effect of _b to be the same (i.e. both
// index sets access the same memory location). We also contrain the indexes to
// their appropriate ranges. Then we see if we can ever get the _a and _b
// version of any of the outer indexes to differ at all (by minimimizing oi_a -
// oi_b). If it's possible for them the differ, then (since _a + _b are
// symmetric), the minimum of the difference will be < 0.
bool RelativeAccessPattern::outerAlias(DenseSet<BlockArgument> allOuter) const {
using Poly = util::math::Polynomial<util::math::Rational>;
using RangeCons = util::math::RangeConstraint;
util::bilp::ILPSolver solver;
// We track each index as we add it, and make a string version since the
// Polynomial logic uses string names for variables.
DenseMap<BlockArgument, std::string> baToStr;
// The collection of constraints, this ends up including:
// 1) Range constraints for two copies (a + b).
// 2) Contraints requiring all dimensions of the access to be the same for
// both the a access and the b access.
std::vector<RangeCons> constraints;
// The collection of things to minimize. Here it's the differences of _a and
// _b for all outer indexes
std::vector<Poly> toMin;
// A lambda to convert a block arg to x<i>_a - x<i>_b for some unique i. If
// we haven't seen the block arg before, we add it to the map, along with
// range constraints for the _a and _b versions.
auto toDiff = [&](BlockArgument arg) {
std::string &str = baToStr[arg];
if (str.empty()) {
str = llvm::formatv("x{0}", baToStr.size());
StrideRange range(arg);
constraints.emplace_back(str + "_a", range.maxVal + 1);
constraints.emplace_back(str + "_b", range.maxVal + 1);
}
return Poly(str + "_a") - Poly(str + "_b");
};
// Add entries for all the outer indexes.
for (BlockArgument arg : allOuter) {
Poly diff = toDiff(arg);
toMin.emplace_back(diff);
}
// Go over each dimension of the access.
for (size_t i = 0; i < outer.size(); i++) {
// Compute the difference between the a + b versions of the access for this
// dimension of the access.
Poly totDiff;
for (const auto &kvp : outer[i].strides) {
Poly diff = toDiff(kvp.first);
totDiff += diff * kvp.second;
}
for (const auto &kvp : inner[i].strides) {
Poly diff = toDiff(kvp.first);
totDiff += diff * kvp.second;
}
// Constrain this diff to be the range [0, 1) in integers, i.e. constrain it
// to be exactly 0.
constraints.emplace_back(totDiff, 1);
}
IVLOG(3, "Doing a batch solve!");
IVLOG(3, "Constraints: " << constraints);
IVLOG(3, "toMin: " << toMin);
// Do the actual ILP solve.
auto res = solver.batch_solve(constraints, toMin);
// If any of the results have a minimum that is not exactly 0, it means the _a
// and _b version of that index can have two differnt values while still
// accessing the same point in the tensor. AKA we have hit an outer alias.
for (const auto &kvp : res) {
IVLOG(3, "obj_val = " << kvp.second.obj_val);
if (kvp.second.obj_val < 0) {
return true;
}
}
// Otherwise, all is well.
return false;
}
bool hasPerfectAliasing(const RelativeAccessPattern &aRap,
RelativeAccessPattern bRap,
const DenseMap<BlockArgument, BlockArgument> &bToA) {
IVLOG(3, "hasPerfectAliasing");
DenseSet<BlockArgument> allOuter;
for (const auto &kvp : bToA) {
allOuter.insert(kvp.second);
}
if (aRap.outerAlias(allOuter)) {
IVLOG(3, "outerAlias");
return false;
}
for (auto &si : bRap.outer) {
StrideInfo translated(si.offset);
for (const auto &kvp : si.strides) {
translated.strides[bToA.find(kvp.first)->second] = kvp.second;
}
si = translated;
}
if (aRap.outer.size() != bRap.outer.size()) {
IVLOG(3, "size mismatch: " << aRap.outer.size()
<< " != " << bRap.outer.size());
return false;
}
IVLOG(3, "aRap.innerCount: " << aRap.innerCount);
IVLOG(3, "bRap.innerCount: " << bRap.innerCount);
for (size_t i = 0; i < aRap.outer.size(); i++) {
const StrideInfo &aOuter = aRap.outer[i];
const StrideInfo &bOuter = bRap.outer[i];
const int64_t aInnerCount = aRap.innerCount[i];
const int64_t bInnerCount = bRap.innerCount[i];
if (aOuter != bOuter) {
IVLOG(3, "aOuter != bOuter");
return false;
}
if (aInnerCount != bInnerCount) {
IVLOG(3, "aInnerCount: " << aInnerCount
<< " != bInnerCount: " << bInnerCount);
return false;
}
}
return true;
}
double computeCacheMiss(double cacheElems,
SmallVector<int64_t, 4> tileDimensions,
SmallVector<int64_t, 4> tensorStrides) {
// Start with one cache line
double cacheLines = 1.0;
// Current accumulated maximum value
int64_t maxVal = 0;
// For each dimension (in sorted order)
assert(tileDimensions.size() == tensorStrides.size());
for (size_t i = tileDimensions.size(); i > 0; i--) {
// Compute gap per step
int64_t gap = std::abs(tensorStrides[i - 1]) - maxVal;
// Multiply current cache hits by size
cacheLines *= static_cast<double>(tileDimensions[i - 1]);
// Compute probability that cache line is shared across gap
double probShared = 0.0; // Assume it's never shared
if (cacheElems != 0.0 && gap < cacheElems) {
probShared = 1.0 - (gap / cacheElems);
}
// Subtract shared elements
cacheLines -= probShared * static_cast<double>(tileDimensions[i - 1] - 1);
// Update maxVal
maxVal += std::abs(tensorStrides[i - 1]) * (tileDimensions[i - 1] - 1);
}
return cacheLines;
}
} // namespace pmlc::dialect::pxa
| 32.151556
| 80
| 0.642971
|
IsolatedMy
|
2ababea0ef23519b966cf9c4d85576fa04565f94
| 3,055
|
cpp
|
C++
|
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
#include <dll_main.h>
#include <Il2CppModLoader/il2cpp_helpers.h>
#include <Il2CppModLoader/interception_macros.h>
using namespace modloader;
INJECT_C_DLLEXPORT bool in_menu();
namespace
{
constexpr float NO_AIR_DECELERATION_DURATION = 0.2f;
constexpr float NO_AIR_DECELERATION_RESET_DURATION = 0.2f;
float aim_timer = 0.0f;
float reset_timer = 0.0f;
STATIC_IL2CPP_BINDING(Game, UI, bool, get_MainMenuVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_WorldMapVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_ShardShopVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, IsInventoryVisible, ());
STATIC_IL2CPP_BINDING(, TimeUtility, float, get_deltaTime, ());
bool is_aiming_launch(app::CharacterAirNoDeceleration* this_ptr)
{
if (!in_menu())
{
if (aim_timer >= 0.0f)
aim_timer -= TimeUtility::get_deltaTime();
if (reset_timer >= 0.0f)
reset_timer -= TimeUtility::get_deltaTime();
}
auto* sein = get_sein();
auto* wrapper = sein->fields.Abilities->fields.ChargeJumpWrapper;
if (wrapper->fields.HasState && wrapper->fields.State->fields.m_state == app::SeinChargeJump_State__Enum_Aiming)
{
aim_timer = NO_AIR_DECELERATION_DURATION;
if (reset_timer > 0.0f)
this_ptr->fields.m_noDeceleration = true;
}
return aim_timer > 0.0f;
}
IL2CPP_INTERCEPT(, CharacterAirNoDeceleration, void, UpdateCharacterState, (app::CharacterAirNoDeceleration* this_ptr)) {
auto* platform_behaviour = this_ptr->fields.PlatformBehaviour;
auto* platform_movement = platform_behaviour->fields.PlatformMovement;
if (!il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsSuspended")->fields)
{
if (il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsOnGround")->fields)
this_ptr->fields.m_noDeceleration = false;
if (0.00000000 <= il2cpp::invoke<app::Single__Boxed>(platform_movement, "get_LocalSpeedY")->fields &&
platform_movement->fields._.Ceiling->fields.IsOn)
this_ptr->fields.m_noDeceleration = false;
auto* left_right_movement = platform_behaviour->fields.LeftRightMovement;
if (!left_right_movement->fields.m_settings->fields.LockInput &&
!is_aiming_launch(this_ptr) &&
left_right_movement->fields.m_horizontalInput != 0.0)
{
if (this_ptr->fields.m_noDeceleration)
reset_timer = NO_AIR_DECELERATION_RESET_DURATION;
this_ptr->fields.m_noDeceleration = false;
}
}
}
}
INJECT_C_DLLEXPORT bool in_menu()
{
return il2cpp::get_class<app::UI__Class>("Game", "UI")->static_fields->m_sMenu->fields.m_equipmentWhellVisible
|| UI::get_MainMenuVisible()
|| UI::get_WorldMapVisible()
|| UI::get_ShardShopVisible()
|| UI::IsInventoryVisible();
}
| 39.166667
| 125
| 0.656301
|
Mawex
|
2abeb9fd1d1143367447899d45b6634125850eb3
| 903
|
hpp
|
C++
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 148
|
2017-08-25T13:32:05.000Z
|
2022-03-17T18:40:49.000Z
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 160
|
2017-08-16T19:58:53.000Z
|
2022-02-26T09:57:38.000Z
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 24
|
2018-05-23T18:59:47.000Z
|
2022-03-23T17:25:01.000Z
|
#pragma once
#include "controller.hpp"
#include "settings.hpp"
namespace msrv {
class Router;
class ContentTypeMap;
class WorkQueue;
class StaticController : public ControllerBase
{
public:
StaticController(
Request* request,
const Path& targetDir,
const ContentTypeMap& contentTypes);
~StaticController();
ResponsePtr getFile();
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
SettingsDataPtr settings,
const ContentTypeMap& contentTypes);
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
const std::string& urlPrefix,
const std::string& targetDir,
const ContentTypeMap& contentTypes);
private:
std::string getNormalizedPath();
ResponsePtr redirectToDirectory();
const Path& targetDir_;
const ContentTypeMap& contentTypes_;
};
}
| 20.066667
| 46
| 0.679956
|
R0nd
|
2abf210d52a35dc06f0affc7c10b492d6f89479f
| 291
|
cpp
|
C++
|
predavanje1/operatori3.cpp
|
Miillky/algoritmi_i_strukture_podataka
|
b5813f4b897a1370b6f46782bf5ecd474d0d7e20
|
[
"MIT"
] | null | null | null |
predavanje1/operatori3.cpp
|
Miillky/algoritmi_i_strukture_podataka
|
b5813f4b897a1370b6f46782bf5ecd474d0d7e20
|
[
"MIT"
] | null | null | null |
predavanje1/operatori3.cpp
|
Miillky/algoritmi_i_strukture_podataka
|
b5813f4b897a1370b6f46782bf5ecd474d0d7e20
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int a = 3;
if (int b = 2; a > b) // javlja warning - init-statement in selection statements only available with -std=c++1z or -std=gnu++1z
{
cout << a << endl;
cout << b << endl;
}
cout << a << endl;
}
| 24.25
| 131
| 0.549828
|
Miillky
|
2abfff4018ad1033983ed6c1d115a1c39441d92c
| 948
|
cpp
|
C++
|
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | 2
|
2019-11-25T20:54:56.000Z
|
2019-11-25T20:55:20.000Z
|
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | null | null | null |
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | 1
|
2019-11-25T23:14:18.000Z
|
2019-11-25T23:14:18.000Z
|
#include "Matrix.hpp"
Matrix Matrix::operator+ () const {
return *this;
}
Matrix Matrix::operator- () const {
return operator*(-1.);
}
Matrix Matrix::operator+ (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] + scalar;
return A;
}
Matrix Matrix::operator- (const real_t &scalar) const {
return operator+ (-scalar);
}
Matrix Matrix::operator* (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] * scalar;
return A;
}
Matrix Matrix::operator/ (const real_t &scalar) const {
ASSERT_DOMAIN(scalar != 0.);
return operator* (1 / scalar);
}
Matrix Matrix::operator+ (const Matrix &B) const {
Matrix A = *this;
ASSERT_DOMAIN(A.Width() == B.Width() && A.Height() == B.Height());
for(size_t y = 0; y < Height(); ++y)
A[y] = A[y] + B[y];
return A;
}
Matrix Matrix::operator- (const Matrix &B) const {
return operator+ (-B);
}
| 19.346939
| 67
| 0.619198
|
frndmg
|
2ac265cf382f478e608bd8422b037015ab3bcd7e
| 1,949
|
hpp
|
C++
|
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <crab/support/debug.hpp>
#include <crab/support/os.hpp>
namespace crab {
namespace cfg {
// To group together statements over integers or real
typedef enum {
BINOP_ADD,
BINOP_SUB,
BINOP_MUL,
BINOP_SDIV,
BINOP_UDIV,
BINOP_SREM,
BINOP_UREM,
BINOP_AND,
BINOP_OR,
BINOP_XOR,
BINOP_SHL,
BINOP_LSHR,
BINOP_ASHR,
} binary_operation_t;
typedef enum { BINOP_BAND, BINOP_BOR, BINOP_BXOR } bool_binary_operation_t;
typedef enum { CAST_TRUNC, CAST_SEXT, CAST_ZEXT } cast_operation_t;
inline crab::crab_os &operator<<(crab::crab_os &o, binary_operation_t op) {
switch (op) {
case BINOP_ADD:
o << "+";
break;
case BINOP_SUB:
o << "-";
break;
case BINOP_MUL:
o << "*";
break;
case BINOP_SDIV:
o << "/";
break;
case BINOP_UDIV:
o << "/_u";
break;
case BINOP_SREM:
o << "%";
break;
case BINOP_UREM:
o << "%_u";
break;
case BINOP_AND:
o << "&";
break;
case BINOP_OR:
o << "|";
break;
case BINOP_XOR:
o << "^";
break;
case BINOP_SHL:
o << "<<";
break;
case BINOP_LSHR:
o << ">>_l";
break;
case BINOP_ASHR:
o << ">>_r";
break;
default:
CRAB_ERROR("unexpected binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, bool_binary_operation_t op) {
switch (op) {
case BINOP_BAND:
o << "&";
break;
case BINOP_BOR:
o << "|";
break;
case BINOP_BXOR:
o << "^";
break;
default:
CRAB_ERROR("unexpected boolean binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, cast_operation_t op) {
switch (op) {
case CAST_TRUNC:
o << "trunc";
break;
case CAST_SEXT:
o << "sext";
break;
case CAST_ZEXT:
o << "zext";
break;
default:
CRAB_ERROR("unexpected cast operation", op);
}
return o;
}
} // end namespace cfg
} // end namespace crab
| 17.247788
| 80
| 0.601847
|
LinerSu
|
2ac7289f2839f679932b31c3de3b0e50c2d56a5a
| 1,735
|
cpp
|
C++
|
rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp
|
afoolsbag/rrCnCxx
|
1e673bd4edac43d8406a0c726138cba194d17f48
|
[
"Unlicense"
] | 2
|
2019-03-20T01:14:10.000Z
|
2021-12-08T15:39:32.000Z
|
rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp
|
afoolsbag/rrCnCxx
|
1e673bd4edac43d8406a0c726138cba194d17f48
|
[
"Unlicense"
] | null | null | null |
rrMFC/Dlg_Property/PropertySheet/PropertyPage1.cpp
|
afoolsbag/rrCnCxx
|
1e673bd4edac43d8406a0c726138cba194d17f48
|
[
"Unlicense"
] | null | null | null |
/// \copyright The Unlicense
#include "stdafx.h"
#include "PropertyPage1.h"
#include "PropertySheet.rc.h"
#include "rrwindows/rrwindows.h"
namespace rrMFC {
namespace Test {
const UINT PropertyPage1::IDD {IDD_PROPERTY_PAGE_1};
#// Constructors
PropertyPage1::
PropertyPage1()
: CPropertyPage(IDD)
{
DcMeth();
}
PropertyPage1::
~PropertyPage1()
{
DcMeth();
}
#// Operations
VOID PropertyPage1::
ReadFrom(CONST Configurations &configs)
{
DcMeth();
#ifdef M
# error Macro name conflicts.
#endif/*M*/
#define M(prop) (prop = configs.prop)
M(ServiceIpaddr);
M(ServiceIpport);
#undef M
}
VOID PropertyPage1::
WriteTo(Configurations *CONST pConfigs) CONST
{
DcMeth();
#ifdef M
# error Macro name conflicts.
#endif/*M*/
#define M(prop) (pConfigs->prop = prop)
M(ServiceIpaddr);
M(ServiceIpport);
#undef M
}
#// Overridables
BOOL PropertyPage1::
OnInitDialog()
{
CPropertyPage::OnInitDialog();
DcMeth();
return TRUE;
}
BOOL PropertyPage1::
OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT *pResult)
{
DcWndMsg();
return CPropertyPage::OnWndMsg(message, wParam, lParam, pResult);
}
VOID PropertyPage1::
DoDataExchange(CDataExchange *pDX)
{
CPropertyPage::DoDataExchange(pDX);
DcMeth();
DDX_IPAddress(pDX, IDC_SERVICE_IPADDR, ServiceIpaddr);
DDX_Text(pDX, IDC_SERVICE_IPPORT, ServiceIpport);
DDV_MinMaxUInt(pDX, ServiceIpport, 0, 65535);
}
VOID PropertyPage1::
OnOK()
{
DcMeth();
CPropertyPage::OnOK();
}
VOID PropertyPage1::
OnCancel()
{
DcMeth();
CPropertyPage::OnCancel();
}
BOOL PropertyPage1::
OnApply()
{
DcMeth();
return CPropertyPage::OnApply();
}
#// Message Handlers
}//namespace Test
}//namespace rrMFC
| 15.772727
| 70
| 0.695677
|
afoolsbag
|
2ac9d9b284c80fb4fcb117ac935242dc593aea35
| 1,825
|
hpp
|
C++
|
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
#ifndef GEOMETRY_MESHBUILDERBASE_HPP
#define GEOMETRY_MESHBUILDERBASE_HPP
#include <Core/Types/TVector.hpp>
#include <Geometry/HalfedgeMesh/HalfedgeMesh.hpp>
#include <Geometry/HalfedgeMeshBuilder/MeshTriangleAdder.hpp>
#include <LinAl/LinearAlgebra.hpp>
namespace Geometry
{
template <typename T, typename Derived>
class MeshBuilderBase {
protected:
LinAl::HMatrix<double_t> m_transformation = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}};
std::unique_ptr<HalfedgeMesh<T>>
buildTriangleHeMesh(const LinAl::Vec3Vector<T>& points,
const Core::TVector<uint32_t>& triangleIndices) const
{
auto heMesh = std::make_unique<HalfedgeMesh<T>>();
MeshTriangleAdder<T> meshTriangleAdder{*heMesh};
std::size_t size = triangleIndices.size();
for (std::size_t i{2}; i < size; i += 3)
{
LinAl::VecArray<T, 3, 3> trianglePoints;
for (std::size_t j{0}; j < 3; ++j)
{
const std::size_t idx = triangleIndices[i - j];
const LinAl::Vec3<T>& point = points[idx];
LinAl::HVec<T> tPoint =
m_transformation * LinAl::HVec<T>{point[0], point[1], point[2], 1.0};
trianglePoints[j] = LinAl::Vec3<T>{tPoint[0], tPoint[1], tPoint[2]};
}
meshTriangleAdder(Triangle<T, 3>(trianglePoints));
}
return heMesh;
}
Derived& setTransformation(const LinAl::HMatrix<T>& transformation)
{
m_transformation = transformation;
return *static_cast<Derived*>(this);
}
};
} // namespace Geometry
#endif // GEOMETRY_MESHBUILDERBASE_HPP
| 35.096154
| 89
| 0.564384
|
timow-gh
|