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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c2c10ea1885fadec386342b225c2c8f48bfdec52 | 1,688 | cpp | C++ | bookopencv/ch4_ex4_3.cpp | quchunguang/test | dd1dde14a69d9e8b2c9ed3efbf536df7840f0487 | [
"MIT"
] | 1 | 2021-05-06T02:02:59.000Z | 2021-05-06T02:02:59.000Z | bookopencv/ch4_ex4_3.cpp | SrikanthParsha14/test | 8cee69e09c8557d53d8d30382cec8ea5c1f82f6e | [
"MIT"
] | null | null | null | bookopencv/ch4_ex4_3.cpp | SrikanthParsha14/test | 8cee69e09c8557d53d8d30382cec8ea5c1f82f6e | [
"MIT"
] | 1 | 2019-06-17T13:20:39.000Z | 2019-06-17T13:20:39.000Z | /* ************ License: *******************************
Oct. 3, 2008
Right to use this code in any way you want without warrenty, support or any guarentee of it working.
BOOK: It would be nice if you cited it:
Learning OpenCV: Computer Vision with the OpenCV Library
by Gary Bradski and Adrian Kaehler
Published by O'Reilly Media, October 3, 2008
AVAILABLE AT:
http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
Or: http://oreilly.com/catalog/9780596516130/
ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
OTHER OPENCV SITES:
* The source code is on sourceforge at:
http://sourceforge.net/projects/opencvlibrary/
* The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back):
http://opencvlibrary.sourceforge.net/
* An active user group is at:
http://tech.groups.yahoo.com/group/OpenCV/
* The minutes of weekly OpenCV development meetings are at:
http://pr.willowgarage.com/wiki/OpenCV
* *****************************************************/
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
int main(int argc, char** argv) {
//Adding something to open a video so that we can read its properties ...
IplImage *frame; //To hold movie images
CvCapture* capture = NULL;
if ((argc < 2) || !(capture = cvCreateFileCapture(argv[1]))) {
printf("Failed to open %s\n", argv[1]);
return -1;
}
//Read the properties
double f = cvGetCaptureProperty(capture, CV_CAP_PROP_FOURCC);
char* fourcc = (char*) (&f);
printf("Properties of %s are:\n", argv[1]);
printf("FORCC = %d | %d | %d | %d |\n", fourcc[0], fourcc[1], fourcc[2],
fourcc[3]);
cvReleaseCapture(&capture);
return 0;
}
| 37.511111 | 105 | 0.670024 | quchunguang |
c2c59e3de767f1acef373193b01c88b784d71a01 | 2,776 | cpp | C++ | Random.cpp | yuanyangwangTJ/RSA | 384423bf33d555047755bb253a3531e35870ffd6 | [
"MIT"
] | null | null | null | Random.cpp | yuanyangwangTJ/RSA | 384423bf33d555047755bb253a3531e35870ffd6 | [
"MIT"
] | null | null | null | Random.cpp | yuanyangwangTJ/RSA | 384423bf33d555047755bb253a3531e35870ffd6 | [
"MIT"
] | null | null | null | /**************************************
* Class Name: PRNG, PrimeGen
* Function: 伪随机数与伪随机素数比特生成器
* Introduction: PrimeGen 继承于 PRNG 类
* ***********************************/
#include "Random.h"
#include "TDES.h"
#include <iostream>
#include <ctime>
#include <cstring>
#include <NTL/ZZ.h>
using namespace std;
using namespace NTL;
typedef unsigned long long size_ul;
/*---------------------------------
* Class: PRNG
*-------------------------------*/
// 构造函数,进行初始化操作
PRNG::PRNG(int n) {
m = n;
x = new bitset<64>[m];
s = "";
}
// 析构函数,释放内存空间
PRNG::~PRNG() {
delete [] x;
}
// 通过外界修改 m 的数值
void PRNG::SetM(int n) {
m = n;
delete [] x;
x = new bitset<64>[m];
}
// 伪随机数比特生成函数
ZZ PRNG::GenerateRandom() {
// 获取本地时间日期
time_t now = time(0);
bitset<64> Date(now);
// 产生 64 比特随机种子 s
size_ul ss = size_ul(random()) << 32 + random();
bitset<64> s(ss);
TDES td;
td.plain = Date;
bitset<64> Im = td.TDESEncrypt();
for (int i = 0; i < m; i++) {
td.plain = Im ^ s;
x[i] = td.TDESEncrypt();
td.plain = x[i] ^ Im;
s = td.TDESEncrypt();
}
// 生成字符串类型保存
bitsToString();
ZZ res = bitsToNumber();
return res;
}
// 将比特数转化为 ZZ 型数字
ZZ PRNG::bitsToNumber() {
ZZ res(0);
for (int i = 0; i < m; i++) {
string str = x[i].to_string();
for (int j = 0; j < 64; j++) {
res = res * 2;
if (str[j] == '1') {
res = res + 1;
}
}
}
return res;
}
// 比特位转为字符串类型(01字符串)
void PRNG::bitsToString() {
s = "";
for (int i = 0; i < m; i++) {
s += x[i].to_string();
}
}
// 以十六进制打印比特数值
void PRNG::PrintInDER() {
cout << "modulus:";
string pairstr = "";
for (size_t i = 0; i < s.length(); i += 4) {
int index = 0;
for (size_t j = i; j < i + 4; j++) {
index = index << 1;
if (s[j] == '1') {
index += 1;
}
}
pairstr += DERTable[index];
if (pairstr.length() == 2) {
cout << pairstr;
if (i + 4 < s.length()) {
cout << ":";
}
pairstr = "";
}
if (i % 120 == 0) {
cout << endl << '\t';
}
}
cout << endl;
}
/*---------------------------------
* Class: PrimeGen
*-------------------------------*/
PrimeGen::PrimeGen(int n) : PRNG(n) {
cout << "Create a pseudorandom number generator.\n";
}
// 生成随机素数,使用 NTL 中库函数检验
// 素性检测算法为 Miller-Rabin 检测
ZZ PrimeGen::GeneratePrime() {
ZZ res(0);
// 此处进行 srandom,为产生 64 比特随机种子
srandom((unsigned)time(NULL));
do {
res = GenerateRandom();
} while(!ProbPrime(res, m * 32));
return res;
} | 19.971223 | 56 | 0.439841 | yuanyangwangTJ |
c2c618b7e7bd6cd15c57a27cc896ac145cd735d9 | 550 | cpp | C++ | test/src/main.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | test/src/main.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | test/src/main.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | #include "gtest/gtest.h"
#include "minko/Minko.hpp"
#include "minko/MinkoTests.hpp"
#include "minko/MinkoSDL.hpp"
using namespace minko;
void wait()
{
std::cout << "Press ENTER to continue...";
std::cin.ignore(std::numeric_limits <std::streamsize> ::max(), '\n');
}
int main(int argc, char **argv)
{
auto canvas = Canvas::create("Minko Tests", 640, 480);
::testing::InitGoogleTest(&argc, argv);
MinkoTests::canvas(canvas);
auto output = RUN_ALL_TESTS();
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5
wait();
#endif
return output;
}
| 17.1875 | 70 | 0.685455 | undeadinu |
c2cb7da54a485a4dcea154ca0c205b70fa691ba3 | 2,428 | cpp | C++ | problems/acmicpc_2188.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_2188.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | problems/acmicpc_2188.cpp | qawbecrdtey/BOJ-sol | e3f410e8f4e3a6ade51b68ce2024529870edac64 | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
class graph {
class edge;
class vertex {
public:
vector<edge*> edges;
void add_edge(vertex *v) {
auto p = edge::make_edge(this, v);
edges.push_back(p.first);
v->edges.push_back(p.second);
}
};
class edge {
vertex *u, *v;
int capacity;
edge *reverse;
edge(vertex *u, vertex *v, int capacity) : u(u), v(v), capacity(capacity), reverse(nullptr) {}
public:
static pair<edge*, edge*> make_edge(vertex *u, vertex *v) {
auto const forward = new edge(u, v, 1);
auto const backward = new edge(v, u, 0);
forward->reverse = backward;
backward->reverse = forward;
return { forward, backward };
}
[[nodiscard]] vertex *next() const { return v; }
[[nodiscard]] bool empty() const { return capacity == 0; }
void fill(int f) {
capacity -= f;
reverse->capacity += f;
}
};
int from, to;
vertex *vertices;
static void add_edge(vertex *u, vertex *v) { u->add_edge(v); }
[[nodiscard]] vertex* start(int x) const { return vertices + x + 1; }
[[nodiscard]] vertex* end(int x) const { return vertices + x + from + 1; }
public:
graph(int from, int to) : from(from), to(to), vertices(new vertex[from + to + 2]) {
for(int i = 1; i <= from; i++) {
add_edge(vertices, start(i));
}
for(int i = 1; i <= to; i++) {
add_edge(end(i), vertices + 1);
}
}
void add_edge(int u, int v) { add_edge(start(u), end(v)); }
int flow() {
auto visited = make_unique<bool[]>(from + to + 2);
queue<pair<int, pair<vector<edge*>, int>>> q;
q.push({ 0, { {}, 1 } });
while(!q.empty()) {
auto const now = q.front(); q.pop();
if(visited[now.first]) continue;
visited[now.first] = true;
if(now.first == 1) {
for(auto e : now.second.first) {
e->fill(1);
}
return 1;
}
for(auto e : vertices[now.first].edges) {
auto const next = e->next() - vertices;
if(e->empty() || visited[next]) continue;
auto v = now.second.first;
v.push_back(e);
q.push({ next, { v, 1 } });
}
}
return 0;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m;
cin >> n >> m;
graph g(n, m);
for(int i = 1; i <= n; i++) {
int t, x;
cin >> t;
for(int j = 0; j < t; j++) {
cin >> x;
g.add_edge(i, x);
}
}
int flow, res = 0;
while((flow = g.flow())) res += flow;
cout << res;
} | 25.030928 | 96 | 0.580725 | qawbecrdtey |
c2cc509b0044c492fe6e19de41aa3973bae6ba24 | 2,073 | cpp | C++ | DS Prep/Trees/Unusual Traversals/verticalOrder.cpp | Kanna727/My-C-git | 3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3 | [
"Apache-2.0"
] | 1 | 2021-04-05T18:55:20.000Z | 2021-04-05T18:55:20.000Z | DS Prep/Trees/Unusual Traversals/verticalOrder.cpp | Kanna727/My-C-git | 3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3 | [
"Apache-2.0"
] | null | null | null | DS Prep/Trees/Unusual Traversals/verticalOrder.cpp | Kanna727/My-C-git | 3fc81b24f07f8533e2b3881b8f1aeb442dca2bd3 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int data){
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
}
void printVerticalOrder(Node* root)
{
// Base case
if (!root)
return;
// Create a map and store vertical oder in
// map using function getVerticalOrder()
map < int,vector<int> > m;
int hd = 0;
// Create queue to do level order traversal.
// Every item of queue contains node and
// horizontal distance.
queue<pair<Node*, int> > que;
que.push(make_pair(root, hd));
while (!que.empty())
{
// pop from queue front
pair<Node *,int> temp = que.front();
que.pop();
hd = temp.second;
Node* node = temp.first;
// insert this node's data in vector of hash
m[hd].push_back(node->data);
if (node->left != NULL)
que.push(make_pair(node->left, hd-1));
if (node->right != NULL)
que.push(make_pair(node->right, hd+1));
}
// Traverse the map and print nodes at
// every horigontal distance (hd)
map< int,vector<int> > :: iterator it;
for (it=m.begin(); it!=m.end(); it++)
{
for (int i=0; i<it->second.size(); ++i)
cout << it->second[i] << " ";
cout << endl;
}
}
int main()
{
int n;
std::cout << "Enter no of node sin tree (except root node): ";
cin>>n;
map<int, Node*> m;
struct Node* root = NULL;
struct Node *parent, *child;
while(n--){
int p,c;
char lr;
cin>>p>>c>>lr;
if(m.find(p) == m.end()){
parent = newNode(p);
m[p] = parent;
if(!root) root = parent;
} else{
parent = m[p];
}
child = newNode(c);
lr == 'L' ? parent->left = child : parent->right = child;
m[c] = child;
}
printVerticalOrder(root);
cout<<endl;
system("pause");
return 0;
} | 23.033333 | 66 | 0.514713 | Kanna727 |
c2cd31a0dd762baae6346740673ce7f928ad4068 | 1,360 | cpp | C++ | components/source/RobotLeg.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | null | null | null | components/source/RobotLeg.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | null | null | null | components/source/RobotLeg.cpp | matheusvxf/Lighting-and-Shaders | c555cbae2a4c882a0d13d1b5e4daa5c39c020c32 | [
"MIT"
] | null | null | null | #include "RobotLeg.h"
#include "MatrixTransform.h"
#include "Cube.h"
#include "Robot.h"
#include "Config.h"
RobotLeg::RobotLeg()
{
}
RobotLeg::RobotLeg(double leg_width, double leg_height, double leg_depth)
{
MatrixTransform *m;
this->leg_width = leg_width;
this->leg_height = leg_height;
this->leg_depth = leg_depth;
this->angle = 0.0;
this->flag = true;
model_view = new Matrix4();
m = new MatrixTransform();
this->update_model_view();
m->setTransform(model_view);
m->add_child(new Cube(1));
this->add_child(m);
}
RobotLeg::~RobotLeg()
{
}
void RobotLeg::update()
{
double speed = owner->getSpeed();
double angular_speed = speed * 20;
if (flag)
{
angle += angular_speed * dt;
if (angle >= 30)
flag = false;
}
else
{
angle -= angular_speed * dt;
if (angle <= -30)
flag = true;
}
update_model_view();
}
void RobotLeg::update_model_view()
{
static Matrix4 rotationX, scale, translate, translate_inv;
translate.makeTranslate(0, -leg_height / 2.0 + leg_width / 2.0, 0);
rotationX.makeRotateX(angle);
translate_inv.makeTranslate(0, leg_height / 2.0 - leg_width / 2.0, 0);
scale.makeScale(leg_width, leg_height, leg_depth);
*model_view = translate_inv * rotationX * translate * scale;
} | 20 | 74 | 0.627206 | matheusvxf |
c2db002dc2057571014d5b16bd55699d793abd70 | 3,107 | cxx | C++ | registration/stats.cxx | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 15 | 2019-10-13T05:25:50.000Z | 2022-03-12T16:58:39.000Z | registration/stats.cxx | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 7 | 2020-10-22T20:05:42.000Z | 2020-11-18T19:41:03.000Z | registration/stats.cxx | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 1 | 2020-01-21T09:16:01.000Z | 2020-01-21T09:16:01.000Z | #include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include "stats.h"
#define print( v, size ) { for (int __i = 0; __i < size; __i++ ) { std::cout << v[ __i ]; if ( __i < ( size - 1 ) ) std::cout<< " " ;} std::cout << std::endl;}
using namespace std;
int Stats::maxSize = 10000;
int Stats::maxIterations = 10000;
float Stats::epsilon = 1e-6;
void Stats::estimateDistribution() {
const float esp = 1.59576912160573;
int iteration = 0;
const float epsilon = Stats::epsilon;
while ( iteration++ < Stats::maxIterations ) {
float sum1 = 0;
float sum2 = 0;
float sum3 = 0;
float sum4 = 0;
float sum5 = 0;
for ( int i = 0; i < this->size; i++ ) {
float f1 = ratio * chipdf( samples[ i ] / c1 ) / c1;
float f2 = ( 1.0 - ratio ) * chipdf( samples[ i ] / c2 ) / c2;
float t = f1/ ( f1 + f2 + 1e-16);
float p = this->samples[ i ] * this->weights[ i ];
sum1 += t * p;
sum2 += t * this->weights[ i ];
sum3 += ( 1.0 - t ) * p;
sum4 += ( 1.0 - t ) * this->weights[ i ];
sum5 += this->weights[ i ];
}
sum2 = max( sum2, epsilon);
sum3 = max( sum3, epsilon);
sum5 = max( sum5, epsilon);
float nc1 = max( epsilon, sum1 / sum2 / esp );
float nc2 = max( epsilon, sum3 / sum4 / esp );
float nRatio = max( epsilon, sum2 / sum5 );
if ( abs( ( c1 - nc1 ) / nc1 ) < 0.001
&& abs( ( c2 - nc2 ) / nc2 ) < 0.001
&& abs( ( nRatio - ratio ) / nRatio ) < 0.001 ) {
c1 = nc1;
c2 = nc2;
ratio = nRatio;
break;
} else {
c1 = nc1;
c2 = nc2;
ratio = nRatio;
}
}
return;
}
void Stats::displayParameters() {
int s = this->size;
cout << "c1=" << c1 << ",";
cout << "c2=" << c2 << ",";
cout << "r=" << ratio << ",";
cout << "nSamples=" << s;
double sum = accumulate( samples.begin(), samples.begin() + s , 0.0 );
double mean = sum / s;
double sq_sum = std::inner_product( samples.begin(), samples.begin() + s,
samples.begin(), 0.0 );
auto max = max_element( samples.begin(), samples.begin() + s );
double stdev = sqrt( sq_sum / s - mean * mean);
cout <<",max=" << *max
<< ",mean="<< mean << ",stdev=" << stdev << endl;
}
void Stats::saveHistogram( const char *file ) {
this->getHistogram();
std::fstream fs;
fs.open ( file, std::fstream::out | std::fstream::trunc );
for ( int i = 0; i < this->histogram.size(); i++ )
fs << histogram[ i ] << endl;
fs.close();
}
void Stats::saveSamples( const char *file, int subsampling ) {
std::fstream fs;
fs.open ( file, std::fstream::out | std::fstream::trunc );
for ( int i = 0; i < this->size; i++ )
if ( !( i % subsampling ) ) fs << this->samples[ i ] << endl;
fs.close();
}
void Stats::getHistogram( float binSize ) {
float max = 0;
for ( int i = 0; i < this->size; i++ ) {
if ( max < this->samples[ i ] ) max = this->samples[ i ];
}
int size = round( max / binSize ) + 1;
this->histogram.resize( size );
for ( int i = 0; i < size; i++ ) this->histogram[ i ] = 0;
for ( int i = 0; i < this->size; i++ ) {
int position = round( this->samples[ i ] / binSize );
this->histogram[ position ]++;
}
}
| 21.280822 | 159 | 0.551979 | valette |
c2db30ee45dc1115c3fbb8eb56f190faec8ca064 | 8,991 | cpp | C++ | src/vulkan/vulkan_swapchain.cpp | zfccxt/calcium | 9cc3a00904c05e675bdb5d35eef0f5356796e564 | [
"MIT"
] | null | null | null | src/vulkan/vulkan_swapchain.cpp | zfccxt/calcium | 9cc3a00904c05e675bdb5d35eef0f5356796e564 | [
"MIT"
] | null | null | null | src/vulkan/vulkan_swapchain.cpp | zfccxt/calcium | 9cc3a00904c05e675bdb5d35eef0f5356796e564 | [
"MIT"
] | null | null | null | #include "vulkan_swapchain.hpp"
#include <GLFW/glfw3.h>
#include "instrumentor.hpp"
#include "vulkan/vulkan_check.hpp"
#include "vulkan/vulkan_render_pass.hpp"
#include "vulkan/vulkan_swapchain_support_details.hpp"
#include "vulkan/vulkan_queue_family_indices.hpp"
#include "vulkan/vulkan_window_data.hpp"
namespace cl::vulkan {
#pragma warning(push)
#pragma warning(disable: 26812)
void VulkanSwapchain::CreateSwapchain() {
CALCIUM_PROFILE_FUNCTION();
VulkanSwapchainSupportDetails swapchain_support(window_data->context_data->physical_device, window_data->surface);
VkSurfaceFormatKHR surface_format = swapchain_support.ChooseBestSurfaceFormat();
VkPresentModeKHR present_mode = swapchain_support.ChooseBestPresentMode(window_data->enable_vsync);
extent = swapchain_support.ChooseSwapExtent(window_data->glfw_window);
image_format = surface_format.format;
// It's recommended to request at least one more swapchain image than the minimum supported, as this avoids having
// to wait for the driver to complete internal operations before we can acquire the next image to render to
image_count = swapchain_support.surface_capabilities.minImageCount + 1;
// Make sure we do not exceed the maximum number of swapchain images
// 0 is a special value indicating that there is no maximum
if (swapchain_support.surface_capabilities.maxImageCount > 0 && image_count > swapchain_support.surface_capabilities.maxImageCount) {
image_count = swapchain_support.surface_capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR create_info { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
create_info.surface = window_data->surface;
create_info.minImageCount = image_count;
create_info.imageFormat = surface_format.format;
create_info.imageColorSpace = surface_format.colorSpace;
create_info.imageExtent = extent;
// imageArrayLayers greater than 1 can be used for things like stereoscopic 3D
create_info.imageArrayLayers = 1;
// We are rendering directly to this swapchain - if we were rendering to a texture and performing postprocessing
// maybe we would use VK_IMAGE_USAGE_TRANSFER_DST_BIT
create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
// Next we must specify how to handle swapchain images that will be used across multiple queue families. If so, we
// would need to draw on the images in the graphics queue, then submit them on the present queue.
VulkanQueueFamilyIndices indices(window_data->context_data->physical_device, window_data->surface);
uint32_t queue_family_indices[] = { indices.graphics_family, indices.present_family };
if (indices.graphics_family == indices.present_family) {
// VK_SHARING_MODE_EXCLUSIVE offers the best performance
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
// No need to specify queueFamilyIndexCount or pQueueFamilyIndices as Vulkan assumes by default that you will be
// using the same queue for both graphics and presentation
}
else {
create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
create_info.queueFamilyIndexCount = 2;
create_info.pQueueFamilyIndices = queue_family_indices;
}
// To specify that we don't want a transform (such as a 90 degree rotation or horizontal flip), we can set this to
// the current transform supplied by default
create_info.preTransform = swapchain_support.surface_capabilities.currentTransform;
// compositeAlpha is used to specify whether the alpha channel should be used for blending with other windows in the
// window system. We don't need this, so we can ignore the alpha channel.
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create_info.presentMode = present_mode;
// clipped means we don't care about the colour of pixels that are obscured, for example by another window
create_info.clipped = VK_TRUE;
create_info.oldSwapchain = VK_NULL_HANDLE;
VK_CHECK(vkCreateSwapchainKHR(window_data->context_data->device, &create_info, window_data->context_data->allocator, &swapchain));
// We only ever specified a minimum number of swapchain images, so it's possible the swapchain we have created has
// more. Therefore we need to query the swapchain to find out how many images it contains.
// We don't need to destroy the images, since they are implicity destroyed when we destroy the swapchain - we are
// only retrieving image handles
vkGetSwapchainImagesKHR(window_data->context_data->device, swapchain, &image_count, nullptr);
images.resize(image_count);
vkGetSwapchainImagesKHR(window_data->context_data->device, swapchain, &image_count, images.data());
// Create image views
image_views.resize(images.size());
for (size_t i = 0; i < images.size(); ++i) {
VkImageViewCreateInfo create_info { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
create_info.image = images[i];
// We want to treat each image as a 2D texture
create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
create_info.format = image_format;
// Use default mapping for colour channels
// Note: Swizzling other than VK_COMPONENT_SWIZZLE_IDENTITY is not available on some incomplete Vulkan implementations, for example MoltenVK
create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
// subresourceRange describes image use, as well as which part of the image to access
create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
create_info.subresourceRange.baseMipLevel = 0;
create_info.subresourceRange.levelCount = 1;
create_info.subresourceRange.baseArrayLayer = 0;
create_info.subresourceRange.layerCount = 1;
VK_CHECK(vkCreateImageView(window_data->context_data->device, &create_info, window_data->context_data->allocator, &image_views[i]));
}
if (window_data->enable_depth_test) {
depth_buffer = new VulkanDepthBuffer(window_data->context_data, extent);
}
}
void VulkanSwapchain::DestroySwapchain() {
CALCIUM_PROFILE_FUNCTION();
vkDeviceWaitIdle(window_data->context_data->device);
if (window_data->enable_depth_test) {
delete depth_buffer;
}
for (auto image_view : image_views) {
vkDestroyImageView(window_data->context_data->device, image_view, window_data->context_data->allocator);
}
vkDestroySwapchainKHR(window_data->context_data->device, swapchain, window_data->context_data->allocator);
}
void VulkanSwapchain::RecreateSwapchain() {
CALCIUM_PROFILE_FUNCTION();
// If the window is minimized, wait until it is unminimized
int width = 0, height = 0;
glfwGetFramebufferSize(window_data->glfw_window, &width, &height);
while (width == 0 || height == 0) {
glfwGetFramebufferSize(window_data->glfw_window, &width, &height);
glfwWaitEvents();
}
vkDeviceWaitIdle(window_data->context_data->device);
DestroySwapchainFramebuffers();
vkDestroyRenderPass(window_data->context_data->device, window_data->swapchain.render_pass, window_data->context_data->allocator);
DestroySwapchain();
CreateSwapchain();
render_pass = CreateSwapchainRenderPass(*this);
CreateSwapchainFramebuffers();
}
void VulkanSwapchain::CreateSwapchainFramebuffers() {
CALCIUM_PROFILE_FUNCTION();
framebuffers.resize(image_views.size());
// Each image view needs its own framebuffer
for (size_t i = 0; i < image_views.size(); ++i) {
std::vector<VkImageView> attachments = { image_views[i] };
if (enable_depth_test) {
attachments.push_back(depth_buffer->depth_image_view);
}
VkFramebufferCreateInfo create_info { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
create_info.renderPass = render_pass;
create_info.attachmentCount = (uint32_t)attachments.size();
create_info.pAttachments = attachments.data();
create_info.width = extent.width;
create_info.height = extent.height;
create_info.layers = 1;
VK_CHECK(vkCreateFramebuffer(window_data->context_data->device, &create_info, window_data->context_data->allocator, &framebuffers[i]));
}
}
void VulkanSwapchain::DestroySwapchainFramebuffers() {
CALCIUM_PROFILE_FUNCTION();
for (auto framebuffer : framebuffers) {
vkDestroyFramebuffer(window_data->context_data->device, framebuffer, window_data->context_data->allocator);
}
}
void VulkanSwapchain::SetClearValue(const Colour& colour) {
CALCIUM_PROFILE_FUNCTION();
clear_values.clear();
VkClearValue colour_clear_value { };
colour_clear_value.color.float32[0] = colour.r;
colour_clear_value.color.float32[1] = colour.g;
colour_clear_value.color.float32[2] = colour.b;
colour_clear_value.color.float32[3] = colour.a;
clear_values.push_back(colour_clear_value);
if (enable_depth_test) {
VkClearValue depth_clear_value { };
depth_clear_value.depthStencil = { 1.0f, 0 };
clear_values.push_back(depth_clear_value);
}
}
#pragma warning(pop)
}
| 41.43318 | 144 | 0.779446 | zfccxt |
c2dbb966bf88dfb1beb05d2ff8ef147bdfeecd27 | 16,516 | hpp | C++ | TinySTL/utility.hpp | syn1w/TinySTL | 04961c8fcec560d23cb99d049d44ff1b88113118 | [
"MIT"
] | 7 | 2020-11-07T04:52:29.000Z | 2022-01-14T06:35:42.000Z | TinySTL/utility.hpp | vczn/TinySTL | ad9951cf38ada8f6903146f306f58778cb132b6a | [
"MIT"
] | 1 | 2021-04-14T10:13:43.000Z | 2021-04-14T10:13:43.000Z | TinySTL/utility.hpp | vczn/TinySTL | ad9951cf38ada8f6903146f306f58778cb132b6a | [
"MIT"
] | 2 | 2020-12-06T03:24:11.000Z | 2021-04-14T10:11:04.000Z | // Copyright (C) 2021 syn1w
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include "type_traits.hpp"
#include <type_traits>
#if _MSVC_LANG >= 201402L || __cplusplus >= 201402L
#define TINY_STL_CXX14
#endif // _MSVC_LANG >= 201402L
#if _MSVC_LANG >= 201703L || __cplusplus >= 201703L
#define TINY_STL_CXX17
#endif // _MSVC_LANG >= 201703L
#ifdef TINY_STL_CXX14
#define XCONSTEXPR14 constexpr
#else
#define XCONSTEXPR14 inline
#endif // TINY_STL_CXX14
#ifdef TINY_STL_CXX17
#define IFCONSTEXPR constexpr
#else
#define IFCONSTEXPR
#endif // TINY_STL_CXX17
namespace tiny_stl {
template <typename T>
constexpr remove_reference_t<T>&& move(T&& param) noexcept {
return static_cast<remove_reference_t<T>&&>(param);
}
template <typename T>
constexpr T&& forward(remove_reference_t<T>& param) noexcept {
return static_cast<T&&>(param);
}
template <typename T>
constexpr T&& forward(remove_reference_t<T>&& param) noexcept {
return static_cast<T&&>(param);
}
template <typename T>
inline void swap(T& lhs, T& rhs) noexcept(
is_nothrow_move_constructible_v<T>&& is_nothrow_move_assignable_v<T>) {
T tmp = tiny_stl::move(lhs);
lhs = tiny_stl::move(rhs);
rhs = tiny_stl::move(tmp);
}
template <typename FwdIter1, typename FwdIter2>
inline void iter_swap(FwdIter1 lhs, FwdIter2 rhs) {
swap(*lhs, *rhs);
}
// swap array lhs and rhs
template <typename T, std::size_t N>
inline void swap(T (&lhs)[N],
T (&rhs)[N]) noexcept(is_nothrow_swappable<T>::value) {
if (&lhs != &rhs) {
T* first1 = lhs;
T* last1 = lhs + N;
T* first2 = rhs;
for (; first1 != last1; ++first1, ++first2) {
tiny_stl::iter_swap(first1, first2);
}
}
}
template <typename T>
inline void swapADL(T& lhs, T& rhs) noexcept(is_nothrow_swappable<T>::value) {
// ADL: argument-dependent lookup
swap(lhs, rhs);
// std::swap(a, b);
// maybe =>
// using std::swap;
// swap(a, b);
}
struct piecewise_construct_t {
explicit piecewise_construct_t() = default;
};
constexpr piecewise_construct_t piecewise_construct{};
template <typename...>
class tuple;
template <typename T1, typename T2>
struct pair {
using first_type = T1;
using second_type = T2;
first_type first;
second_type second;
// (1)
template <typename U1 = T1, typename U2 = T2,
typename = enable_if_t<is_default_constructible<U1>::value &&
is_default_constructible<U2>::value>>
/*explicit*/ constexpr pair() : first(), second() {
}
// (2)
template <typename U1 = T1, typename U2 = T2,
typename = enable_if_t<is_copy_constructible<U1>::value &&
is_copy_constructible<U2>::value>,
enable_if_t<!is_convertible<const U1&, U1>::value ||
!is_convertible<const U2&, U2>::value,
int> = 0>
constexpr explicit pair(const T1& f, const T2& s) : first(f), second(s) {
}
// (2)
template <typename U1 = T1, typename U2 = T2,
typename = enable_if_t<is_copy_constructible<U1>::value &&
is_copy_constructible<U2>::value>,
enable_if_t<is_convertible<const U1&, U1>::value &&
is_convertible<const U2&, U2>::value,
int> = 0>
constexpr pair(const T1& f, const T2& s) : first(f), second(s) {
}
// (3)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, U1&&>::value &&
is_constructible<T2, U2&&>::value>,
enable_if_t<!is_convertible<U1&&, T1>::value ||
!is_convertible<U2&&, T2>::value,
int> = 0>
constexpr explicit pair(U1&& f, U2&& s)
: first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)) {
}
// (3)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, U1&&>::value &&
is_constructible<T2, U2&&>::value>,
enable_if_t<is_convertible<U1&&, T1>::value &&
is_convertible<U2&&, T2>::value,
int> = 0>
constexpr pair(U1&& f, U2&& s)
: first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)) {
}
// (4)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, const U1&>::value &&
is_constructible<T2, const U2&>::value>,
enable_if_t<!is_convertible<const U1&, T1>::value ||
!is_convertible<const U2&, T2>::value,
int> = 0>
constexpr explicit pair(const pair<U1, U2>& rhs)
: first(rhs.first), second(rhs.second) {
}
// (4)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, const U1&>::value &&
is_constructible<T2, const T2&>::value>,
enable_if_t<is_convertible<const U1&, T1>::value &&
is_convertible<const U2&, T2>::value,
int> = 0>
constexpr pair(const pair<U1, U2>& rhs)
: first(rhs.first), second(rhs.second) {
}
// (5)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, U1&&>::value &&
is_constructible<T2, U2&&>::value>,
enable_if_t<!is_convertible<U1&&, T1>::value ||
!is_convertible<U1&&, T1>::value,
int> = 0>
constexpr explicit pair(pair<U1, U2>&& rhs)
: first(tiny_stl::forward<U1>(rhs.first)),
second(tiny_stl::forward<U2>(rhs.second)) {
}
// (5)
template <typename U1, typename U2,
typename = enable_if_t<is_constructible<T1, U1&&>::value &&
is_constructible<T2, U2&&>::value>,
enable_if_t<is_convertible<U1&&, T1>::value &&
is_convertible<U1&&, T1>::value,
int> = 0>
constexpr pair(pair<U1, U2>&& rhs)
: first(tiny_stl::forward<U1>(rhs.first)),
second(tiny_stl::forward<U2>(rhs.second)) {
}
// (6)
template <typename... Args1, typename... Args2>
pair(piecewise_construct_t, tuple<Args1...> t1, tuple<Args2...> t2);
// (7)
pair(const pair& p) = default;
// (8)
pair(pair&&) = default;
// operator=()
pair& operator=(const pair& rhs) {
first = rhs.first;
second = rhs.second;
return *this;
}
template <typename U1, typename U2>
pair& operator=(const pair<U1, U2>& rhs) {
first = rhs.first;
second = rhs.second;
return *this;
}
pair&
operator=(pair&& rhs) noexcept(is_nothrow_move_assignable<T1>::value&&
is_nothrow_move_assignable<T2>::value) {
first = tiny_stl::forward<T1>(rhs.first);
second = tiny_stl::forward<T2>(rhs.second);
return *this;
}
template <typename U1, typename U2>
pair& operator=(pair<U1, U2>&& rhs) {
first = tiny_stl::forward<T1>(rhs.first);
second = tiny_stl::forward<T2>(rhs.second);
return *this;
}
void
swap(pair& rhs) noexcept(is_nothrow_swappable<first_type>::value&&
is_nothrow_swappable<second_type>::value) {
if (this != tiny_stl::addressof(rhs)) {
swapADL(first, rhs.first);
swapADL(second, rhs.second);
}
}
}; // class pair<T1, T2>
// if reference_wrap<T> -> T&
// else -> decay_t<T>
template <typename T1, typename T2>
constexpr pair<typename UnRefWrap<T1>::type, typename UnRefWrap<T2>::type>
make_pair(T1&& t1, T2&& t2) {
using Type_pair =
pair<typename UnRefWrap<T1>::type, typename UnRefWrap<T2>::type>;
return Type_pair(tiny_stl::forward<T1>(t1), tiny_stl::forward<T2>(t2));
}
template <typename T1, typename T2>
constexpr bool operator==(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (lhs.first == rhs.first && lhs.second == lhs.second);
}
template <typename T1, typename T2>
constexpr bool operator!=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (!(lhs == rhs));
}
template <typename T1, typename T2>
constexpr bool operator<(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (lhs.first < rhs.first) ||
(lhs.first == rhs.first && lhs.second < rhs.second);
}
template <typename T1, typename T2>
constexpr bool operator<=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (!(rhs < lhs));
}
template <typename T1, typename T2>
constexpr bool operator>(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (rhs < lhs);
}
template <typename T1, typename T2>
constexpr bool operator>=(const pair<T1, T2>& lhs, const pair<T1, T2>& rhs) {
return (!(lhs < rhs));
}
template <typename T1, typename T2>
inline void swap(pair<T1, T2>& lhs,
pair<T1, T2>& rhs) noexcept(noexcept(lhs.swap(rhs))) {
lhs.swap(rhs);
}
template <typename T>
struct tuple_size;
// tuple_size to pair
template <typename T1, typename T2>
struct tuple_size<pair<T1, T2>> : integral_constant<std::size_t, 2> {};
// tuple_size to tuple
template <typename... Ts>
struct tuple_size<tuple<Ts...>>
: integral_constant<std::size_t, sizeof...(Ts)> {};
template <typename T>
struct tuple_size<const T>
: integral_constant<std::size_t, tuple_size<T>::value> {};
template <typename T>
struct tuple_size<volatile T>
: integral_constant<std::size_t, tuple_size<T>::value> {};
template <typename T>
struct tuple_size<const volatile T>
: integral_constant<std::size_t, tuple_size<T>::value> {};
// tuple element
template <typename T>
struct AlwaysFalse : false_type {};
template <std::size_t Idx, typename Tuple>
struct tuple_element;
// tuple_element to tuple
template <std::size_t Idx>
struct tuple_element<Idx, tuple<>> {
static_assert(AlwaysFalse<integral_constant<std::size_t, Idx>>::value,
"tuple index out of range");
};
template <typename Head, typename... Tail>
struct tuple_element<0, tuple<Head, Tail...>> {
using type = Head;
using TupleType = tuple<Head, Tail...>;
};
template <std::size_t Idx, typename Head, typename... Tail>
struct tuple_element<Idx, tuple<Head, Tail...>>
: tuple_element<Idx - 1, tuple<Tail...>> {};
template <std::size_t Idx, typename Tuple>
struct tuple_element<Idx, const Tuple> : tuple_element<Idx, Tuple> {
using BaseType = tuple_element<Idx, Tuple>;
using type = add_const_t<typename BaseType::type>;
};
template <std::size_t Idx, typename Tuple>
struct tuple_element<Idx, volatile Tuple> : tuple_element<Idx, Tuple> {
using BaseType = tuple_element<Idx, Tuple>;
using type = add_volatile_t<typename BaseType::type>;
};
template <std::size_t Idx, typename Tuple>
struct tuple_element<Idx, const volatile Tuple> : tuple_element<Idx, Tuple> {
using BaseType = tuple_element<Idx, Tuple>;
using type = add_cv_t<typename BaseType::type>;
};
// tuple_element to pair
template <typename T1, typename T2>
struct tuple_element<0, pair<T1, T2>> {
using type = T1;
};
template <typename T1, typename T2>
struct tuple_element<1, pair<T1, T2>> {
using type = T2;
};
template <std::size_t Idx, typename T>
using tuple_element_t = typename tuple_element<Idx, T>::type;
template <typename Ret, typename Pair>
constexpr Ret pairGetHelper(Pair& p,
integral_constant<std::size_t, 0>) noexcept {
return (p.first);
}
template <typename Ret, typename Pair>
constexpr Ret pairGetHelper(Pair& p,
integral_constant<std::size_t, 1>) noexcept {
return (p.second);
}
// get<Idx>(pair<T1, T2>)
// (1) C++ 14
template <std::size_t Idx, typename T1, typename T2>
constexpr tuple_element_t<Idx, pair<T1, T2>>& get(pair<T1, T2>& p) noexcept {
using Ret = tuple_element_t<Idx, pair<T1, T2>>&;
return pairGetHelper<Ret>(p, integral_constant<std::size_t, Idx>{});
}
// (2) C++ 14
template <std::size_t Idx, typename T1, typename T2>
constexpr const tuple_element_t<Idx, pair<T1, T2>>&
get(const pair<T1, T2>& p) noexcept {
using Ret = const tuple_element_t<Idx, pair<T1, T2>>&;
return pairGetHelper<Ret>(p, integral_constant<std::size_t, Idx>{});
}
// (3) C++ 14
template <std::size_t Idx, typename T1, typename T2>
constexpr tuple_element_t<Idx, pair<T1, T2>>&& get(pair<T1, T2>&& p) noexcept {
using Ret = tuple_element_t<Idx, pair<T1, T2>>&&;
return tiny_stl::forward<Ret>(get<Idx>(p));
}
// (4) C++ 17
template <std::size_t Idx, typename T1, typename T2>
constexpr const tuple_element_t<Idx, pair<T1, T2>>&&
get(const pair<T1, T2>&& p) noexcept {
using Ret = const tuple_element_t<Idx, pair<T1, T2>>&&;
return tiny_stl::forward<Ret>(get<Idx>(p));
}
// (5) C++ 14
template <typename T1, typename T2>
constexpr T1& get(pair<T1, T2>& p) noexcept {
return get<0>(p);
}
// (6) C++ 14
template <typename T1, typename T2>
constexpr const T1& get(const pair<T1, T2>& p) noexcept {
return get<0>(p);
}
// (7) C++ 14
template <typename T1, typename T2>
constexpr T1&& get(pair<T1, T2>&& p) noexcept {
return get<0>(tiny_stl::move(p));
}
// (8) C++ 17
template <typename T1, typename T2>
constexpr const T1&& get(const pair<T1, T2>&& p) noexcept {
return get<0>(tiny_stl::move(p));
}
// (9) C++ 14
template <typename T1, typename T2>
constexpr T1& get(pair<T2, T1>& p) noexcept {
return get<1>(p);
}
// (10) C++ 14
template <typename T1, typename T2>
constexpr const T1& get(const pair<T2, T1>& p) noexcept {
return get<1>(p);
}
// (11) C++ 14
template <typename T1, typename T2>
constexpr T1&& get(pair<T2, T1>&& p) noexcept {
return get<1>(tiny_stl::move(p));
}
// (12) C++ 17
template <typename T1, typename T2>
constexpr const T1&& get(const pair<T2, T1>&& p) noexcept {
return get<1>(tiny_stl::move(p));
}
namespace extra {
// compress pair
template <typename T1, typename T2,
bool = is_empty<T1>::value && !is_final<T1>::value>
class compress_pair final : private T1 {
public:
using first_type = T1;
using second_type = T2;
private:
T2 second;
using Base = T1;
public:
constexpr explicit compress_pair() : T1(), second() {
}
template <typename U1, typename... U2>
compress_pair(U1&& f, U2&&... s)
: T1(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)...) {
}
T1& get_first() noexcept {
return *this;
}
const T1& get_first() const noexcept {
return *this;
}
T2& get_second() noexcept {
return second;
}
const T2& get_second() const noexcept {
return second;
}
};
template <typename T1, typename T2>
class compress_pair<T1, T2, false> {
public:
using first_type = T1;
using second_type = T2;
private:
T1 first;
T2 second;
public:
constexpr explicit compress_pair() : first(), second() {
}
template <typename U1, typename... U2>
compress_pair(U1&& f, U2&&... s)
: first(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)...) {
}
T1& get_first() noexcept {
return first;
}
const T1& get_first() const noexcept {
return first;
}
T2& get_second() noexcept {
return second;
}
const T2& get_second() const noexcept {
return second;
}
}; // class extra::compress_pair<T1, T2>
} // namespace extra
template <typename T>
struct TidyRAII { // strong exception guarantee
T* obj;
~TidyRAII() {
if (obj) {
obj->tidy();
}
}
};
struct in_place_t {
explicit in_place_t() = default;
};
constexpr in_place_t in_place{};
template <typename T>
struct in_place_type_t {
explicit in_place_type_t() = default;
};
template <typename T>
constexpr in_place_type_t<T> in_place_type{};
template <std::size_t I>
struct in_place_index_t {
explicit in_place_index_t() = default;
};
template <std::size_t I>
constexpr in_place_index_t<I> in_place_index{};
} // namespace tiny_stl
| 28.723478 | 80 | 0.607653 | syn1w |
c2dc2d42b2427109966c9edcf921908444869951 | 278 | hpp | C++ | include/miniberry/Port.hpp | krzysztof-magosa/MiniBerry | b4e4aac914d1813238fd3f43753c1e71488b8f90 | [
"MIT"
] | 1 | 2015-06-27T16:24:34.000Z | 2015-06-27T16:24:34.000Z | include/miniberry/Port.hpp | krzysztof-magosa/MiniBerry | b4e4aac914d1813238fd3f43753c1e71488b8f90 | [
"MIT"
] | null | null | null | include/miniberry/Port.hpp | krzysztof-magosa/MiniBerry | b4e4aac914d1813238fd3f43753c1e71488b8f90 | [
"MIT"
] | null | null | null | #ifndef MINIBERRY_PORT_HPP
#define MINIBERRY_PORT_HPP
#include <stdint.h>
namespace miniberry {
class Port
{
public:
volatile uint8_t* port;
volatile uint8_t* pin;
volatile uint8_t* ddr;
protected:
Port() {}
};
}
#endif
| 12.636364 | 31 | 0.604317 | krzysztof-magosa |
c2de0f33eb2441d11f77e79da71408d8381f5fa2 | 6,665 | cpp | C++ | Exam Practice/egemenkilic_THE3.cpp | egmnklc/Egemen-Files | 34d409fa593ec41fc0d2cb48e23658663a1a06db | [
"MIT"
] | null | null | null | Exam Practice/egemenkilic_THE3.cpp | egmnklc/Egemen-Files | 34d409fa593ec41fc0d2cb48e23658663a1a06db | [
"MIT"
] | null | null | null | Exam Practice/egemenkilic_THE3.cpp | egmnklc/Egemen-Files | 34d409fa593ec41fc0d2cb48e23658663a1a06db | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include "strutils.h"
using namespace std;
bool take_input(string input, string & sentence, bool & numeric_word, int & dot_count, string & new_sentence);
string reverse_string(string str)
{
string dummy = "";
for (int i = str.length()-1; i > -1; i--)
{
dummy += str.at(i);
}
return dummy;
}
void allInt(string input, bool & check, bool & numeric_word)
{
int count = 0;
for (int i = 0; i < input.length(); i++) {
check = isdigit(input.at(i));
if (check)
{
count++;
}
}
if (count == input.length())
{
numeric_word = true;
}
else if (input.at(input.length()-1) == '.' && count == input.length()-1)
{
numeric_word = true;
}
}
string process_word(string sentence, string & new_sentence)
{
for (int ba = 0; ba < sentence.length()-1; ba++)
{
if ( sentence.at(ba) == ' ' || isalpha(sentence.at(ba)) )
{
new_sentence += sentence.at(ba);
}
if (sentence.at(ba) == '.')
{
new_sentence += sentence.at(ba);
}
}
if (new_sentence.rfind(" ") == new_sentence.length()-1)
{
new_sentence = new_sentence.substr(0, new_sentence.length() - 1);
}
return new_sentence;
}
void create_word(string k, int space_count)
{
string word = "";
string reverse_word = "";
string final = "";
while (space_count != -1)
{
if (k.find(' ') == -1)
{
word = k;
}
else
{
word = k.substr(0, k.find(' '));
k = k.substr(k.find(' ')+1);
}
for (int x = word.length()-1; x != -1; x--)
{
if(word.at(x) != ' ')
{
reverse_word += word.at(x);
}
}
if (reverse_word == word)
{
final += word + " ";
}
else if (reverse_word != word)
{
final += "emordnilapton ";
}
reverse_word = "";
space_count-=1;
}
// cout << reverse_string(final) << "Will it work? " << endl;
// cout << "Final is: " << final << endl;
if (final.find(' ') == 0)
{
final = final.substr(1, final.rfind(' '));
}
if (final.at(final.rfind(' ')) == ' ')
{
final = final.substr(0, final.length()-1);
}
string reverse_final = "";
for (int c = final.length()-1; c > -1 ; c--)
{
reverse_final += final.at(c);
}
cout << reverse_final << endl;
final = "";
}
void palindrome(string m, int dot_count, int sentence_counter)
{
int k, space_count = 0;
string merhaba = "";
k = m.length() - 1;
while (k >= 0)
{
merhaba += m.substr(k, 1);
k -= 1;
}
cout << "Sentence ("<< sentence_counter << "/" << dot_count << "):"<< endl;
for (int f = 0; f < merhaba.length()-1; f++)
{
if (merhaba.at(f) == ' ')
{
space_count+=1;
}
}
create_word(merhaba, space_count);
merhaba = "";
}
bool take_input(string input, string & sentence, bool & numeric_word, int & dot_count, string & new_sentence, bool & cont)
{
bool check;
int cbt = 0;
cout << "Please enter the input sentences: "; cin >> input;
sentence += input;
allInt(input, check, numeric_word);
if (sentence.length() == 1 && sentence.at(0) == '@')
{
cout << "Input string should not be empty." << endl << endl;
input = " ", sentence = "", new_sentence = "", dot_count = 0, numeric_word = false, cbt = 0;
return false;
}
else
{
int hmt = 0;
while (input != "@")
{
cin >> input;
sentence += " " + input;
allInt(input, check, numeric_word);
}
ToLower(sentence);
for (int i = 0; i < sentence.length()-1; i++)
{
if (sentence.at(i) == '.')
{
dot_count+=1;
}
}
if (sentence.length() == 3 && sentence == ". @")
{
cout << "There should be no words without alphabetical characters." << endl << endl;
input = " ", sentence = "", new_sentence = "", dot_count = 0, hmt = 0,numeric_word = false, cbt = 0;
return false;
}
else if (dot_count == 0)
{
cout << "There should be at least one sentence." << endl << endl;
input = " ", sentence = "", new_sentence = "", dot_count = 0, hmt = 0,numeric_word = false, cbt = 0;
return false;
}
else if (numeric_word == true
|| sentence.at(sentence.find('.')) == sentence.at(sentence.find('.') + 1)
|| sentence.at(sentence.find('.')) == sentence.at(sentence.find('.') - 1))
{
cout << "There should be no words without alphabetical characters." << endl << endl;
input = " ", sentence = "", new_sentence = "", dot_count = 0, numeric_word = false, hmt = 0, cbt = 0;
return false;
}
cout << endl;
}
cont = false;
return true;
}
void another(string s, int dot_count)
{
string sentence = "", special = "";
string s_copy = s;
int sentence_counter = dot_count+1, space = 0;
while (s.find('.') != -1)
{
sentence = s.substr(0, s.find('.'));
s = s.substr(s.find('.')+1);
if (sentence.at(0) == ' ')
{
sentence = sentence.substr(1);
}
sentence_counter -= 1;
palindrome(sentence, dot_count, sentence_counter);
}
for (int o = 0; o < s.length()-1; o++)
{
if (s.at(o) == ' ')
{
space += 1;
}
}
if (s.find('.') == -1)
{
while (space != -1)
{
special = s_copy.substr(0, s_copy.find('.'));
s_copy = s_copy.substr(s_copy.find('.')+1);
if (special.at(0) == ' ')
{
special = special.substr(1);
}
space -= 1;
}
if (s.find('.') == -1)
{
palindrome(s, dot_count, 1);
}
}
}
int main()
{
string input = " ", sentence = "", new_sentence = "";
bool numeric_word = false, cont = true;
int dot_count = 0;
while (cont == true)
{
take_input(input, sentence, numeric_word, dot_count, new_sentence, cont);
}
process_word(sentence, new_sentence);
new_sentence = reverse_string(new_sentence);
new_sentence = new_sentence.substr(1);
another(new_sentence, dot_count);
return 0;
} | 25.342205 | 122 | 0.477119 | egmnklc |
c2df85fa013e02ad895a93a54a9010a49c3d98c9 | 1,495 | cpp | C++ | src/certificate/AccessDescription.cpp | LabSEC/libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-26T16:40:59.000Z | 2022-02-22T19:52:55.000Z | src/certificate/AccessDescription.cpp | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 14 | 2015-09-01T00:39:22.000Z | 2018-12-17T16:24:28.000Z | src/certificate/AccessDescription.cpp | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-31T19:17:37.000Z | 2021-01-04T13:38:35.000Z | #include <libcryptosec/certificate/AccessDescription.h>
AccessDescription::AccessDescription() {
}
AccessDescription::AccessDescription(ACCESS_DESCRIPTION *accessDescription) {
if(accessDescription->method) {
accessMethod = ObjectIdentifier(OBJ_dup(accessDescription->method));
}
if(accessDescription->location) {
accessLocation = GeneralName(accessDescription->location);
}
}
ACCESS_DESCRIPTION* AccessDescription::getAccessDescription() {
ACCESS_DESCRIPTION* accessDescription = ACCESS_DESCRIPTION_new();
accessDescription->method = accessMethod.getObjectIdentifier();
accessDescription->location = accessLocation.getGeneralName();
return accessDescription;
}
GeneralName AccessDescription::getAccessLocation()
{
return accessLocation;
}
ObjectIdentifier AccessDescription::getAccessMethod()
{
return accessMethod;
}
void AccessDescription::setAccessLocation(GeneralName accessLocation)
{
this->accessLocation = accessLocation;
}
void AccessDescription::setAccessMethod(ObjectIdentifier accessMethod)
{
this->accessMethod = accessMethod;
}
std::string AccessDescription::getXmlEncoded()
{
return this->getXmlEncoded("");
}
std::string AccessDescription::getXmlEncoded(std::string tab)
{
std::string ret;
ret = tab + "<accessDescription>\n";
ret += this->accessMethod.getXmlEncoded(tab + "\t");
ret += this->accessLocation.getXmlEncoded(tab + "\t");
ret += tab + "</accessDescription>\n";
return ret;
}
AccessDescription::~AccessDescription() {
}
| 24.508197 | 77 | 0.776589 | LabSEC |
123fb4a420334ec65d9a6526c2eff759062554d3 | 40,867 | cpp | C++ | src/object.cpp | Celissa/Legacy-Base | 027553da16342c4e31cebf5eaad6925fbaa5d5a5 | [
"CC-BY-3.0"
] | 1 | 2018-09-16T03:17:50.000Z | 2018-09-16T03:17:50.000Z | src/object.cpp | Celissa/Legacy-Base | 027553da16342c4e31cebf5eaad6925fbaa5d5a5 | [
"CC-BY-3.0"
] | null | null | null | src/object.cpp | Celissa/Legacy-Base | 027553da16342c4e31cebf5eaad6925fbaa5d5a5 | [
"CC-BY-3.0"
] | null | null | null | #include "system.h"
void read_string( FILE*, char**, char, int );
/*
* LOCAL_CONSTANTS
*/
const char* item_type_name [] = { "other", "light", "scroll", "wand",
"staff", "weapon", "gem", "spellbook", "treasure", "armor", "potion",
"reagent", "furniture", "trash", "cross", "container", "lock.pick",
"drink.container", "key", "food", "money", "key.ring", "boat",
"corpse", "bait", "fountain", "whistle", "trap",
"light.perm", "bandage", "bounty", "gate", "arrow", "skin",
"body.part", "chair", "table", "book", "pipe", "tobacco", "deck.cards",
"fire", "garrote", "shield", "herb", "flower", "jewelry", "ore",
"tree", "plant", "charm", "charm.bracelet", "toy", "apparel",
"dragon.scale", "shot", "bolt", "s.corpse", "musical", "poison",
"ancient.oak.tree", "statue" };
const char* item_values [] = { "unused", //other
"unused | unused | life time | unused", //light
"spell | level | duration | unused", //scroll
"spell | level | duration | charges", //wand
"spell | level | duration | charges", //staff
"enchantment | damdice | damside | weapon class", //weapon
"hardness | condition", //gem
"unused", //spell book
"unused", //treasure
"enchantment | armor value | bracer ac | unused", //armor
"spell | level | duration | unused", //potion
"charges", //reagent
"unused", //furniture
"unused", //trash
"unused", //cross
"capacity | container flags | key vnum | unused", //container
"pick modifier | unused", //pick modifier?
"capacity | contains | liquid | poisoned == -1", //drink container
"unused", //key
"food value | cooked? | unused | poisoned == -1", //food
"unused", //money
"unused", //key ring
"unused", //boat object?!?
"half-life| species | level of PC corpse | identity of PC", //corpse
"unused", //bait
"required to be -1 | unused | liquid | poisoned == -1", //fountain
"range | unused", //whistle
"trap flags | damdice | damside | unused", //trap, values unused?
"unused | unused | lifetime | unused", //permanent light, duration?
"unused", //bandage
"unused", //bounty?
"lifetime | unused", //gate
"unused | damdice | damside | shots", //arrow
"unused", //skin
"unused", //body part
"seats | unused", //chair
"unused", //table
"unused", //book
"unused", //pipe
"unused", //tobacco
"unused", //deck of cards
"timer | next item | unused", //fire
"unused", //garrote
"enchantment | armor value | bracer ac | unused", //shield
"unused", //herb
"unused", //flower
"unused", //jewelry
"unused", //ore
"unused", //tree
"unused", //plant
"unused", //charm
"unused", //charm bracelet
"unused", //toy
"unused", //apparel
"unused", //dragon.scale
"unused | damdice | damside | shots", //shot
"unused | damdice | damside | shots", //bolt
"half-life| species", //s.corpse
"unused", //musical
"unused", //poison
"unused", //ancient tree
"unused", //statues
};
const char *cont_flag_name [] = { "closeable", "pickproof", "closed",
"locked", "holding" };
/*
* OBJ_CLSS_DATA CLASS
*/
Synergy :: Synergy( )
{
record_new( sizeof( synergy ), MEM_OBJ_CLSS );
skill = empty_string;
clss = 0;
amount = 0;
}
Synergy :: ~Synergy( )
{
record_delete( sizeof( synergy ), MEM_OBJ_CLSS );
}
Obj_Clss_Data :: Obj_Clss_Data( )
{
record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS );
oprog = NULL;
date = -1;
count = 0;
}
Obj_Clss_Data :: ~Obj_Clss_Data( )
{
record_delete( sizeof( obj_clss_data ), MEM_OBJ_CLSS );
if( item_type == ITEM_MONEY )
update_coinage();
// memory leaks galore
}
Obj_Clss_Data :: Obj_Clss_Data( obj_clss_data* obj_copy, const char* name, int vnumber, const char* acreator )
{
char buf [ MAX_INPUT_LENGTH ];
record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS );
vnum = vnumber;
fakes = vnumber; // obj_copy->vnum ??
sprintf( buf, "%ss", name );
singular = alloc_string( name, MEM_OBJ_CLSS );
plural = alloc_string( buf, MEM_OBJ_CLSS );
before = alloc_string( obj_copy->before, MEM_OBJ_CLSS );
after = alloc_string( obj_copy->after, MEM_OBJ_CLSS );
long_s = alloc_string( obj_copy->long_s, MEM_OBJ_CLSS );
long_p = alloc_string( obj_copy->long_p, MEM_OBJ_CLSS );
prefix_singular = alloc_string( obj_copy->prefix_singular, MEM_OBJ_CLSS );
prefix_plural = alloc_string( obj_copy->prefix_plural, MEM_OBJ_CLSS );
creator = alloc_string( acreator, MEM_OBJ_CLSS );
last_mod = alloc_string( acreator, MEM_OBJ_CLSS );
item_type = obj_copy->item_type;
memcpy( extra_flags, obj_copy->extra_flags, sizeof( extra_flags ) );
wear_flags = obj_copy->wear_flags;
anti_flags = obj_copy->anti_flags;
restrictions = obj_copy->restrictions;
size_flags = obj_copy->size_flags;
materials = obj_copy->materials;
memcpy( affect_flags, obj_copy->affect_flags, sizeof( affect_flags ) );
layer_flags = obj_copy->layer_flags;
memcpy( value, obj_copy->value, sizeof( value ) );
weight = obj_copy->weight;
cost = obj_copy->cost;
level = obj_copy->level;
limit = obj_copy->limit;
repair = obj_copy->repair;
durability = obj_copy->durability;
blocks = obj_copy->blocks;
light = obj_copy->light;
memcpy( clss_synergy, obj_copy->clss_synergy, sizeof( clss_synergy ) );
religion_flags = obj_copy->religion_flags;
color = obj_copy->color;
count = 0;
date = time(0);
copy_extras( extra_descr, obj_copy->extra_descr );
oprog = NULL; // one day dupe oprogs
}
Obj_Clss_Data :: Obj_Clss_Data( const char* name, int vnumber, const char* acreator )
{
char buf [ MAX_INPUT_LENGTH ];
record_new( sizeof( obj_clss_data ), MEM_OBJ_CLSS );
vnum = vnumber;
fakes = vnumber;
sprintf( buf, "%ss", name );
singular = alloc_string( name, MEM_OBJ_CLSS );
plural = alloc_string( buf, MEM_OBJ_CLSS );
before = empty_string;
after = empty_string;
long_s = empty_string;
long_p = empty_string;
prefix_singular = empty_string;
prefix_plural = empty_string;
creator = alloc_string( acreator, MEM_OBJ_CLSS );
last_mod = alloc_string( acreator, MEM_OBJ_CLSS );
item_type = ITEM_TRASH;
vzero( extra_flags, 2 );
wear_flags = 0;
set_bit( &wear_flags, ITEM_TAKE );
anti_flags = 0;
restrictions = 0;
size_flags = 0;
materials = 0;
vzero( affect_flags, AFFECT_INTS );
layer_flags = 0;
vzero( value, 4 );
weight = 0;
cost = 0;
level = 1;
limit = -1;
repair = 10;
durability = 1000;
blocks = 0;
light = 0;
vzero( clss_synergy, MAX_NEW_CLSS );
religion_flags = 0;
color = ANSI_NORMAL;
count = 0;
date = time(0);
oprog = NULL;
}
/*
* Obj_Clss_Data Synergy Stuff
*/
void Obj_Clss_Data :: HandleSynergyEdit( wizard_data* ch, char* argument )
{
if( *argument == '\0' ) {
// display the synergies
if( is_empty( synergy_array ) ) {
page( ch, "There are no synergies on %s.\r\n", this->Name( ) );
return;
}
DisplaySynergyList( ch );
return;
} else if( exact_match( argument, "delete" ) ) {
if( *argument == '\0' ) {
page( ch, "Which synergy do you wish to delte?\r\n" );
page( ch, "Syntax: <unsure yet>\r\n" );
return;
}
if( is_empty( synergy_array ) ) {
page( ch, "There are no synergies to delete.\r\n" );
return;
}
int i = atoi( argument );
if( i < 1 || i > synergy_array ) {
page( ch, "Selected synergy '%s' out of range [1-%d].\r\n", argument, synergy_array.size );
return;
}
Synergy* syn = synergy_array[i-1];
if( syn != NULL ) {
synergy_array -= syn;
page( ch, "Synergy #%i deleted.\r\n", i );
delete syn;
} else {
send( ch, "[BUG] Synergy #%i not found.\r\n", i );
}
return;
} else if( exact_match( argument, "new" ) ) {
Synergy* syn = new Synergy;
// add the synergy to the array for that object class
// then make the immortal edit it
ch->SynergyEdit = syn;
synergy_array += syn;
page( ch, "Synergy created and you are editting it.\r\n" );
return;
} else if( isdigit( *argument ) ) {
int i = atoi( argument );
if( i < 1 || i > synergy_array ) {
page( ch, "Selected synergy '%s' is out of range [1-%d].\r\n", argument, synergy_array.size );
return;
}
synergy* syn = synergy_array[i-1];
if( syn != NULL ) {
ch->SynergyEdit = syn;
page( ch, "You are now editting synergy #%i.\r\n", i );
} else {
send( ch, "[BUG] Synergy #%i not found.\r\n", i );
}
return;
} else {
send( ch, "Syntax: <unknown>\r\n" );
}
}
void Obj_Clss_Data :: DisplaySynergyList( wizard_data* ch )
{
bool found = false;
if( is_empty( synergy_array ) ) {
page( ch, "%s has no synergies.\r\n", Name( ) );
return;
}
for( int i = 0; i < synergy_array; i++ ) {
synergy* syn = synergy_array[i];
if( !found ) {
page( ch, "Skill specific synergies on %s.\r\n", Name( ) );
page_underlined( ch, " # Skill Amount Class\r\n" );
found = true;
}
page( ch, "[%3i] %-26s%6i %s\r\n", i+1, syn->skill, syn->amount, clss_table[ syn->clss ].name );
}
return;
}
void Obj_Clss_Data :: HandleSynergySet( wizard_data* ch, char* argument )
{
synergy* syn = ch->SynergyEdit;
if( *argument == '\0' ) {
HandleSynergyStat( ch );
return;
}
if( syn == NULL ) {
send( ch, "You are not currently editting a synergy.\r\n" );
return;
}
class int_field int_list [] = {
{ "amount", -20000, 100, &syn->amount },
{ "", 0, 0, NULL },
};
if( process( int_list, ch, "synergy", argument ) )
return;
if( exact_match( argument, "skill" ) ) {
int skill;
if( ( skill = skill_index( argument ) ) != -1 ) {
syn->skill = skill_table[skill].name;
send( ch, "%s now synergizes %s.\r\n", Name( ), skill_table[skill].name );
return;
}
else {
send( ch, "%s is an invalid skill.\r\n", argument );
return;
}
}
if( exact_match( argument, "class" ) ) {
for( int i = 0; i < MAX_CLSS; i++ ) {
if( fmatches( argument, clss_table[i].name ) ) {
syn->clss = i;
send( ch, "%s now synergizes with %s class skill set.\r\n", Name( ), clss_table[i].name );
return;
}
}
}
send( ch, "Unknown parameters\r\n" );
return;
}
void Obj_Clss_Data :: HandleSynergyStat( wizard_data* ch )
{
synergy* syn = ch->SynergyEdit;
if( syn == NULL ) {
send( ch, "You are not editting any synergy right now.\r\n" );
return;
}
page_title( ch, "Object %s - Synergy Being Editted", Name( ) );
page( ch, "\r\n" );
page( ch, " Skill: %s\r\n", syn->skill );
page( ch, " Amount: %i\r\n", syn->amount );
page( ch, " Class: %s\r\n", clss_table[ syn->clss ].name );
return;
}
bool Synergy :: Save( FILE* fp )
{
fprintf( fp, "%d\n", 1 ); // version
fprintf( fp, "%s~\n", skill );
fprintf( fp, "%d\n", amount );
fprintf( fp, "%d\n", clss );
return true;
}
bool Synergy :: Load( FILE* fp )
{
int version = fread_number( fp );
skill = fread_string( fp, MEM_OBJ_CLSS );
amount = fread_number( fp );
clss = fread_number( fp );
return true;
}
void do_synedit( char_data* ch, char* argument )
{
wizard_data* imm = wizard( ch );
if( imm == NULL )
return;
obj_clss_data* obj = imm->obj_edit;
if( obj == NULL ) {
send( ch, "You need to be editting an object to work on synergies.\r\n" );
return;
}
obj->HandleSynergyEdit( imm, argument );
}
void do_synset( char_data* ch, char* argument )
{
wizard_data* imm = wizard( ch );
if( imm == NULL )
return;
obj_clss_data* obj = imm->obj_edit;
if( obj == NULL ) {
send( ch, "You need to be editting an object to work on synergies.\r\n" );
return;
}
if( imm->SynergyEdit == NULL ) {
send( ch, "You are not editting a synergy.\r\n" );
return;
}
obj->HandleSynergySet( imm, argument );
}
/*
* OBJ_DATA
*/
int compare_vnum( obj_data* obj1, obj_data* obj2 )
{
int a = obj1->pIndexData->vnum;
int b = obj2->pIndexData->vnum;
return( a < b ? -1 : ( a > b ? 1 : 0 ) );
}
Obj_Data :: Obj_Data( obj_clss_data* obj_clss )
{
record_new( sizeof( obj_data ), MEM_OBJECT );
valid = OBJ_DATA;
extra_descr = NULL;
array = NULL;
save = NULL;
owner = NULL;
source = empty_string;
label = empty_string;
reset_mob_vnum = 0;
reset_room_vnum = 0;
position = WEAR_NONE;
layer = 0;
unjunked = 0;
pIndexData = obj_clss;
insert( obj_list, this, binary_search( obj_list, this, compare_vnum ) );
}
Obj_Data :: ~Obj_Data( )
{
record_delete( sizeof( obj_data ), MEM_OBJECT );
obj_list -= this;
}
/*
* SUPPORT FUNCTIONS
*/
bool can_extract( obj_clss_data* obj_clss, char_data* ch )
{
/*
if( obj_clss->vnum == 1 ) {
send( ch, "You may not delete the template object.\r\n" );
return FALSE;
}
*/
for( int i = 0; i < obj_list; i++ ) {
if( obj_list[i]->Is_Valid() && obj_list[i]->pIndexData == obj_clss ) {
send( ch, "You must destroy all examples of %s first.\r\n", obj_clss );
return FALSE;
}
}
if( generic_search( ch, obj_clss, obj_clss->vnum, OBJECT, true ) ) {
send( ch, "You must remove all references of that object first.\r\n" );
return FALSE;
}
return TRUE;
}
/*
* LOW LEVEL OBJECT ROUTINES
*/
int coin_value_in_condition( obj_data* obj )
{
int cost = 0;
if( obj == NULL )
return 0;
cost = obj->Cost( );
if( obj->pIndexData->item_type == ITEM_ARMOR || obj->pIndexData->item_type == ITEM_SHIELD || obj->pIndexData->item_type == ITEM_WEAPON )
cost /= 12;
else
cost /= 4;
cost = cost*obj->condition/obj->pIndexData->durability*sqr(4-obj->rust)/16;
switch( obj->pIndexData->item_type ) {
case ITEM_STAFF :
case ITEM_WAND :
if( obj->value[0] != 0 )
cost = cost*(1+obj->value[3]/obj->value[0])/2;
break;
case ITEM_DRINK_CON :
cost += obj->value[1]*liquid_table[ obj->value[2] ].cost/100;
break;
}
cost += cost*12/(3+obj->number);
return cost;
}
bool is_same( obj_data* obj1, obj_data* obj2 )
{
obj_array* array;
if( obj1->pIndexData != obj2->pIndexData )
return FALSE;
if( obj1->pIndexData->item_type == ITEM_MONEY )
return TRUE; // perhaps money-specific checks later if you want 'dented gold coin' etc
if( !is_empty( obj1->contents ) || !is_empty( obj2->contents )
|| !is_empty( obj1->affected ) || !is_empty( obj2->affected )
|| !is_empty( obj1->events ) || !is_empty( obj2->events )
|| obj1->extra_flags[0] != obj2->extra_flags[0]
|| obj1->extra_flags[1] != obj2->extra_flags[1]
|| obj1->timer != obj2->timer
|| obj1->condition != obj2->condition
|| obj1->materials != obj2->materials
|| obj1->rust != obj2->rust
|| obj1->owner != obj2->owner
|| obj1->weight != obj2->weight
|| obj1->unjunked != obj2->unjunked
|| obj1->position != obj2->position )
return FALSE;
for( int i = 0; i < 4; i++ )
if( obj1->value[i] != obj2->value[i] )
return FALSE;
if( obj2->save != NULL ) {
if( obj1->save == NULL ) {
obj1->save = obj2->save;
obj2->save = NULL;
array = &obj1->save->save_list;
for( int i = 0; ; i++ ) {
if( i >= array->size )
panic( "Is_Same: Object not in save array." );
if( obj2 == array->list[i] ) {
array->list[i] = obj1;
break;
}
}
} else if( obj1->save != obj2->save )
return FALSE;
}
if( obj1->pIndexData->vnum == OBJ_BALL_OF_LIGHT && range( 0, obj1->value[2] / 5, 10 ) != range( 0, obj2->value[2] / 5, 10 ) )
return FALSE;
if( obj1->pIndexData->vnum == OBJ_CORPSE_LIGHT && ( obj1->value[3] > 0 ? range( 0, 6 * obj1->value[2] / obj1->value[3], 6 ) : 6 ) != ( obj2->value[3] > 0 ? range( 0, 6 * obj2->value[2] / obj2->value[3], 6 ) : 6 ) )
return FALSE;
if( obj1->pIndexData->item_type == ITEM_CORPSE )
return FALSE;
if( obj1->source != obj2->source && strcmp( obj1->source, obj2->source ) != 0 )
return FALSE;
return( !strcmp( obj1->label, obj2->label ) );
}
/*
* OWNERSHIP
*/
bool Obj_Data :: Belongs( char_data* ch )
{
return( owner == NULL || ( ch != NULL && ch->pcdata != NULL
&& ch->pcdata->pfile == owner ) );
}
void set_owner( pfile_data* pfile, thing_array& array, bool force_transfer )
{
obj_data* obj;
for( int i = 0; i < array; i++ ) {
if( ( obj = object( array[i] ) ) != NULL ) {
if ( obj->pIndexData->item_type != ITEM_MONEY ) {
if( obj->owner == NULL || force_transfer )
obj->owner = pfile;
}
set_owner( pfile, obj->contents, force_transfer );
}
}
}
void set_owner( obj_data* obj, pfile_data* buyer )
{
obj_data* content;
if( obj->pIndexData->item_type != ITEM_MONEY )
obj->owner = buyer;
for( int i = 0; i < obj->contents; i++ )
if( ( content = object( obj->contents[i] ) ) != NULL )
set_owner( content, buyer );
}
void set_owner( obj_data* obj, char_data* buyer, char_data* seller )
{
obj_data* content;
if( obj->Belongs( seller ) && obj->pIndexData->item_type != ITEM_MONEY )
obj->owner = ( ( buyer != NULL && buyer->pcdata != NULL )
? buyer->pcdata->pfile : NULL );
for( int i = 0; i < obj->contents; i++ )
if( ( content = object( obj->contents[i] ) ) != NULL )
set_owner( content, buyer, seller );
}
/*
* MISC ROUTINES
*/
void condition_abbrev( char* tmp, obj_data* obj, char_data* ch )
{
const char* abbrev [] = { "wls", "dmg", "vwn", "wrn", "vsc", "scr",
"rea", "goo", "vgo", "exc" };
int i;
i = 1000*obj->condition/obj->pIndexData->durability;
i = range( 0, i/100, 9 );
sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) )
: ( i > 2 ? yellow( ch ) : red( ch ) ), abbrev[i], normal( ch ) );
return;
}
void age_abbrev( char* tmp, obj_data*, char_data* )
{
sprintf( tmp, " " );
return;
}
const char* obj_data :: repair_condition_name( char_data* ch, bool ansi )
{
static char tmp [ ONE_LINE ];
int i;
const char* txt;
i = 1000 * repair_condition(this) / pIndexData->durability;
i = range( 0, i/100, 9 );
if( i == 0 ) txt = "worthless";
else if( i == 1 ) txt = "damaged";
else if( i == 2 ) txt = "very worn";
else if( i == 3 ) txt = "worn";
else if( i == 4 ) txt = "very scratched";
else if( i == 5 ) txt = "scratched";
else if( i == 6 ) txt = "reasonable";
else if( i == 7 ) txt = "good";
else if( i == 8 ) txt = "very good";
else txt = "excellent";
if( !ansi || ch->pcdata == NULL || ch->pcdata->terminal != TERM_ANSI )
return txt;
sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) )
: ( i > 2 ? yellow( ch ) : red( ch ) ), txt, normal( ch ) );
return tmp;
}
const char* obj_data :: condition_name( char_data* ch, bool ansi )
{
static char tmp [ ONE_LINE ];
int i;
const char* txt;
i = 1000*condition/pIndexData->durability;
i = range( 0, i/100, 9 );
if( i == 0 ) txt = "worthless";
else if( i == 1 ) txt = "damaged";
else if( i == 2 ) txt = "very worn";
else if( i == 3 ) txt = "worn";
else if( i == 4 ) txt = "very scratched";
else if( i == 5 ) txt = "scratched";
else if( i == 6 ) txt = "reasonable";
else if( i == 7 ) txt = "good";
else if( i == 8 ) txt = "very good";
else txt = "excellent";
if( !ansi || ch->pcdata == NULL || ( ch->pcdata->terminal != TERM_ANSI
&& ch->pcdata->terminal != TERM_MXP ) )
return txt;
sprintf( tmp, "%s%s%s", i > 4 ? ( i > 7 ? blue( ch ) : green( ch ) )
: ( i > 2 ? yellow( ch ) : red( ch ) ), txt, normal( ch ) );
return tmp;
}
/*
* WEIGHT/NUMBER ROUTINES
*/
int Obj_Data :: Cost( )
{
int cost = pIndexData->cost;
int i;
if( ( pIndexData->item_type == ITEM_WEAPON || pIndexData->item_type == ITEM_ARMOR || pIndexData->item_type == ITEM_SHIELD ) && is_set( extra_flags, OFLAG_IDENTIFIED ) )
cost += cost*sqr( URANGE( 0, value[0], 5 ) )/2;
if( ( pIndexData->item_type != ITEM_WEAPON && pIndexData->item_type != ITEM_ARMOR && pIndexData->item_type != ITEM_SHIELD ) || !is_set( pIndexData->extra_flags, OFLAG_RANDOM_METAL ) )
return cost;
for( i = MAT_BRONZE; i <= MAT_LIRIDIUM; i++ )
if( is_set( &pIndexData->materials, i ) )
return cost*material_table[i].cost;
return cost;
}
/*
* OBJECT UTILITY ROUTINES
*/
void enchant_object( obj_data* obj )
{
int i;
if( obj->pIndexData->item_type == ITEM_WAND
|| obj->pIndexData->item_type == ITEM_STAFF )
obj->value[3] = number_range( 0, obj->pIndexData->value[3] );
if( ( obj->pIndexData->item_type == ITEM_WEAPON
|| obj->pIndexData->item_type == ITEM_SHIELD
|| obj->pIndexData->item_type == ITEM_ARMOR )
&& !is_set( obj->extra_flags, OFLAG_NO_ENCHANT ) ) {
if( ( i = number_range( 0, 1000 ) ) >= 900 ) {
obj->value[0] = ( i > 950 ? ( i > 990 ? ( i == 1000 ? 3 : 2 ) : 1 )
: ( i < 910 ? ( i == 900 ? -3 : -2 ) : -1 ) );
set_bit( obj->extra_flags, OFLAG_MAGIC );
if( obj->value[0] < 0 )
set_bit( obj->extra_flags, OFLAG_NOREMOVE );
}
}
}
void rust_object( obj_data* obj, int chance )
{
int i;
if( obj->metal( ) && !is_set( obj->extra_flags, OFLAG_RUST_PROOF ) && number_range( 0, 100 ) < chance ) {
i = number_range( 0, 1000 );
obj->rust = ( i > 700 ? 1 : ( i > 400 ? 2 : 3 ) );
}
if( obj->pIndexData->item_type == ITEM_WEAPON || obj->pIndexData->item_type == ITEM_SHIELD || obj->pIndexData->item_type == ITEM_ARMOR ) {
obj->age = number_range( 0, obj->pIndexData->durability/25-1 );
obj->condition = number_range( 1, repair_condition( obj ) );
}
}
void set_alloy( obj_data* obj, int level )
{
int metal;
if( !is_set( obj->pIndexData->extra_flags, OFLAG_RANDOM_METAL ) )
return;
for( metal = MAT_BRONZE; metal <= MAT_LIRIDIUM; metal++ )
if( is_set( &obj->materials, metal ) )
break;
if( metal > MAT_LIRIDIUM ) {
metal = MAT_BRONZE;
for( ; ; ) {
if( metal == MAT_LIRIDIUM || number_range( 0, level+75 ) > level-10*(metal-MAT_BRONZE) )
break;
metal++;
}
set_bit( &obj->materials, metal );
}
if( obj->pIndexData->item_type == ITEM_ARMOR || obj->pIndexData->item_type == ITEM_SHIELD )
obj->value[1] = obj->pIndexData->value[1]-MAT_BRONZE+metal;
}
obj_data* create( obj_clss_data* obj_clss, int number )
{
obj_data* obj;
if( obj_clss == NULL ) {
roach( "Create_object: NULL obj_clss." );
return NULL;
}
obj = new obj_data( obj_clss );
obj->singular = obj_clss->singular;
obj->plural = obj_clss->plural;
obj->after = obj_clss->after;
obj->before = obj_clss->before;
obj->extra_flags[0] = obj_clss->extra_flags[0];
obj->extra_flags[1] = obj_clss->extra_flags[1];
if( is_set( &obj_clss->size_flags, SFLAG_CUSTOM ) )
obj->size_flags = -1;
else
obj->size_flags = obj_clss->size_flags;
obj->value[0] = obj_clss->value[0];
obj->value[1] = obj_clss->value[1];
obj->value[2] = obj_clss->value[2];
obj->value[3] = obj_clss->value[3];
obj->condition = obj_clss->durability;
obj->materials = obj_clss->materials;
obj->weight = obj_clss->weight;
obj->age = 0;
obj->rust = 0;
obj->timer = 0;
if( number > 0 )
obj_clss->count += number;
else
number = -number;
obj->number = number;
obj->selected = number;
obj->shown = number;
switch( obj_clss->item_type ) {
case ITEM_MONEY:
obj->value[0] = obj->pIndexData->cost;
break;
case ITEM_FIRE:
case ITEM_GATE:
obj->timer = obj->value[0];
break;
}
if( obj_clss->item_type != ITEM_ARMOR && obj_clss->item_type != ITEM_WEAPON
&& obj_clss->item_type != ITEM_SHIELD
&& !strcmp( obj_clss->before, obj_clss->after )
&& obj_clss->plural[0] != '{' && obj_clss->singular[0] != '{' )
set_bit( obj->extra_flags, OFLAG_IDENTIFIED );
return obj;
}
obj_data* duplicate( obj_data* copy, int num )
{
obj_data* obj;
obj_clss_data* obj_clss = copy->pIndexData;
obj = new obj_data( obj_clss );
char* string_copy [] = { copy->singular, copy->plural, copy->before, copy->after };
char** string_obj [] = { &obj->singular, &obj->plural, &obj->before, &obj->after };
char* string_index [] = { obj_clss->singular, obj_clss->plural, obj_clss->before, obj_clss->after };
for( int i = 0; i < 4; i++ )
*string_obj[i] = ( string_copy[i] != string_index[i] ? alloc_string( string_copy[i], MEM_OBJECT ) : string_index[i] );
obj->age = copy->age;
obj->extra_flags[0] = copy->extra_flags[0];
obj->extra_flags[1] = copy->extra_flags[1];
obj->size_flags = copy->size_flags;
obj->value[0] = copy->value[0];
obj->value[1] = copy->value[1];
obj->value[2] = copy->value[2];
obj->value[3] = copy->value[3];
obj->weight = copy->weight;
obj->condition = copy->condition;
obj->rust = copy->rust;
obj->timer = copy->timer;
obj->materials = copy->materials;
obj->owner = copy->owner;
obj->temp = copy->temp;
obj->number = num;
obj->selected = num;
obj->shown = num;
obj_clss->count += num;
if( copy->save != NULL ) {
copy->save->save_list += obj;
obj->save = copy->save;
}
return obj;
}
/*
* OBJECT TRANSFER FUNCTIONS
*/
int drop_contents( obj_data* obj )
{
room_data* room;
if( obj == NULL || obj->array == NULL || (room = Room(obj->array->where)) == NULL )
return 0;
int num = 0;
for( int i = obj->contents.size - 1; i >= 0; i-- ) {
obj_data *content = object(obj->contents[i]);
if (!content || !content->Is_Valid())
continue;
content->From(content->number);
content->To(room);
num++;
}
return num;
}
/*
* OBJECT EXTRACTION ROUTINES
*/
void Obj_Data :: Extract( int i )
{
if( i < number ) {
remove_weight( this, i );
number -= i;
if( boot_stage == BOOT_COMPLETE )
pIndexData->count -= i;
return;
}
if( i > number ) {
roach( "Extract( Obj ): number > amount." );
roach( "-- Obj = %s", this );
roach( "-- Number = %d", i );
roach( "-- Amount = %d", number );
}
Extract( );
}
void Obj_Data :: Extract( )
{
obj_array* array;
int i;
if( !Is_Valid( ) ) {
roach( "Extracting invalid object." );
roach( "-- Valid = %d", valid );
roach( "-- Obj = %s", this );
return;
}
if( pIndexData->vnum == OBJ_CORPSE_PC )
corpse_list -= this;
if( this->array != NULL )
From( number );
extract( contents );
if( boot_stage == BOOT_COMPLETE )
pIndexData->count -= number;
clear_queue( this );
stop_events( this );
if( save != NULL ) {
array = &save->save_list;
for( i = 0; ; i++ ) {
if( i >= array->size )
panic( "Extract: Object not found in save array." );
if( this == array->list[i] ) {
array->list[i] = NULL;
save = NULL;
break;
}
}
}
delete_list( affected );
free_string( source, MEM_OBJECT );
if( singular != pIndexData->singular )
free_string( singular, MEM_OBJECT );
if( plural != pIndexData->plural )
free_string( plural, MEM_OBJECT );
if( after != pIndexData->after )
free_string( after, MEM_OBJECT );
if( before != pIndexData->before )
free_string( before, MEM_OBJECT );
timer = -2;
valid = -1;
extracted += this;
}
/*
* DISK ROUTINES
*/
void fix( obj_clss_data* obj_clss )
{
if( obj_clss->item_type == ITEM_SCROLL )
set_bit( &obj_clss->materials, MAT_PAPER );
for( int i = 0; i < MAX_ANTI; i++ ) {
if( !strncasecmp( anti_flags[i], "unused", 6 ) )
remove_bit( &obj_clss->anti_flags, i );
}
if( obj_clss->color < COLOR_DEFAULT || obj_clss->color > MAX_COLOR )
obj_clss->color = COLOR_DEFAULT;
return;
}
void load_objects( void )
{
FILE* fp;
obj_clss_data* obj_clss;
oprog_data* oprog;
char letter;
int i;
int vnum;
int count = 0;
bool boot_old = false, boot_tfh = false;
int version = 0;
echo( "Loading Objects ...\r\n" );
vzero( obj_index_list, MAX_OBJ_INDEX );
fp = open_file( AREA_DIR, OBJECT_FILE, "rb", TRUE );
char *word = fread_word( fp );
if( !strcmp( word, "#M2_OBJECTS" ) ) {
version = fread_number( fp );
} else if( !strcmp( word, "#OLD_OBJECTS" ) ) {
log("... old style object file");
boot_old = true;
} else if( !str_cmp( word, "#TFH_OBJECTS" ) ) {
log("... tfh style object file");
boot_tfh = true;
} else if( !strcmp( word, "#OBJECTS" ) ) {
// version 0 object file
} else {
panic( "Load_objects: header not found" );
}
log( " * %-20s : v%d :", OBJECT_FILE, version );
for( ; ; ) {
letter = fread_letter( fp );
if( letter != '#' )
panic( "Load_objects: # not found." );
if( ( vnum = fread_number( fp ) ) == 0 )
break;
if( vnum < 0 || vnum >= MAX_OBJ_INDEX )
panic( "Load_objects: vnum out of range." );
if( obj_index_list[vnum] != NULL )
panic( "Load_objects: vnum %d duplicated.", vnum );
obj_clss = new obj_clss_data;
obj_index_list[vnum] = obj_clss;
obj_clss->vnum = vnum;
obj_clss->fakes = vnum;
obj_clss->singular = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->plural = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->before = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->after = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->long_s = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->long_p = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->prefix_singular = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->prefix_plural = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->creator = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->last_mod = fread_string( fp, MEM_OBJ_CLSS );
obj_clss->item_type = fread_number( fp );
obj_clss->fakes = fread_number( fp );
obj_clss->extra_flags[0] = fread_number( fp );
obj_clss->extra_flags[1] = fread_number( fp );
obj_clss->wear_flags = fread_number( fp );
if( boot_old ) {
// perform object translation
int old_flags = obj_clss->wear_flags;
obj_clss->wear_flags = 0;
for (int i = 0; i < MAX_WEAR; i++)
if (is_set(&old_flags, i))
set_bit(&obj_clss->wear_flags, old_wear_locs[i]);
}
obj_clss->anti_flags = fread_number( fp );
obj_clss->restrictions = fread_number( fp );
obj_clss->size_flags = fread_number( fp );
obj_clss->materials = fread_number( fp );
obj_clss->affect_flags[0] = fread_number( fp );
obj_clss->affect_flags[1] = fread_number( fp );
obj_clss->affect_flags[2] = fread_number( fp );
if( version < 3 ) {
obj_clss->affect_flags[3] = 0;
obj_clss->affect_flags[4] = 0;
}
else {
obj_clss->affect_flags[3] = fread_number( fp );
obj_clss->affect_flags[4] = fread_number( fp );
}
if( version < 10 ) {
obj_clss->affect_flags[5] = 0;
obj_clss->affect_flags[6] = 0;
obj_clss->affect_flags[7] = 0;
obj_clss->affect_flags[8] = 0;
obj_clss->affect_flags[9] = 0;
}
else {
obj_clss->affect_flags[5] = fread_number( fp );
obj_clss->affect_flags[6] = fread_number( fp );
obj_clss->affect_flags[7] = fread_number( fp );
obj_clss->affect_flags[8] = fread_number( fp );
obj_clss->affect_flags[9] = fread_number( fp );
}
obj_clss->layer_flags = fread_number( fp );
obj_clss->value[0] = fread_number( fp );
obj_clss->value[1] = fread_number( fp );
obj_clss->value[2] = fread_number( fp );
obj_clss->value[3] = fread_number( fp );
obj_clss->weight = fread_number( fp );
obj_clss->cost = fread_number( fp );
obj_clss->level = fread_number( fp );
obj_clss->limit = fread_number( fp );
obj_clss->repair = fread_number( fp );
obj_clss->durability = fread_number( fp );
obj_clss->blocks = fread_number( fp );
obj_clss->light = fread_number( fp );
if( version < 6 )
obj_clss->color = 0;
else
obj_clss->color = fread_number( fp );
if( version < 7 )
obj_clss->religion_flags = 0;
else
obj_clss->religion_flags = fread_number( fp );
if( version < 5 ) {
obj_clss->clss_synergy[ CLSS_THIEF+1 ] = 0;
obj_clss->clss_synergy[ CLSS_MAGE+1 ] = 0;
obj_clss->clss_synergy[ CLSS_SORCERER+1 ] = 0;
obj_clss->clss_synergy[ CLSS_CLERIC+1 ] = 0;
obj_clss->clss_synergy[ CLSS_DANCER+1 ] = 0;
}
else {
obj_clss->clss_synergy[ CLSS_THIEF+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_MAGE+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_SORCERER+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_CLERIC+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_DANCER+1 ] = fread_number( fp );
}
if( version < 10 )
obj_clss->clss_synergy[ CLSS_DRUID+1 ] = 0;
else
obj_clss->clss_synergy[ CLSS_DRUID+1 ] = fread_number( fp );
if( version < 11 ) {
obj_clss->clss_synergy[ CLSS_WARRIOR+1 ] = 0;
obj_clss->clss_synergy[ CLSS_CAVALIER+1 ] = 0;
obj_clss->clss_synergy[ CLSS_BARBARIAN+1 ] = 0;
obj_clss->clss_synergy[ CLSS_PALADIN+1 ] = 0;
obj_clss->clss_synergy[ CLSS_RANGER+1 ] = 0;
obj_clss->clss_synergy[ CLSS_DEFENSIVE+1 ] = 0;
obj_clss->clss_synergy[ CLSS_MONK+1 ] = 0;
obj_clss->clss_synergy[ CLSS_ROGUE+1 ] = 0;
obj_clss->clss_synergy[ CLSS_ASSASSIN+1 ] = 0;
}
else {
obj_clss->clss_synergy[ CLSS_WARRIOR+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_CAVALIER+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_BARBARIAN+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_PALADIN+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_RANGER+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_DEFENSIVE+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_MONK+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_ROGUE+1 ] = fread_number( fp );
obj_clss->clss_synergy[ CLSS_ASSASSIN+1 ] = fread_number( fp );
}
if( version > 8 )
count = fread_number( fp );
// Reading skills (not likely, but i am hoping )
/*
for( int i = 0; i < MAX_SKILL; i++ )
obj_clss->skill_modifier[i] = 0;
if( version < 4 ) {
for( int i = 0; i < MAX_SKILL; i++ )
obj_clss->skill_modifier[i] = 0;
}
else if( version < 8 ) {
for( int i = 0; i < 600; i++ ) {
obj_clss->skill_modifier[i] = fread_number( fp );
}
}
else if( version < 9 ) {
for( int i = 0; i < MAX_SKILL; i++ )
obj_clss->skill_modifier[i] = fread_number( fp );
}
else */if( version < 12 ) {
if( count > 0 ) {
for( int i = 0; i < count; i++ ) {
const char* skill = fread_string( fp, MEM_OBJ_CLSS );
for( int j = 0; j < MAX_SKILL; j++ ) {
if( !strcmp( skill, skill_table[j].name ) ) {
// obj_clss->skill_modifier[j] = fread_number( fp );
synergy* syn = new Synergy;
syn->skill = skill_table[j].name;
syn->amount = fread_number( fp );
obj_clss->synergy_array += syn;
break;
}
if( j == MAX_SKILL ) {
fread_number( fp );
}
}
}
}
}
else if( version < 13 ) {
int size = fread_number( fp );
for( int i = 0; i < size; i++ ) {
synergy* syn = new Synergy;
syn->Load( fp );
obj_clss->synergy_array += syn;
}
}
if( boot_tfh ) {
fread_number( fp );
fread_number( fp );
}
obj_clss->date = fread_number( fp );
read_affects( fp, obj_clss, version >= 2 ? false : true ); // version 2 object file introduced new affects format
read_extra( fp, obj_clss->extra_descr );
fread_letter( fp );
for( ; ; ) {
int number = fread_number( fp );
if( number == -1 )
break;
oprog = new oprog_data( obj_clss );
append( obj_clss->oprog, oprog );
oprog->trigger = number;
if( oprog->trigger == OPROG_TRIGGER_WEAR )
oprog->trigger = OPROG_TRIGGER_AFTER_USE;
oprog->obj_vnum = fread_number( fp );
if( boot_old ) {
oprog->value = 0;
} else {
oprog->value = fread_number( fp );
}
oprog->command = fread_string( fp, MEM_OPROG );
oprog->target = fread_string( fp, MEM_OPROG );
// oprog->value = fread_number( fp );
oprog->code = fread_string( fp, MEM_OPROG );
read_extra( fp, oprog->data );
}
fix( obj_clss );
}
fclose( fp );
for( i = 0; i < MAX_OBJ_INDEX; i++ )
if( obj_index_list[i] != NULL )
for( oprog = obj_index_list[i]->oprog; oprog != NULL; oprog = oprog->next )
if( oprog->obj_vnum > 0 )
oprog->obj_act = get_obj_index( oprog->obj_vnum );
return;
}
| 29.21158 | 216 | 0.532802 | Celissa |
123fc1ac7a5431b39d285aac6ed78ee4b7a57040 | 1,492 | cpp | C++ | WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | WeirdEngine/src/TestProject/Source Files/PlaySceneInputComponent.cpp | jeramauni/Proyecto-3 | 2dbdba99ef2899e498dea3eb9a085417773686d7 | [
"Apache-2.0"
] | null | null | null | #include "PlaySceneInputComponent.h"
#include <iostream>
#include <Container.h>
#include <Messages_defs.h>
#include <ComponentFactory.h>
CREATE_REGISTER(PlaySceneInput);
PlaySceneInputComponent::PlaySceneInputComponent(Container* e) : InputComponent(e){
_listener = new WEInputListener(e);
_name = "PlayScene" + _name;
_parent->getWEManager()->addKeyListener(_listener, _name);
}
void PlaySceneInputComponent::Init(std::unordered_map<std::string, std::string>& param) {
PauseMenu = OIS::KC_ESCAPE;
}
// Cuando reacciona al teclado
WEInputListener* PlaySceneInputComponent::getKeyListener() {
return _listener;
}
// Cuando reacciona al raton
InputMouseListener* PlaySceneInputComponent::getMouseListener() {
return nullptr;
}
////-----------------------LISTENER-------------------------
WEInputListener::WEInputListener(Container* ow) {
_owner = ow;
}
WEInputListener::~WEInputListener() {}
bool WEInputListener::keyPressed(const OIS::KeyEvent& ke) {
switch (ke.key) {
case OIS::KC_ESCAPE:
_owner->globalSend(this, msg::Close_Win(msg::WEManager, msg::Broadcast));
break;
case OIS::KC_SPACE:
std::cout << "Funciona\n";
//_owner->localSend(this, msg::Prueba(msg::Player, msg::Broadcast));
//_owner->send(this, msg::Prueba(msg::WEManager, msg::Broadcast));
break;
default:
break;
}
return true;
}
bool WEInputListener::keyReleased(const OIS::KeyEvent& ke) {
return true;
} | 26.175439 | 89 | 0.676944 | jeramauni |
12400188b528059e5e9c0ccf1ac9b43545084cb3 | 5,991 | cpp | C++ | Code/IO/GenerateMesh.cpp | guanjilai/FastCAE | 7afd59a3c0a82c1edf8f5d09482e906e878eb807 | [
"BSD-3-Clause"
] | 1 | 2021-08-14T04:49:56.000Z | 2021-08-14T04:49:56.000Z | Code/IO/GenerateMesh.cpp | guanjilai/FastCAE | 7afd59a3c0a82c1edf8f5d09482e906e878eb807 | [
"BSD-3-Clause"
] | null | null | null | Code/IO/GenerateMesh.cpp | guanjilai/FastCAE | 7afd59a3c0a82c1edf8f5d09482e906e878eb807 | [
"BSD-3-Clause"
] | null | null | null | #include "GenerateMesh.h"
#include "Gmsh/GmshThread.h"
#include "Gmsh/GmshModule.h"
#include "Gmsh/GmshThreadManager.h"
#include "moduleBase/processBar.h"
#include "geometry/geometryData.h"
#include "geometry/GeoComponent.h"
#include "geometry/geometrySet.h"
#include "meshData/ElementType.h"
#include <qdom.h>
#include <vtkDataSet.h>
#include <vtkCell.h>
#include <qfile.h>
namespace IO
{
void GenerateMesh::iniGenerateMesh(GUI::MainWindow* mw, QString path)
{
_mw = mw;
_filePath = path;
iniParameter();
connect(_thread, SIGNAL(writeToSolveFileSig(vtkDataSet*)), this, SLOT(writeToSolveFileSlot(vtkDataSet*)));
}
void GenerateMesh::iniParameter()
{
Geometry::GeometryData* geoData = Geometry::GeometryData::getInstance();
QList<Geometry::GeoComponent*> gcs = geoData->getGeoComponentList();
QMultiHash<int, int> Surface, Body;
for (Geometry::GeoComponent* gc : gcs)
{
if (!gc) continue;
QMultiHash<Geometry::GeometrySet*, int> items = gc->getSelectedItems();
QHashIterator<Geometry::GeometrySet*, int> it(items);
while (it.hasNext())
{
it.next();
int ID = it.key()->getID();
int index = it.value();
if (gc->getGCType() == Geometry::GeoComponentType::Surface)
Surface.insert(ID, index);
else if (gc->getGCType() == Geometry::GeoComponentType::Body)
Body.insert(ID, index);
}
}
Gmsh::GMshPara* para = new Gmsh::GMshPara;
para->_solidHash = Body;
para->_surfaceHash = Surface;
para->_elementType = "Tet";
para->_method = 1;
para->_dim = 3;
para->_elementOrder = 1;
para->_sizeFactor = 1.00;
para->_maxSize = 100.00;
para->_minSize = 0.00;
para->_isGridCoplanar = true;
para->_geoclean = true;
Gmsh::GmshModule* gModule = Gmsh::GmshModule::getInstance(_mw);
_thread = gModule->iniGmshThread(para);
}
void GenerateMesh::startGenerateMesh()
{
_thread->isSaveDataToKernal(false);
Gmsh::GmshModule* gModule = Gmsh::GmshModule::getInstance(_mw);
Gmsh::GmshThreadManager* manager = gModule->getGmshThreadManager();
auto processBar = new ModuleBase::ProcessBar(_mw, QObject::tr("Gmsh Working..."));
manager->insertThread(processBar, _thread);
}
void GenerateMesh::writeToSolveFileSlot(vtkDataSet* data)
{
QDomDocument doc;
QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(instruction);
QDomElement root = doc.createElement("DISO_FILE_1.0");
doc.appendChild(root);
QDomElement mesh = doc.createElement("Mesh");
root.appendChild(mesh);
writeMeshToSolveFile(&doc, &mesh, data);
writeComponentToSolveFile(&doc, &mesh, data);
QFile file(_filePath + "/meshdata.xml");
if (file.open(QFile::WriteOnly | QFile::Text))
{
QTextStream out(&file);
doc.save(out, QDomNode::EncodingFromDocument);
file.close();
}
}
void GenerateMesh::writeMeshToSolveFile(QDomDocument* doc, QDomElement* parent, vtkDataSet* data)
{
int pointsCount = data->GetNumberOfPoints();
int cellsCount = data->GetNumberOfCells();
QDomElement generatedMesh = doc->createElement("GeneratedMesh");
parent->appendChild(generatedMesh);
QDomElement nodelist = doc->createElement("NodeList");
generatedMesh.appendChild(nodelist);
for (int i = 0; i < pointsCount; i++)
{
double* array = data->GetPoint(i);
QStringList list;
list << QString::number(i) << QString::number(array[0]) << QString::number(array[1]) << QString::number(array[2]);
QString str = list.join(',');
QDomText text = doc->createTextNode(str);
QDomElement node = doc->createElement("Node");
nodelist.appendChild(node);
node.appendChild(text);
}
QDomElement elementlist = doc->createElement("ElementList");
generatedMesh.appendChild(elementlist);
for (int i = 0; i < cellsCount; i++)
{
vtkCell* cell = data->GetCell(i);
QString stype = MeshData::vtkCellTYpeToString((VTKCellType)cell->GetCellType());
QString text = QString("%1,%2").arg(i).arg(stype);
vtkIdList* ids = cell->GetPointIds();
int count = ids->GetNumberOfIds();
QDomElement element = doc->createElement("Element");
for (int j = 0; j < count; j++)
{
int id = ids->GetId(j);
text.append(",");
text.append(QString("%1").arg(id));
}
QDomText eletext = doc->createTextNode(text);
elementlist.appendChild(element);
element.appendChild(eletext);
}
}
void GenerateMesh::writeComponentToSolveFile(QDomDocument* doc, QDomElement* parent, vtkDataSet* data)
{
QDomElement set = doc->createElement("Set");
parent->appendChild(set);
Geometry::GeometryData* geoData = Geometry::GeometryData::getInstance();
QList<Geometry::GeoComponent*> gcs = geoData->getGeoComponentList();
QList<Gmsh::itemInfo> infos = _thread->generateGeoIds(data);
for (Geometry::GeoComponent* gc : gcs)
{
if (!gc) continue;
QDomElement geoComponent = doc->createElement("GeoComponent");
geoComponent.setAttribute("ID", gc->getID());
geoComponent.setAttribute("Name", gc->getName());
geoComponent.setAttribute("Type", "Element");
set.appendChild(geoComponent);
QDomElement member = doc->createElement("Member");
geoComponent.appendChild(member);
QString cellIndexs = getCellIndexs(infos, gc);
QDomText text = doc->createTextNode(cellIndexs);
member.appendChild(text);
}
}
QString GenerateMesh::getCellIndexs(QList<Gmsh::itemInfo>& infos, Geometry::GeoComponent*gc/*int geoSetID, int itemIndex*/)
{
QString cellIndexs;
QMultiHash<Geometry::GeometrySet*, int> items = gc->getSelectedItems();
QHashIterator<Geometry::GeometrySet*, int> it(items);
while (it.hasNext())
{
it.next();
int geoSetID = it.key()->getID();
int itemIndex = it.value();
for (Gmsh::itemInfo info : infos)
{
if (info.geoSetID == geoSetID && info.itemIndex == itemIndex)
{
for (int index : info.cellIndexs)
cellIndexs.append(QString::number(index)).append(',');
break;
}
}
}
return cellIndexs.left(cellIndexs.size() - 1);
}
} | 32.209677 | 124 | 0.697212 | guanjilai |
1240720287dbe4fe8e41388f8fb50f390dc268a3 | 2,153 | cpp | C++ | ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp | james-p-foster/ocs2 | 8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa | [
"BSD-3-Clause"
] | null | null | null | ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp | james-p-foster/ocs2 | 8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa | [
"BSD-3-Clause"
] | null | null | null | ocs2_robotic_examples/ocs2_nadia/src/gait/Gait.cpp | james-p-foster/ocs2 | 8f1da414ba9ebb94ad1e8dd9bd513dbb9cc462fa | [
"BSD-3-Clause"
] | null | null | null | #include "ocs2_nadia/gait/Gait.h"
#include <ocs2_core/misc/Display.h>
#include <algorithm>
#include <cassert>
#include <cmath>
namespace ocs2 {
namespace legged_robot {
bool isValidGait(const Gait& gait) {
bool validGait = true;
validGait &= gait.duration > 0.0;
validGait &= std::all_of(gait.eventPhases.begin(), gait.eventPhases.end(), [](scalar_t phase) { return 0.0 < phase && phase < 1.0; });
validGait &= std::is_sorted(gait.eventPhases.begin(), gait.eventPhases.end());
validGait &= gait.eventPhases.size() + 1 == gait.modeSequence.size();
return validGait;
}
bool isValidPhase(scalar_t phase) {
return phase >= 0.0 && phase < 1.0;
}
scalar_t wrapPhase(scalar_t phase) {
phase = std::fmod(phase, 1.0);
if (phase < 0.0) {
phase += 1.0;
}
return phase;
}
int getModeIndexFromPhase(scalar_t phase, const Gait& gait) {
assert(isValidPhase(phase));
assert(isValidGait(gait));
auto firstLargerValueIterator = std::upper_bound(gait.eventPhases.begin(), gait.eventPhases.end(), phase);
return static_cast<int>(firstLargerValueIterator - gait.eventPhases.begin());
}
size_t getModeFromPhase(scalar_t phase, const Gait& gait) {
assert(isValidPhase(phase));
assert(isValidGait(gait));
return gait.modeSequence[getModeIndexFromPhase(phase, gait)];
}
scalar_t timeLeftInGait(scalar_t phase, const Gait& gait) {
assert(isValidPhase(phase));
assert(isValidGait(gait));
return (1.0 - phase) * gait.duration;
}
scalar_t timeLeftInMode(scalar_t phase, const Gait& gait) {
assert(isValidPhase(phase));
assert(isValidGait(gait));
int modeIndex = getModeIndexFromPhase(phase, gait);
if (modeIndex < gait.eventPhases.size()) {
return (gait.eventPhases[modeIndex] - phase) * gait.duration;
} else {
return timeLeftInGait(phase, gait);
}
}
std::ostream& operator<<(std::ostream& stream, const Gait& gait) {
stream << "Duration: " << gait.duration << "\n";
stream << "Event phases: {" << toDelimitedString(gait.eventPhases) << "}\n";
stream << "Mode sequence: {" << toDelimitedString(gait.modeSequence) << "}\n";
return stream;
}
} // namespace legged_robot
} // namespace ocs2
| 29.902778 | 136 | 0.699025 | james-p-foster |
12416d9f0f5578a5c5f14ba2973b7e1ea95d7dce | 2,910 | cc | C++ | base/metrics/stats_counters.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 321 | 2018-06-17T03:52:46.000Z | 2022-03-18T02:34:52.000Z | base/metrics/stats_counters.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 19 | 2018-06-26T10:37:45.000Z | 2020-12-09T03:16:45.000Z | base/metrics/stats_counters.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2010 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 "base/metrics/stats_counters.h"
namespace base {
StatsCounter::StatsCounter(const std::string& name)
: counter_id_(-1) {
// We prepend the name with 'c:' to indicate that it is a counter.
if (StatsTable::current()) {
// TODO(mbelshe): name_ construction is racy and it may corrupt memory for
// static.
name_ = "c:";
name_.append(name);
}
}
StatsCounter::~StatsCounter() {
}
void StatsCounter::Set(int value) {
int* loc = GetPtr();
if (loc)
*loc = value;
}
void StatsCounter::Add(int value) {
int* loc = GetPtr();
if (loc)
(*loc) += value;
}
StatsCounter::StatsCounter()
: counter_id_(-1) {
}
int* StatsCounter::GetPtr() {
StatsTable* table = StatsTable::current();
if (!table)
return NULL;
// If counter_id_ is -1, then we haven't looked it up yet.
if (counter_id_ == -1) {
counter_id_ = table->FindCounter(name_);
if (table->GetSlot() == 0) {
if (!table->RegisterThread(std::string())) {
// There is no room for this thread. This thread
// cannot use counters.
counter_id_ = 0;
return NULL;
}
}
}
// If counter_id_ is > 0, then we have a valid counter.
if (counter_id_ > 0)
return table->GetLocation(counter_id_, table->GetSlot());
// counter_id_ was zero, which means the table is full.
return NULL;
}
StatsCounterTimer::StatsCounterTimer(const std::string& name) {
// we prepend the name with 't:' to indicate that it is a timer.
if (StatsTable::current()) {
// TODO(mbelshe): name_ construction is racy and it may corrupt memory for
// static.
name_ = "t:";
name_.append(name);
}
}
StatsCounterTimer::~StatsCounterTimer() {
}
void StatsCounterTimer::Start() {
if (!Enabled())
return;
start_time_ = TimeTicks::Now();
stop_time_ = TimeTicks();
}
// Stop the timer and record the results.
void StatsCounterTimer::Stop() {
if (!Enabled() || !Running())
return;
stop_time_ = TimeTicks::Now();
Record();
}
// Returns true if the timer is running.
bool StatsCounterTimer::Running() {
return Enabled() && !start_time_.is_null() && stop_time_.is_null();
}
// Accept a TimeDelta to increment.
void StatsCounterTimer::AddTime(TimeDelta time) {
Add(static_cast<int>(time.InMilliseconds()));
}
void StatsCounterTimer::Record() {
AddTime(stop_time_ - start_time_);
}
StatsRate::StatsRate(const std::string& name)
: StatsCounterTimer(name),
counter_(name),
largest_add_(std::string(" ").append(name).append("MAX")) {
}
StatsRate::~StatsRate() {
}
void StatsRate::Add(int value) {
counter_.Increment();
StatsCounterTimer::Add(value);
if (value > largest_add_.value())
largest_add_.Set(value);
}
} // namespace base
| 23.095238 | 78 | 0.654983 | domenic |
1243fa74c62b5e80b178f84fc7fb8eadc1079278 | 1,683 | cpp | C++ | Project/Main/Onket/goodgenralinfowidget.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | 1 | 2021-01-03T21:33:26.000Z | 2021-01-03T21:33:26.000Z | Project/Main/Onket/goodgenralinfowidget.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | null | null | null | Project/Main/Onket/goodgenralinfowidget.cpp | IsfahanUniversityOfTechnology-CE2019-23/Onket | 403d982f7c80d522ca28bb5f757a295eb02b3807 | [
"MIT"
] | 1 | 2020-07-22T14:48:58.000Z | 2020-07-22T14:48:58.000Z | #include "goodgenralinfowidget.h"
#include "ui_goodgenralinfowidget.h"
void GoodGenralInfoWidget::update()
{
if(this->info_valid==true)
{
Good& g=Good::getGood(good_id);
if(g.getDiscountpercent()==0)
{
this->ui->lab_price->setStyleSheet(this->font_regular);
}
else
{
this->ui->lab_price->setStyleSheet(this->font_skriteout);
}
ui->lab_name->setText(g.getName());
ui->lab_seller->setText(g.getMakerId());
ui->lab_price->setText(price::number(g.getPrice()));
ui->lab_discount_percent->setText(QString::number(g.getDiscountpercent()*100));
ui->lab_final_price->setText(price::number(g.getFinalPrice()));
ui->gridLayout->addWidget(ui->lab_1,0,0);
ui->gridLayout->addWidget(ui->lab_2,1,0);
ui->gridLayout->addWidget(ui->lab_3,2,0);
ui->gridLayout->addWidget(ui->lab_4,3,0);
ui->gridLayout->addWidget(ui->lab_5,4,0);
ui->gridLayout->addWidget(ui->lab_name,0,1);
ui->gridLayout->addWidget(ui->lab_seller,1,1);
ui->gridLayout->addWidget(ui->lab_price,2,1);
ui->gridLayout->addWidget(ui->lab_discount_percent,3,1);
ui->gridLayout->addWidget(ui->lab_final_price,4,1);
}
}
GoodGenralInfoWidget::GoodGenralInfoWidget(const QString& good_id,QWidget *parent) :
QWidget(parent),
ui(new Ui::GoodGenralInfoWidget)
{
ui->setupUi(this);
this->good_id=good_id;
if(Good::existGoodId(good_id)==false)
{
return;
}
else
{
this->info_valid=true;
update();
}
}
GoodGenralInfoWidget::~GoodGenralInfoWidget()
{
delete ui;
}
| 25.119403 | 87 | 0.620915 | IsfahanUniversityOfTechnology-CE2019-23 |
12478c4c20dff2eb0a6695abb649947dff78812b | 444 | hpp | C++ | Notes_Week7/friendDemo/budget.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | 1 | 2019-01-06T22:36:01.000Z | 2019-01-06T22:36:01.000Z | Notes_Week7/friendDemo/budget.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | Notes_Week7/friendDemo/budget.hpp | WeiChienHsu/CS165 | 65e95efc90415c8acc707e2d544eb384d3982e18 | [
"MIT"
] | null | null | null | #ifndef BUDGET_HPP
#define BUDGET_HPP
#include "aux.hpp"
class Budget {
private:
static double corpBudget;
double divBudget;
public:
Budget() { divBudget = 0;}
void addBudget(double b) {
this->divBudget += b;
this->corpBudget += divBudget;
}
double getDivBudget() const {return this->divBudget;}
static double getCorpBudget() {return corpBudget;}
friend void Aux::addBudget(double);
};
#endif | 21.142857 | 57 | 0.664414 | WeiChienHsu |
1247a50cfa2148ab27780aa67c44238c57f1c5f1 | 544 | cpp | C++ | 12_cmake_with_unittest/wolfram/alpha.cpp | TeachYourselfCS/cmakeDemo | 752ab76cd43aa80aaa647eed4f5389f4f1ff39e7 | [
"MIT"
] | null | null | null | 12_cmake_with_unittest/wolfram/alpha.cpp | TeachYourselfCS/cmakeDemo | 752ab76cd43aa80aaa647eed4f5389f4f1ff39e7 | [
"MIT"
] | null | null | null | 12_cmake_with_unittest/wolfram/alpha.cpp | TeachYourselfCS/cmakeDemo | 752ab76cd43aa80aaa647eed4f5389f4f1ff39e7 | [
"MIT"
] | null | null | null | #include "wolfram/alpha.hpp"
#include <curl_wrapper/curl_wrapper.hpp>
namespace wolfram {
const std::string API_BASE = "https://api.wolframalpha.com/v1/result";
std::string simple_query(const std::string &appid, const std::string &query) {
// 使用 curl_wrapper 库提供的对 CURL 的 C++ 封装
using curl_wrapper::url_encode;
using curl_wrapper::http_get_string;
const auto url = API_BASE + "?appid=" + url_encode(appid) + "&i=" + url_encode(query);
return http_get_string(url);
}
} // namespace wolfram
| 34 | 94 | 0.672794 | TeachYourselfCS |
1248872175050391e57b1e55632ee79d9f6705c2 | 3,414 | hpp | C++ | stm32/stm32f1/include/stm32f1/dma/Channel.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 1 | 2022-01-31T01:59:52.000Z | 2022-01-31T01:59:52.000Z | stm32/stm32f1/include/stm32f1/dma/Channel.hpp | PhischDotOrg/stm32-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 5 | 2020-04-13T21:55:12.000Z | 2020-06-27T17:44:44.000Z | stm32/stm32f1/include/stm32f1/dma/Channel.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | null | null | null | /*-
* $Copyright$
-*/
#ifndef _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555
#define _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555
#include <stdint.h>
#include <stddef.h>
#include <stm32/dma/Types.hpp>
#include <stm32f1/dma/Stream.hpp>
/*****************************************************************************/
namespace stm32 {
namespace f1 {
/*****************************************************************************/
/*****************************************************************************/
class DmaChannel {
DMA_Channel_TypeDef & m_channel;
protected:
DmaChannel(DMA_Channel_TypeDef *p_channel) : m_channel(*p_channel) {
}
public:
static constexpr
intptr_t
getDmaChannelAddress(intptr_t p_dmaEngine, unsigned p_channel) {
return (p_dmaEngine + 0x1c + p_channel * 20);
}
void
handleIrq(void) const {
(void) m_channel;
}
};
/*****************************************************************************/
/*****************************************************************************/
template<
typename NvicT,
typename DmaEngineT,
unsigned nChannelNo
>
class DmaChannelT : public EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) >, public DmaChannel {
static_assert(nChannelNo >= 0);
static_assert((DmaEngineT::m_engineType == DMA1_BASE) && (nChannelNo <= 7));
const NvicT & m_nvic;
public:
DmaChannelT(const NvicT &p_nvic, const DmaEngineT & /* p_dmaEngine */)
: DmaChannel(reinterpret_cast<DMA_Channel_TypeDef *>(DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo))), m_nvic(p_nvic) {
m_nvic.enableIrq(* static_cast< EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) > *>(this));
}
~DmaChannelT() {
m_nvic.disableIrq(* static_cast< EngineT< DmaChannel::getDmaChannelAddress(DmaEngineT::m_engineType, nChannelNo) > *>(this));
}
void setup(const dma::DmaDirection_t /* p_direction */, const size_t /* p_length */) const {
// this->m_stream.disable();
// this->m_stream.setup(this->m_channel, p_direction, p_length);
}
void setupFifo(const dma::DmaBurstSize_t /* p_burst */, const dma::DmaFifoThreshold_t /* p_threshold */) const {
}
void setupSource(const void * const /* p_addr */, const unsigned /* p_width */, const bool /* p_incr */) const {
// this->m_stream.setupSource(p_addr, p_width, p_incr);
}
void setupTarget(void * const /* p_addr */, const unsigned /* p_width */, const bool /* p_incr */) const {
// this->m_stream.setupTarget(p_addr, p_width, p_incr);
}
void start(/* const DmaChannelCallback * const p_callback */ void) const {
// assert(this->m_callback == NULL);
// this->m_callback = p_callback;
// this->m_stream.enable(&this->m_streamCallback);
}
void stop(void) const {
// this->m_stream.disable();
// this->m_callback = NULL;
}
};
/*****************************************************************************/
/*****************************************************************************/
} /* namespace f1 */
} /* namespace dma */
/*****************************************************************************/
#endif /* _DMA_CHANNEL_STM32_HPP_B6BD9823_B66D_4724_9A96_965E03319555 */
| 34.836735 | 149 | 0.550088 | PhischDotOrg |
1249a9e10b06ff417f104350e87b75ba712d9446 | 2,470 | hpp | C++ | src/client/ofi_connector.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | null | null | null | src/client/ofi_connector.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | 3 | 2021-09-08T02:26:12.000Z | 2022-03-12T00:45:28.000Z | src/client/ofi_connector.hpp | ashahba/aeon | eafbc6b7040bf594854bd92f1606d37ddd862943 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Intel(R) Nervana(TM)
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.
*/
#pragma once
#include <memory>
#include "http_connector.hpp"
#include "../rdma/ofi.hpp"
namespace nervana
{
class ofi_connector final : public http_connector
{
public:
explicit ofi_connector(const std::string& address,
unsigned int port,
std::shared_ptr<http_connector> base_connector);
ofi_connector() = delete;
~ofi_connector();
http_response get(const std::string& endpoint,
const http_query_t& query = http_query_t()) override;
http_response post(const std::string& endpoint, const std::string& body = "") override
{
return m_base_connector->post(endpoint, body);
}
http_response post(const std::string& endpoint, const http_query_t& query) override
{
return m_base_connector->post(endpoint, query);
}
http_response del(const std::string& endpoint,
const http_query_t& query = http_query_t()) override;
private:
void connect(const std::string& address, unsigned int port);
void disconnect();
void register_rdma_memory(size_t size);
void unregister_rdma_memory();
bool is_rdma_registered() { return m_rdma_memory.is_registered(); }
http_response receive_data(const std::string& endpoint, const http_query_t& query);
http_response receive_message_data(const std::string& endpoint, const http_query_t& query);
http_response receive_rdma_data(const std::string& endpoint, const http_query_t& query);
std::shared_ptr<http_connector> m_base_connector;
std::string m_connection_id;
ofi::ofi m_ofi;
ofi::rdma_memory m_rdma_memory;
};
}
| 38 | 99 | 0.640081 | ashahba |
124fd45622dd2f9fb7cb43fc834bca9ecfbc2925 | 3,128 | cpp | C++ | jbmc/unit/java_bytecode/expr2java.cpp | DamonLiuTHU/cbmc | 67f8c916672347ab05418db45eebbd93885efdec | [
"BSD-4-Clause"
] | null | null | null | jbmc/unit/java_bytecode/expr2java.cpp | DamonLiuTHU/cbmc | 67f8c916672347ab05418db45eebbd93885efdec | [
"BSD-4-Clause"
] | null | null | null | jbmc/unit/java_bytecode/expr2java.cpp | DamonLiuTHU/cbmc | 67f8c916672347ab05418db45eebbd93885efdec | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Unit tests for expr-to-java string conversion
Author: Diffblue Ltd.
\*******************************************************************/
#include <testing-utils/catch.hpp>
#include <java_bytecode/expr2java.h>
TEST_CASE(
"expr2java tests",
"[core][java_bytecode][expr2java][floating_point_to_java_string]")
{
SECTION("0.0 double to string")
{
REQUIRE(floating_point_to_java_string(0.0) == "0.0");
}
SECTION("0.0 float to string")
{
REQUIRE(floating_point_to_java_string(0.0f) == "0.0f");
}
SECTION("-0.0 double to string")
{
REQUIRE(floating_point_to_java_string(-0.0) == "-0.0");
}
SECTION("-0.0 float to string")
{
REQUIRE(floating_point_to_java_string(-0.0f) == "-0.0f");
}
SECTION("1.0 double to string")
{
REQUIRE(floating_point_to_java_string(1.0) == "1.0");
}
SECTION("1.0 float to string")
{
REQUIRE(floating_point_to_java_string(1.0f) == "1.0f");
}
SECTION("-1.0 double to string")
{
REQUIRE(floating_point_to_java_string(-1.0) == "-1.0");
}
SECTION("-1.0 float to string")
{
REQUIRE(floating_point_to_java_string(-1.0f) == "-1.0f");
}
SECTION("Infinity double to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<double>(INFINITY)) ==
"Double.POSITIVE_INFINITY");
}
SECTION("Infinity float to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<float>(INFINITY)) ==
"Float.POSITIVE_INFINITY");
}
SECTION("Negative infinity double to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<double>(-INFINITY)) ==
"Double.NEGATIVE_INFINITY");
}
SECTION("Negative infinity float to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<float>(-INFINITY)) ==
"Float.NEGATIVE_INFINITY");
}
SECTION("Float NaN to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<float>(NAN)) == "Float.NaN");
}
SECTION("Double NaN to string")
{
REQUIRE(
floating_point_to_java_string(static_cast<double>(NAN)) == "Double.NaN");
}
SECTION("Hex float to string (print a comment)")
{
const float value = std::strtod("0x1p+37f", nullptr);
#ifndef _MSC_VER
REQUIRE(
floating_point_to_java_string(value) == "0x1p+37f /* 1.37439e+11 */");
#else
REQUIRE(
floating_point_to_java_string(value) ==
"0x1.000000p+37f /* 1.37439e+11 */");
#endif
}
SECTION("Hex double to string (print a comment)")
{
const double value = std::strtod("0x1p+37f", nullptr);
#ifndef _MSC_VER
REQUIRE(
floating_point_to_java_string(value) == "0x1p+37 /* 1.37439e+11 */");
#else
REQUIRE(
floating_point_to_java_string(value) ==
"0x1.000000p+37 /* 1.37439e+11 */");
#endif
}
SECTION("Beyond numeric limits")
{
#ifndef _MSC_VER
REQUIRE(
floating_point_to_java_string(-5.56268e-309)
.find("/* -5.56268e-309 */") != std::string::npos);
#else
REQUIRE(floating_point_to_java_string(-5.56268e-309) == "-5.56268e-309");
#endif
}
}
| 23.518797 | 79 | 0.624361 | DamonLiuTHU |
1254ceced548ab361631a57308eaa611c1904981 | 1,301 | cc | C++ | mindspore/ccsrc/runtime/framework/actor/recorder_actor.cc | ATestGroup233/mindspore | 5d81221b5896cf7d7c6adb44daef28d92cb43352 | [
"Apache-2.0"
] | 1 | 2021-06-01T12:34:37.000Z | 2021-06-01T12:34:37.000Z | mindspore/ccsrc/runtime/framework/actor/recorder_actor.cc | ATestGroup233/mindspore | 5d81221b5896cf7d7c6adb44daef28d92cb43352 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/runtime/framework/actor/recorder_actor.cc | ATestGroup233/mindspore | 5d81221b5896cf7d7c6adb44daef28d92cb43352 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 "runtime/framework/actor/recorder_actor.h"
#include "utils/log_adapter.h"
namespace mindspore {
namespace runtime {
void RecorderActor::RecordMemAddressInfo(const AnfNode *node, const KernelLaunchInfo *launch_info_,
const DeviceContext *device_context, OpContext<DeviceTensor> *op_context) {
MS_EXCEPTION_IF_NULL(node);
MS_EXCEPTION_IF_NULL(launch_info_);
MS_EXCEPTION_IF_NULL(device_context);
MS_EXCEPTION_IF_NULL(op_context);
// todo record
}
void RecorderActor::ClearMemAddressInfo(OpContext<DeviceTensor> *op_context) {
MS_EXCEPTION_IF_NULL(op_context);
// todo clear
}
} // namespace runtime
} // namespace mindspore
| 34.236842 | 116 | 0.747118 | ATestGroup233 |
125941b9721baa7147c01a5b8adf1f094d456f39 | 4,167 | cpp | C++ | demo/Demo.cpp | logicomacorp/pulsejet | ec73d19ccb71ff05b2122e258fe4b7b16e55fb53 | [
"MIT"
] | 30 | 2021-06-07T20:25:48.000Z | 2022-03-30T00:52:38.000Z | demo/Demo.cpp | going-digital/pulsejet | 8452a0311645867d64c038cef7fdf751b26717ee | [
"MIT"
] | null | null | null | demo/Demo.cpp | going-digital/pulsejet | 8452a0311645867d64c038cef7fdf751b26717ee | [
"MIT"
] | 1 | 2021-09-21T11:17:45.000Z | 2021-09-21T11:17:45.000Z | #include "FastSinusoids.hpp"
// Required by `Pulsejet::Encode` and `Pulsejet::Decode`
namespace Pulsejet::Shims
{
inline float CosF(float x)
{
return FastSinusoids::CosF(x);
}
inline float Exp2f(float x)
{
return exp2f(x);
}
inline float SinF(float x)
{
return FastSinusoids::SinF(x);
}
inline float SqrtF(float x)
{
return sqrtf(x);
}
}
#include <Pulsejet/Pulsejet.hpp>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
static void PrintUsage(const char **argv)
{
cout << "Usage:\n";
cout << " encode: " << argv[0] << " -e <target bit rate in kbps> <input.raw> <output.pulsejet>\n";
cout << " decode: " << argv[0] << " -d <input.pulsejet> <output.raw>\n";
}
static void ErrorInvalidArgs(const char **argv)
{
cout << "ERROR: Invalid args\n\n";
PrintUsage(argv);
}
static vector<uint8_t> ReadFile(const char *fileName)
{
ifstream inputFile(fileName, ios::binary | ios::ate);
const auto inputFileSize = inputFile.tellg();
inputFile.seekg(0, ios::beg);
vector<uint8_t> ret(inputFileSize);
inputFile.read(reinterpret_cast<char *>(ret.data()), inputFileSize);
return ret;
}
int main(int argc, const char **argv)
{
if (argc < 4)
{
ErrorInvalidArgs(argv);
return 1;
}
cout << "library version: " << Pulsejet::LibraryVersionString() << "\n";
cout << "codec version: " << Pulsejet::CodecVersionString() << "\n";
FastSinusoids::Init();
if (!strcmp(argv[1], "-e"))
{
if (argc != 5)
{
ErrorInvalidArgs(argv);
return 1;
}
const double targetBitRate = stod(argv[2]);
const auto inputFileName = argv[3];
const auto outputFileName = argv[4];
cout << "reading ... " << flush;
const auto input = ReadFile(inputFileName);
cout << "ok\n";
cout << "size check ... " << flush;
if (input.size() % sizeof(float))
{
cout << "ERROR: Input size is not aligned to float size\n\n";
return 1;
}
cout << "ok\n";
cout << "encoding ... " << flush;
const uint32_t numSamples = static_cast<uint32_t>(input.size()) / sizeof(float);
const double sampleRate = 44100.0;
double totalBitsEstimate;
const auto encodedSample = Pulsejet::Encode(reinterpret_cast<const float *>(input.data()), numSamples, sampleRate, targetBitRate, totalBitsEstimate);
const auto bitRateEstimate = totalBitsEstimate / 1000.0 / (static_cast<double>(numSamples) / sampleRate);
cout << "ok, compressed size estimate: " << static_cast<uint32_t>(ceil(totalBitsEstimate / 8.0)) << " byte(s) (~" << setprecision(4) << bitRateEstimate << "kbps)\n";
cout << "writing ... " << flush;
ofstream outputFile(outputFileName, ios::binary);
outputFile.write(reinterpret_cast<const char *>(encodedSample.data()), encodedSample.size());
cout << "ok\n";
cout << "encoding successful!\n";
}
else if (!strcmp(argv[1], "-d"))
{
if (argc != 4)
{
ErrorInvalidArgs(argv);
return 1;
}
const auto inputFileName = argv[2];
const auto outputFileName = argv[3];
cout << "reading ... " << flush;
const auto input = ReadFile(inputFileName);
cout << "ok\n";
cout << "sample check ... " << flush;
if (!Pulsejet::CheckSample(input.data()))
{
cout << "ERROR: Input is not a pulsejet sample\n\n";
return 1;
}
cout << "ok\n";
cout << "sample version: " << Pulsejet::SampleVersionString(input.data()) << "\n";
cout << "sample version check ... " << flush;
if (!Pulsejet::CheckSampleVersion(input.data()))
{
cout << "ERROR: Incompatible codec and sample versions\n\n";
return 1;
}
cout << "ok\n";
cout << "decoding ... " << flush;
uint32_t numDecodedSamples;
const auto decodedSample = Pulsejet::Decode(input.data(), &numDecodedSamples);
cout << "ok, " << numDecodedSamples << " samples\n";
cout << "writing ... " << flush;
ofstream outputFile(outputFileName, ios::binary);
outputFile.write(reinterpret_cast<const char *>(decodedSample), numDecodedSamples * sizeof(float));
cout << "ok\n";
cout << "cleanup ... " << flush;
delete [] decodedSample;
cout << "ok\n";
cout << "decoding successful!\n";
}
else
{
ErrorInvalidArgs(argv);
return 1;
}
return 0;
}
| 24.656805 | 167 | 0.648908 | logicomacorp |
125d95781fe1a6a5ee591f15c3d616be1b9c5d76 | 11,560 | hpp | C++ | src/libraries/sampling/sampledSurface/sampledSurfaces/sampledSurfaces.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/sampling/sampledSurface/sampledSurfaces/sampledSurfaces.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | src/libraries/sampling/sampledSurface/sampledSurfaces/sampledSurfaces.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) 2011 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with CAELUS. If not, see <http://www.gnu.org/licenses/>.
Class
CML::sampledSurfaces
Description
Set of surfaces to sample.
The write() method is used to sample and write files.
SourceFiles
sampledSurfaces.cpp
\*---------------------------------------------------------------------------*/
#ifndef sampledSurfaces_H
#define sampledSurfaces_H
#include "sampledSurface.hpp"
#include "surfaceWriter.hpp"
#include "volFieldsFwd.hpp"
#include "surfaceFieldsFwd.hpp"
#include "wordReList.hpp"
#include "IOobjectList.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
class fvMesh;
class dictionary;
/*---------------------------------------------------------------------------*\
Class sampledSurfaces Declaration
\*---------------------------------------------------------------------------*/
class sampledSurfaces
:
public PtrList<sampledSurface>
{
// Private classes
//- Class used for surface merging information
class mergeInfo
{
public:
pointField points;
faceList faces;
labelList pointsMap;
//- Clear all storage
void clear()
{
points.clear();
faces.clear();
pointsMap.clear();
}
};
// Static data members
//- output verbosity
static bool verbose_;
//- Tolerance for merging points (fraction of mesh bounding box)
static scalar mergeTol_;
// Private data
//- Name of this set of surfaces,
// Also used as the name of the sampledSurfaces directory.
const word name_;
//- Const reference to fvMesh
const fvMesh& mesh_;
//- Load fields from files (not from objectRegistry)
const bool loadFromFiles_;
//- output path
fileName outputPath_;
// Read from dictonary
//- Names of fields to sample
wordReList fieldSelection_;
//- Interpolation scheme to use
word interpolationScheme_;
// surfaces
//- Information for merging surfaces
List<mergeInfo> mergeList_;
// Calculated
//- Surface formatter
autoPtr<surfaceWriter> formatter_;
// Private Member Functions
//- Return number of fields
label classifyFields();
//- Write geometry only
void writeGeometry() const;
//- Write sampled fieldName on surface and on outputDir path
template<class Type>
void writeSurface
(
const Field<Type>& values,
const label surfI,
const word& fieldName,
const fileName& outputDir
);
//- Sample and write a particular volume field
template<class Type>
void sampleAndWrite
(
const GeometricField<Type, fvPatchField, volMesh>&
);
//- Sample and write a particular surface field
template<class Type>
void sampleAndWrite
(
const GeometricField<Type, fvsPatchField, surfaceMesh>&
);
//- Sample and write all sampled fields
template<class Type> void sampleAndWrite(const IOobjectList& objects);
//- Disallow default bitwise copy construct and assignment
sampledSurfaces(const sampledSurfaces&);
void operator=(const sampledSurfaces&);
public:
//- Runtime type information
TypeName("surfaces");
// Constructors
//- Construct for given objectRegistry and dictionary
// allow the possibility to load fields from files
sampledSurfaces
(
const word& name,
const objectRegistry&,
const dictionary&,
const bool loadFromFiles = false
);
//- Destructor
virtual ~sampledSurfaces();
// Member Functions
//- Does any of the surfaces need an update?
virtual bool needsUpdate() const;
//- Mark the surfaces as needing an update.
// May also free up unneeded data.
// Return false if all surfaces were already marked as expired.
virtual bool expire();
//- Update the surfaces as required and merge surface points (parallel).
// Return false if no surfaces required an update.
virtual bool update();
//- Return name of the set of surfaces
virtual const word& name() const
{
return name_;
}
//- set verbosity level
void verbose(const bool verbosity = true);
//- Execute, currently does nothing
virtual void execute();
//- Execute at the final time-loop, currently does nothing
virtual void end();
//- Called when time was set at the end of the Time::operator++
virtual void timeSet();
//- Sample and write
virtual void write();
//- Read the sampledSurfaces dictionary
virtual void read(const dictionary&);
//- Update for changes of mesh - expires the surfaces
virtual void updateMesh(const mapPolyMesh&);
//- Update for mesh point-motion - expires the surfaces
virtual void movePoints(const pointField&);
//- Update for changes of mesh due to readUpdate - expires the surfaces
virtual void readUpdate(const polyMesh::readUpdateState state);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "volFields.hpp"
#include "surfaceFields.hpp"
#include "ListListOps.hpp"
#include "stringListOps.hpp"
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
template<class Type>
void CML::sampledSurfaces::writeSurface
(
const Field<Type>& values,
const label surfI,
const word& fieldName,
const fileName& outputDir
)
{
const sampledSurface& s = operator[](surfI);
if (Pstream::parRun())
{
// Collect values from all processors
List<Field<Type> > gatheredValues(Pstream::nProcs());
gatheredValues[Pstream::myProcNo()] = values;
Pstream::gatherList(gatheredValues);
if (Pstream::master())
{
// Combine values into single field
Field<Type> allValues
(
ListListOps::combine<Field<Type> >
(
gatheredValues,
accessOp<Field<Type> >()
)
);
// Renumber (point data) to correspond to merged points
if (mergeList_[surfI].pointsMap.size() == allValues.size())
{
inplaceReorder(mergeList_[surfI].pointsMap, allValues);
allValues.setSize(mergeList_[surfI].points.size());
}
// Write to time directory under outputPath_
// skip surface without faces (eg, a failed cut-plane)
if (mergeList_[surfI].faces.size())
{
formatter_->write
(
outputDir,
s.name(),
mergeList_[surfI].points,
mergeList_[surfI].faces,
fieldName,
allValues,
s.interpolate()
);
}
}
}
else
{
// Write to time directory under outputPath_
// skip surface without faces (eg, a failed cut-plane)
if (s.faces().size())
{
formatter_->write
(
outputDir,
s.name(),
s.points(),
s.faces(),
fieldName,
values,
s.interpolate()
);
}
}
}
template<class Type>
void CML::sampledSurfaces::sampleAndWrite
(
const GeometricField<Type, fvPatchField, volMesh>& vField
)
{
// interpolator for this field
autoPtr<interpolation<Type> > interpolatorPtr;
const word& fieldName = vField.name();
const fileName outputDir = outputPath_/vField.time().timeName();
forAll(*this, surfI)
{
const sampledSurface& s = operator[](surfI);
Field<Type> values;
if (s.interpolate())
{
if (interpolatorPtr.empty())
{
interpolatorPtr = interpolation<Type>::New
(
interpolationScheme_,
vField
);
}
values = s.interpolate(interpolatorPtr());
}
else
{
values = s.sample(vField);
}
writeSurface<Type>(values, surfI, fieldName, outputDir);
}
}
template<class Type>
void CML::sampledSurfaces::sampleAndWrite
(
const GeometricField<Type, fvsPatchField, surfaceMesh>& sField
)
{
const word& fieldName = sField.name();
const fileName outputDir = outputPath_/sField.time().timeName();
forAll(*this, surfI)
{
const sampledSurface& s = operator[](surfI);
Field<Type> values(s.sample(sField));
writeSurface<Type>(values, surfI, fieldName, outputDir);
}
}
template<class GeoField>
void CML::sampledSurfaces::sampleAndWrite(const IOobjectList& objects)
{
wordList names;
if (loadFromFiles_)
{
IOobjectList fieldObjects(objects.lookupClass(GeoField::typeName));
names = fieldObjects.names();
}
else
{
names = mesh_.thisDb().names<GeoField>();
}
labelList nameIDs(findStrings(fieldSelection_, names));
wordHashSet fieldNames(wordList(names, nameIDs));
forAllConstIter(wordHashSet, fieldNames, iter)
{
const word& fieldName = iter.key();
if ((Pstream::master()) && verbose_)
{
Pout<< "sampleAndWrite: " << fieldName << endl;
}
if (loadFromFiles_)
{
const GeoField fld
(
IOobject
(
fieldName,
mesh_.time().timeName(),
mesh_,
IOobject::MUST_READ
),
mesh_
);
sampleAndWrite(fld);
}
else
{
sampleAndWrite
(
mesh_.thisDb().lookupObject<GeoField>(fieldName)
);
}
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 25.861298 | 80 | 0.528287 | MrAwesomeRocks |
125dcfd5073caa4a21da9cf969edd3a46e6c89d8 | 30,060 | cpp | C++ | framework/NetKinectArray.cpp | steppobeck/rgbd-recon | 171a8336c8e3ba52a1b187b73544338fdd3c9285 | [
"MIT"
] | 18 | 2016-09-03T05:12:25.000Z | 2022-02-23T15:52:33.000Z | framework/NetKinectArray.cpp | 3d-scan/rgbd-recon | c4a5614eaa55dd93c74da70d6fb3d813d74f2903 | [
"MIT"
] | 1 | 2016-05-04T09:06:29.000Z | 2016-05-04T09:06:29.000Z | framework/NetKinectArray.cpp | 3d-scan/rgbd-recon | c4a5614eaa55dd93c74da70d6fb3d813d74f2903 | [
"MIT"
] | 7 | 2016-04-20T13:58:50.000Z | 2018-07-09T15:47:26.000Z | #include "NetKinectArray.h"
#include "calibration_files.hpp"
#include "texture_blitter.hpp"
#include "screen_quad.hpp"
#include <FileBuffer.h>
#include <TextureArray.h>
#include <KinectCalibrationFile.h>
#include "CalibVolumes.hpp"
#include <DXTCompressor.h>
#include "timer_database.hpp"
#include <glbinding/gl/gl.h>
#include <glbinding/gl/functions-patches.h>
using namespace gl;
#include <globjects/Program.h>
#include <globjects/Texture.h>
#include <globjects/Framebuffer.h>
#include <globjects/Buffer.h>
#include <globjects/Shader.h>
#include <globjects/logging.h>
#include <globjects/NamedString.h>
#include <globjects/base/File.h>
#include <globjects/Query.h>
#include <globjects/NamedString.h>
#include <globjects/base/File.h>
#include "squish/squish.h"
#include <zmq.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <thread>
namespace kinect{
static const std::size_t s_num_bg_frames = 20;
NetKinectArray::NetKinectArray(std::string const& serverport, std::string const& slaveport, CalibrationFiles const* calibs, CalibVolumes const* vols, bool readfromfile)
: m_numLayers(0),
m_colorArray(),
m_depthArray_raw(),
m_textures_depth{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_depth_b{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_depth2{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY), globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_quality{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_normal{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_color{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_bg{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY), globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_textures_silhouette{globjects::Texture::createDefault(GL_TEXTURE_2D_ARRAY)},
m_fbo{new globjects::Framebuffer()},
m_colorArray_back(),
m_colorsize(0),
m_depthsize(0),
m_pbo_colors(),
m_pbo_depths(),
m_mutex_pbo(),
m_readThread(),
m_running(true),
m_filter_textures(true),
m_refine_bound(true),
m_serverport(serverport),
m_slaveport(slaveport),
m_num_frame{0},
m_curr_frametime{0.0},
m_use_processed_depth{true},
m_start_texture_unit(0),
m_calib_files{calibs},
m_calib_vols{vols},
m_streamslot(0)
{
m_programs.emplace("filter", new globjects::Program());
m_programs.emplace("normal", new globjects::Program());
m_programs.emplace("quality", new globjects::Program());
m_programs.emplace("boundary", new globjects::Program());
m_programs.emplace("morph", new globjects::Program());
// must happen before thread launching
init();
if(readfromfile){
readFromFiles();
}
else{
m_readThread = std::unique_ptr<std::thread>{new std::thread(std::bind(&NetKinectArray::readLoop, this))};
}
globjects::NamedString::create("/bricks.glsl", new globjects::File("glsl/inc_bricks.glsl"));
m_programs.at("filter")->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs")
,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_depth.fs")
);
m_programs.at("normal")->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs")
,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_normal.fs")
);
m_programs.at("quality")->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs")
,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_quality.fs")
);
m_programs.at("boundary")->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs")
,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_boundary.fs")
);
m_programs.at("morph")->attach(
globjects::Shader::fromFile(GL_VERTEX_SHADER, "glsl/texture_passthrough.vs")
,globjects::Shader::fromFile(GL_FRAGMENT_SHADER, "glsl/pre_morph.fs")
);
}
bool
NetKinectArray::init(){
m_numLayers = m_calib_files->num();
m_resolution_depth = glm::uvec2{m_calib_files->getWidth(), m_calib_files->getHeight()};
m_resolution_color = glm::uvec2{m_calib_files->getWidthC(), m_calib_files->getHeightC()};
if(m_calib_files->isCompressedRGB() == 1){
mvt::DXTCompressor dxt;
dxt.init(m_calib_files->getWidthC(), m_calib_files->getHeightC(), FORMAT_DXT1);
m_colorsize = dxt.getStorageSize();
}
else if(m_calib_files->isCompressedRGB() == 5){
std::cerr << "NetKinectArray: using DXT5" << std::endl;
m_colorsize = 307200;
}
else{
m_colorsize = m_resolution_color.x * m_resolution_color.y * 3 * sizeof(byte);
}
m_pbo_colors = double_pbo{m_colorsize * m_numLayers};
if(m_calib_files->isCompressedDepth()){
m_pbo_depths.size = m_resolution_depth.x * m_resolution_depth.y * m_numLayers * sizeof(byte);
m_depthsize = m_resolution_depth.x * m_resolution_depth.y * sizeof(byte);
}
else{
m_pbo_depths.size = m_resolution_depth.x * m_resolution_depth.y * m_numLayers * sizeof(float);
m_depthsize = m_resolution_depth.x * m_resolution_depth.y * sizeof(float);
}
m_pbo_depths = double_pbo{m_depthsize * m_numLayers};
/* kinect color: GL_RGB32F, GL_RGB, GL_FLOAT*/
/* kinect depth: GL_LUMINANCE32F_ARB, GL_RED, GL_FLOAT*/
//m_colorArray = new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_RGB32F, GL_RGB, GL_FLOAT);
if(m_calib_files->isCompressedRGB() == 1){
std::cout << "Color DXT 1 compressed" << std::endl;
m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_UNSIGNED_BYTE, m_colorsize)};
}
else if(m_calib_files->isCompressedRGB() == 5){
std::cout << "Color DXT 5 compressed" << std::endl;
m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_UNSIGNED_BYTE, m_colorsize)};
}
else{
m_colorArray = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE)};
}
m_colorArray_back = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_color.x, m_resolution_color.y, m_numLayers, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE)};
m_textures_color->image3D(0, GL_RGB32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RGB, GL_FLOAT, (void*)nullptr);
m_textures_quality->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr);
m_textures_normal->image3D(0, GL_RGB32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RGB, GL_FLOAT, (void*)nullptr);
std::vector<glm::fvec2> empty_bg_tex(m_resolution_depth.x * m_resolution_depth.y * m_numLayers, glm::fvec2{0.0f});
m_textures_bg.front->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, empty_bg_tex.data());
m_textures_bg.back->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, empty_bg_tex.data());
m_textures_silhouette->image3D(0, GL_R32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr);
if(m_calib_files->isCompressedDepth()){
m_depthArray_raw = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_LUMINANCE, GL_RED, GL_UNSIGNED_BYTE)};
}
else{
m_depthArray_raw = std::unique_ptr<TextureArray>{new TextureArray(m_resolution_depth.x, m_resolution_depth.y, m_numLayers, GL_LUMINANCE32F_ARB, GL_RED, GL_FLOAT)};
}
m_textures_depth->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, (void*)nullptr);
m_textures_depth_b->image3D(0, GL_RG32F, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RG, GL_FLOAT, (void*)nullptr);
m_textures_depth2.front->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr);
m_textures_depth2.back->image3D(0, GL_LUMINANCE32F_ARB, m_resolution_depth.x, m_resolution_depth.y, m_numLayers, 0, GL_RED, GL_FLOAT, (void*)nullptr);
m_depthArray_raw->setMAGMINFilter(GL_NEAREST);
m_textures_depth_b->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_textures_depth_b->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_textures_depth->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_textures_depth->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_textures_depth2.front->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_textures_depth2.front->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_textures_depth2.back->setParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST);
m_textures_depth2.back->setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST);
m_texture_unit_offsets.emplace("morph_input", 42);
m_texture_unit_offsets.emplace("raw_depth", 40);
// m_texture_unit_offsets.emplace("bg_depth", 41);
m_programs.at("filter")->setUniform("kinect_depths", getTextureUnit("raw_depth"));
glm::fvec2 tex_size_inv{1.0f/m_resolution_depth.x, 1.0f/m_resolution_depth.y};
m_programs.at("filter")->setUniform("texSizeInv", tex_size_inv);
m_programs.at("normal")->setUniform("texSizeInv", tex_size_inv);
m_programs.at("quality")->setUniform("texSizeInv", tex_size_inv);
m_programs.at("quality")->setUniform("camera_positions", m_calib_vols->getCameraPositions());
m_programs.at("morph")->setUniform("texSizeInv", tex_size_inv);
m_programs.at("morph")->setUniform("kinect_depths", getTextureUnit("morph_input"));
m_programs.at("boundary")->setUniform("texSizeInv", tex_size_inv);
// m_programs.at("bg")->setUniform("bg_depths", getTextureUnit("bg_depth"));
globjects::NamedString::create("/inc_bbox_test.glsl", new globjects::File("glsl/inc_bbox_test.glsl"));
globjects::NamedString::create("/inc_color.glsl", new globjects::File("glsl/inc_color.glsl"));
TimerDatabase::instance().addTimer("morph");
TimerDatabase::instance().addTimer("bilateral");
TimerDatabase::instance().addTimer("boundary");
TimerDatabase::instance().addTimer("normal");
TimerDatabase::instance().addTimer("quality");
TimerDatabase::instance().addTimer("1preprocess");
return true;
}
NetKinectArray::~NetKinectArray(){
m_running = false;
m_readThread->join();
}
bool
NetKinectArray::update() {
// lock pbos before checking status
std::unique_lock<std::mutex> lock(m_mutex_pbo);
// skip if no new frame was received
if(!m_pbo_colors.dirty || !m_pbo_depths.dirty) return false;
m_colorArray->fillLayersFromPBO(m_pbo_colors.get()->id());
m_depthArray_raw->fillLayersFromPBO(m_pbo_depths.get()->id());
// processTextures();
return true;
}
glm::uvec2 NetKinectArray::getDepthResolution() const {
return m_resolution_depth;
}
glm::uvec2 NetKinectArray::getColorResolution() const {
return m_resolution_color;
}
int NetKinectArray::getTextureUnit(std::string const& name) const {
return m_texture_unit_offsets.at(name);
}
void NetKinectArray::processDepth() {
m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0});
glActiveTexture(GL_TEXTURE0 + getTextureUnit("morph_input"));
m_depthArray_raw->bind();
m_programs.at("morph")->use();
m_programs.at("morph")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits());
// erode
m_programs.at("morph")->setUniform("mode", 0u);
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth2.back, 0, i);
m_programs.at("morph")->setUniform("layer", i);
ScreenQuad::draw();
}
// dilate
m_programs.at("morph")->setUniform("mode", 1u);
m_textures_depth2.swapBuffers();
m_textures_depth2.front->bindActive(getTextureUnit("morph_input"));
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth2.back, 0, i);
m_programs.at("morph")->setUniform("layer", i);
ScreenQuad::draw();
}
m_textures_depth2.front->unbindActive(getTextureUnit("morph_input"));
m_programs.at("morph")->release();
m_textures_depth2.swapBuffers();
m_textures_depth2.front->bindActive(getTextureUnit("morph_depth"));
if(m_use_processed_depth) {
m_textures_depth2.front->bindActive(getTextureUnit("raw_depth"));
}
}
void NetKinectArray::processBackground() {
m_textures_bg.front->bindActive(getTextureUnit("bg_depth"));
m_programs.at("bg")->use();
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_bg.back, 0, i);
m_programs.at("bg")->setUniform("layer", i);
ScreenQuad::draw();
}
m_programs.at("bg")->release();
m_textures_bg.swapBuffers();
m_textures_bg.front->bindActive(getTextureUnit("bg"));
++m_num_frame;
}
void NetKinectArray::processTextures(){
TimerDatabase::instance().begin("1preprocess");
GLint current_fbo;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, ¤t_fbo);
GLsizei old_vp_params[4];
glGetIntegerv(GL_VIEWPORT, old_vp_params);
glViewport(0, 0, m_resolution_depth.x, m_resolution_depth.y);
glActiveTexture(GL_TEXTURE0 + getTextureUnit("raw_depth"));
m_depthArray_raw->bind();
m_fbo->bind();
TimerDatabase::instance().begin("morph");
processDepth();
TimerDatabase::instance().end("morph");
TimerDatabase::instance().begin("bilateral");
m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1});
m_programs.at("filter")->use();
m_programs.at("filter")->setUniform("filter_textures", m_filter_textures);
m_programs.at("filter")->setUniform("processed_depth", m_use_processed_depth);
m_programs.at("filter")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits());
m_programs.at("filter")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits());
// depth and old quality
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_programs.at("filter")->setUniform("cv_min_ds", m_calib_vols->getDepthLimits(i).x);
m_programs.at("filter")->setUniform("cv_max_ds", m_calib_vols->getDepthLimits(i).y);
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth, 0, i);
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT1, m_textures_color, 0, i);
m_programs.at("filter")->setUniform("layer", i);
m_programs.at("filter")->setUniform("compress", m_calib_files->getCalibs()[i].isCompressedDepth());
const float near = m_calib_files->getCalibs()[i].getNear();
const float far = m_calib_files->getCalibs()[i].getFar();
const float scale = (far - near);
m_programs.at("filter")->setUniform("scale", scale);
m_programs.at("filter")->setUniform("near", near);
m_programs.at("filter")->setUniform("scaled_near", scale/255.0f);
ScreenQuad::draw();
}
m_programs.at("filter")->release();
TimerDatabase::instance().end("bilateral");
// boundary
TimerDatabase::instance().begin("boundary");
m_programs.at("boundary")->use();
m_programs.at("boundary")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits());
m_programs.at("boundary")->setUniform("refine", m_refine_bound);
m_textures_depth->bindActive(getTextureUnit("depth"));
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_depth_b, 0, i);
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT1, m_textures_silhouette, 0, i);
m_programs.at("boundary")->setUniform("layer", i);
ScreenQuad::draw();
}
m_programs.at("boundary")->release();
TimerDatabase::instance().end("boundary");
m_textures_depth_b->bindActive(getTextureUnit("depth"));
// normals
TimerDatabase::instance().begin("normal");
m_programs.at("normal")->use();
m_programs.at("normal")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits());
m_programs.at("normal")->setUniform("cv_uv", m_calib_vols->getUVVolumeUnits());
m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0});
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_normal, 0, i);
m_programs.at("normal")->setUniform("layer", i);
ScreenQuad::draw();
}
m_programs.at("normal")->release();
TimerDatabase::instance().end("normal");
// quality
TimerDatabase::instance().begin("quality");
m_fbo->setDrawBuffers({GL_COLOR_ATTACHMENT0});
m_programs.at("quality")->use();
m_programs.at("quality")->setUniform("cv_xyz", m_calib_vols->getXYZVolumeUnits());
m_programs.at("quality")->setUniform("processed_depth", m_use_processed_depth);
for(unsigned i = 0; i < m_calib_files->num(); ++i){
m_fbo->attachTextureLayer(GL_COLOR_ATTACHMENT0, m_textures_quality, 0, i);
m_programs.at("quality")->setUniform("layer", i);
ScreenQuad::draw();
}
m_programs.at("quality")->release();
TimerDatabase::instance().end("quality");
if(m_num_frame < s_num_bg_frames && m_curr_frametime < 0.5) {
// processBackground();
}
m_fbo->unbind();
glViewport ((GLsizei)old_vp_params[0],
(GLsizei)old_vp_params[1],
(GLsizei)old_vp_params[2],
(GLsizei)old_vp_params[3]);
TimerDatabase::instance().end("1preprocess");
}
void NetKinectArray::setStartTextureUnit(unsigned start_texture_unit) {
m_start_texture_unit = start_texture_unit;
m_texture_unit_offsets["color"] = m_start_texture_unit;
m_texture_unit_offsets["depth"] = m_start_texture_unit + 1;
m_texture_unit_offsets["quality"] = m_start_texture_unit + 2;
m_texture_unit_offsets["normal"] = m_start_texture_unit + 3;
m_texture_unit_offsets["silhouette"] = m_start_texture_unit + 4;
// m_texture_unit_offsets["bg"] = m_start_texture_unit + 5;
m_texture_unit_offsets["morph_depth"] = m_start_texture_unit + 5;
m_texture_unit_offsets["color_lab"] = m_start_texture_unit + 6;
bindToTextureUnits();
m_programs.at("filter")->setUniform("kinect_colors", getTextureUnit("color"));
m_programs.at("normal")->setUniform("kinect_depths", getTextureUnit("depth"));
m_programs.at("quality")->setUniform("kinect_depths", getTextureUnit("depth"));
m_programs.at("quality")->setUniform("kinect_normals", getTextureUnit("normal"));
m_programs.at("quality")->setUniform("kinect_colors_lab", getTextureUnit("color_lab"));
m_programs.at("boundary")->setUniform("kinect_colors_lab", getTextureUnit("color_lab"));
m_programs.at("boundary")->setUniform("kinect_depths", getTextureUnit("depth"));
m_programs.at("boundary")->setUniform("kinect_colors", getTextureUnit("color"));
}
void NetKinectArray::bindToTextureUnits() const {
glActiveTexture(GL_TEXTURE0 + getTextureUnit("color"));
m_colorArray->bind();
m_textures_quality->bindActive(getTextureUnit("quality"));
m_textures_normal->bindActive(getTextureUnit("normal"));
m_textures_silhouette->bindActive(getTextureUnit("silhouette"));
// m_textures_bg.front->bindActive(getTextureUnit("bg"));
m_textures_depth2.front->bindActive(getTextureUnit("morph_depth"));
m_textures_color->bindActive(getTextureUnit("color_lab"));
glActiveTexture(GL_TEXTURE0 + getTextureUnit("raw_depth"));
m_depthArray_raw->bind();
}
unsigned NetKinectArray::getStartTextureUnit() const {
return m_start_texture_unit;
}
void NetKinectArray::filterTextures(bool filter) {
m_filter_textures = filter;
// process with new settings
processTextures();
}
void NetKinectArray::useProcessedDepths(bool filter) {
m_use_processed_depth = filter;
processTextures();
}
void NetKinectArray::refineBoundary(bool filter) {
m_refine_bound = filter;
processTextures();
}
void NetKinectArray::readLoop(){
// open multicast listening connection to server and port
zmq::context_t ctx(1); // means single threaded
zmq::socket_t socket(ctx, ZMQ_SUB); // means a subscriber
socket.setsockopt(ZMQ_SUBSCRIBE, "", 0);
uint32_t hwm = 1;
socket.setsockopt(ZMQ_RCVHWM, &hwm, sizeof(hwm));
std::string endpoint("tcp://" + m_serverport);
socket.connect(endpoint.c_str());
zmq::socket_t slave_socket(ctx, ZMQ_SUB); // means a subscriber
slave_socket.setsockopt(ZMQ_SUBSCRIBE, "", 0);
uint32_t slave_hwm = 1;
slave_socket.setsockopt(ZMQ_RCVHWM, &slave_hwm, sizeof(slave_hwm));
std::string slave_endpoint("tcp://" + m_slaveport);
slave_socket.connect(slave_endpoint.c_str());
//const unsigned pixelcountc = m_calib_files->getWidthC() * m_calib_files->getHeightC();
const unsigned colorsize = m_colorsize;
const unsigned depthsize = m_depthsize;//pixelcount * sizeof(float);
double current_time = 0.0;
while(m_running){
zmq::message_t zmqm((colorsize + depthsize) * m_calib_files->num());
if(1 == m_streamslot){
slave_socket.recv(&zmqm); // blocking
}
else{
socket.recv(&zmqm); // blocking
}
{
// lock pbos
std::unique_lock<std::mutex> lock(m_mutex_pbo);
memcpy(¤t_time, (byte*)zmqm.data(), sizeof(double));
// std::cout << "time " << current_time << std::endl;
m_curr_frametime = current_time;
unsigned offset = 0;
// receive data
const unsigned number_of_kinects = m_calib_files->num(); // is 5 in the current example
// this loop goes over each kinect like K1_frame_1 K2_frame_1 K3_frame_1
for(unsigned i = 0; i < number_of_kinects; ++i){
memcpy((byte*) m_pbo_colors.pointer() + i*colorsize , (byte*) zmqm.data() + offset, colorsize);
offset += colorsize;
memcpy((byte*) m_pbo_depths.pointer() + i*depthsize , (byte*) zmqm.data() + offset, depthsize);
offset += depthsize;
}
// swap
m_pbo_colors.dirty = true;
m_pbo_depths.dirty = true;
}
}
}
void
NetKinectArray::writeCurrentTexture(std::string prefix){
//depths
if (m_calib_files->isCompressedDepth())
{
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D_ARRAY,m_depthArray_raw->getGLHandle());
int width, height, depth;
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth);
std::vector<std::uint8_t> depths;
depths.resize(width*height*depth);
glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RED, GL_UNSIGNED_BYTE, (void*)&depths[0]);
int offset = 0;
for (int k = 0; k < depth; ++k)
{
std::stringstream sstr;
sstr << "output/" << prefix << "_d_" << k << ".bmp";
std::string filename (sstr.str());
std::cout << "writing depth texture for kinect " << k << " to file " << filename << std::endl;
offset += width*height;
writeBMP(filename, depths, offset, 1);
offset += width*height;
}
}
else
{
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D_ARRAY,m_depthArray_raw->getGLHandle());
int width, height, depth;
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth);
std::vector<float> depthsTmp;
depthsTmp.resize(width*height*depth);
glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RED, GL_FLOAT, (void*)&depthsTmp[0]);
std::vector<std::uint8_t> depths;
depths.resize(depthsTmp.size());
for (int i = 0; i < width*height*depth; ++i)
{
depths[i] = (std::uint8_t)depthsTmp[i] * 255.0f;
}
int offset = 0;
for (int k = 0; k < depth; ++k)
{
std::stringstream sstr;
sstr << "output/" << prefix << "_d_" << k << ".bmp";
std::string filename (sstr.str());
std::cout << "writing depth texture for kinect " << k << " to file " << filename << " (values are compressed to 8bit)" << std::endl;
writeBMP(filename, depths, offset, 1);
offset += width*height;
}
}
//color
if (m_calib_files->isCompressedRGB() == 1)
{
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D_ARRAY,m_colorArray->getGLHandle());
int size;
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &size);
std::vector<std::uint8_t> data;
data.resize(size);
glGetCompressedTexImage(GL_TEXTURE_2D_ARRAY, 0, (void*)&data[0]);
std::vector<std::uint8_t> colors;
colors.resize(4*m_resolution_color.x*m_resolution_color.y);
for (unsigned k = 0; k < m_numLayers; ++k)
{
squish::DecompressImage (&colors[0], m_resolution_color.x, m_resolution_color.y, &data[k*m_colorsize], squish::kDxt1);
std::stringstream sstr;
sstr << "output/" << prefix << "_col_" << k << ".bmp";
std::string filename (sstr.str());
std::cout << "writing color texture for kinect " << k << " to file " << filename << std::endl;
writeBMP(filename, colors, 0, 4);
}
}
else
{
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D_ARRAY,m_colorArray->getGLHandle());
int width, height, depth;
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_HEIGHT, &height);
glGetTexLevelParameteriv (GL_TEXTURE_2D_ARRAY, 0, GL_TEXTURE_DEPTH, &depth);
std::vector<std::uint8_t> colors;
colors.resize(3*width*height*depth);
glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RGB, GL_UNSIGNED_BYTE, (void*)&colors[0]);
int offset = 0;
for (int k = 0; k < depth; ++k)
{
std::stringstream sstr;
sstr << "output/" << prefix << "_col_" << k << ".bmp";
std::string filename (sstr.str());
std::cout << "writing color texture for kinect " << k << " to file " << filename << std::endl;
writeBMP(filename, colors, offset, 3);
offset += 3 * width*height;
}
}
}
// no universal use! very unflexible, resolution depth = resolution color, no row padding
void NetKinectArray::writeBMP(std::string filename, std::vector<std::uint8_t> const& data, unsigned int offset, unsigned int bytesPerPixel)
{
std::ofstream file (filename, std::ofstream::binary);
char c;
short s;
int i;
c = 'B'; file.write(&c, 1);
c = 'M'; file.write(&c, 1);
i = m_resolution_color.x * m_resolution_color.y * 3 + 54; file.write((char const*) &i, 4);
i = 0; file.write((char const*) &i,4);
i = 54; file.write((char const*) &i, 4);
i = 40; file.write((char const*) &i, 4);
i = m_resolution_color.x; file.write((char const*) &i, 4);
i = m_resolution_color.y; file.write((char const*) &i, 4);
s = 1; file.write((char const*) &s, 2);
s = 24; file.write((char const*) &s, 2);
i = 0; file.write((char const*) &i, 4);
i = m_resolution_color.x * m_resolution_color.y * 3; file.write((char const*) &i, 4);
i = 0; file.write((char const*) &i, 4);
i = 0; file.write((char const*) &i, 4);
i = 0; file.write((char const*) &i, 4);
i = 0; file.write((char const*) &i, 4);
for (unsigned int h = m_resolution_color.y; h > 0; --h)
{
for (unsigned int w = 0; w < m_resolution_color.x * bytesPerPixel; w += bytesPerPixel)
{
if (bytesPerPixel == 1)
{
file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
file.write((char const*) &data[offset + w + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
}
else if (bytesPerPixel == 3 || bytesPerPixel == 4)
{
file.write((char const*) &data[offset + w+2 + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
file.write((char const*) &data[offset + w+1 + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
file.write((char const*) &data[offset + w+0 + (h-1) * m_resolution_color.x * bytesPerPixel], 1);
}
}
}
file.close();
}
void
NetKinectArray::readFromFiles(){
std::vector<sys::FileBuffer*> fbs;
for(unsigned i = 0 ; i < m_calib_files->num(); ++i){
std::string yml(m_calib_files->getCalibs()[i]._filePath);
std::string base((const char*) basename((char *) yml.c_str()));
base.replace( base.end() - 4, base.end(), "");
std::string filename = std::string("recordings/" + base + ".stream");
fbs.push_back(new sys::FileBuffer(filename.c_str()));
if(!fbs.back()->open("r")){
std::cerr << "error opening " << filename << " exiting..." << std::endl;
exit(1);
}
fbs.back()->setLooping(/*true*/false);
}
const unsigned colorsize = m_colorsize;
const unsigned depthsize = m_depthsize;
{
// lock pbos
std::unique_lock<std::mutex> lock(m_mutex_pbo);
unsigned offset = 0;
// receive data
for(unsigned i = 0; i < m_calib_files->num(); ++i){
//memcpy((byte*) m_pbo_colors.pointer() + i*colorsize , (byte*) zmqm.data() + offset, colorsize);
fbs[i]->read((byte*) m_pbo_colors.pointer() + i*colorsize, colorsize);
offset += colorsize;
//memcpy((byte*) m_pbo_depths.pointer() + i*depthsize , (byte*) zmqm.data() + offset, depthsize);
fbs[i]->read((byte*) m_pbo_depths.pointer() + i*depthsize, depthsize);
offset += depthsize;
}
m_pbo_colors.dirty = true;
m_pbo_depths.dirty = true;
}
}
void
NetKinectArray::updateInputSocket(unsigned stream_slot){
if(stream_slot != m_streamslot){
m_streamslot = stream_slot;
}
}
}
| 38.837209 | 225 | 0.699235 | steppobeck |
125ddaa64893c1bc5fb3d87b467e692bac094343 | 14,229 | cpp | C++ | model/mosesdecoder/moses/TranslationModel/PhraseDictionaryGroup.cpp | saeedesm/UNMT_AH | cc171bf66933b5c0ad8a0ab87e57f7364312a7df | [
"Apache-2.0"
] | 3 | 2020-02-28T21:42:44.000Z | 2021-03-12T13:56:16.000Z | tools/mosesdecoder-master/moses/TranslationModel/PhraseDictionaryGroup.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-11-06T14:40:10.000Z | 2020-12-29T19:03:11.000Z | tools/mosesdecoder-master/moses/TranslationModel/PhraseDictionaryGroup.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2019-11-26T05:27:16.000Z | 2019-12-17T01:53:43.000Z | /***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "moses/TranslationModel/PhraseDictionaryGroup.h"
#include <boost/foreach.hpp>
#include <boost/unordered_map.hpp>
#include "util/exception.hh"
using namespace std;
using namespace boost;
namespace Moses
{
PhraseDictionaryGroup::PhraseDictionaryGroup(const string &line)
: PhraseDictionary(line, true),
m_numModels(0),
m_totalModelScores(0),
m_phraseCounts(false),
m_wordCounts(false),
m_modelBitmapCounts(false),
m_restrict(false),
m_haveDefaultScores(false),
m_defaultAverageOthers(false),
m_scoresPerModel(0),
m_haveMmsaptLrFunc(false)
{
ReadParameters();
}
void PhraseDictionaryGroup::SetParameter(const string& key, const string& value)
{
if (key == "members") {
m_memberPDStrs = Tokenize(value, ",");
m_numModels = m_memberPDStrs.size();
m_seenByAll = dynamic_bitset<>(m_numModels);
m_seenByAll.set();
} else if (key == "restrict") {
m_restrict = Scan<bool>(value);
} else if (key == "phrase-counts") {
m_phraseCounts = Scan<bool>(value);
} else if (key == "word-counts") {
m_wordCounts = Scan<bool>(value);
} else if (key == "model-bitmap-counts") {
m_modelBitmapCounts = Scan<bool>(value);
} else if (key =="default-scores") {
m_haveDefaultScores = true;
m_defaultScores = Scan<float>(Tokenize(value, ","));
} else if (key =="default-average-others") {
m_defaultAverageOthers = Scan<bool>(value);
} else if (key =="mmsapt-lr-func") {
m_haveMmsaptLrFunc = true;
} else {
PhraseDictionary::SetParameter(key, value);
}
}
void PhraseDictionaryGroup::Load(AllOptions::ptr const& opts)
{
m_options = opts;
SetFeaturesToApply();
m_pdFeature.push_back(const_cast<PhraseDictionaryGroup*>(this));
size_t numScoreComponents = 0;
// Locate/check component phrase tables
BOOST_FOREACH(const string& pdName, m_memberPDStrs) {
bool pdFound = false;
BOOST_FOREACH(PhraseDictionary* pd, PhraseDictionary::GetColl()) {
if (pd->GetScoreProducerDescription() == pdName) {
pdFound = true;
m_memberPDs.push_back(pd);
size_t nScores = pd->GetNumScoreComponents();
numScoreComponents += nScores;
if (m_scoresPerModel == 0) {
m_scoresPerModel = nScores;
} else if (m_defaultAverageOthers) {
UTIL_THROW_IF2(nScores != m_scoresPerModel,
m_description << ": member models must have the same number of scores when using default-average-others");
}
}
}
UTIL_THROW_IF2(!pdFound,
m_description << ": could not find member phrase table " << pdName);
}
m_totalModelScores = numScoreComponents;
// Check feature total
if (m_phraseCounts) {
numScoreComponents += m_numModels;
}
if (m_wordCounts) {
numScoreComponents += m_numModels;
}
if (m_modelBitmapCounts) {
numScoreComponents += (pow(2, m_numModels) - 1);
}
UTIL_THROW_IF2(numScoreComponents != m_numScoreComponents,
m_description << ": feature count mismatch: specify \"num-features=" << numScoreComponents << "\" and supply " << numScoreComponents << " weights");
#ifdef PT_UG
// Locate mmsapt lexical reordering functions if specified
if (m_haveMmsaptLrFunc) {
BOOST_FOREACH(PhraseDictionary* pd, m_memberPDs) {
// pointer to pointer, all start as NULL and some may be populated prior
// to translation
m_mmsaptLrFuncs.push_back(&(static_cast<Mmsapt*>(pd)->m_lr_func));
}
}
#endif
// Determine "zero" scores for features
if (m_haveDefaultScores) {
UTIL_THROW_IF2(m_defaultScores.size() != m_numScoreComponents,
m_description << ": number of specified default scores is unequal to number of member model scores");
} else {
// Default is all 0 (as opposed to e.g. -99 or similar to approximate log(0)
// or a smoothed "not in model" score)
m_defaultScores = vector<float>(m_numScoreComponents, 0);
}
}
void PhraseDictionaryGroup::InitializeForInput(const ttasksptr& ttask)
{
// Member models are registered as FFs and should already be initialized
}
void PhraseDictionaryGroup::GetTargetPhraseCollectionBatch(
const ttasksptr& ttask, const InputPathList& inputPathQueue) const
{
// Some implementations (mmsapt) do work in PrefixExists
BOOST_FOREACH(const InputPath* inputPath, inputPathQueue) {
const Phrase& phrase = inputPath->GetPhrase();
BOOST_FOREACH(const PhraseDictionary* pd, m_memberPDs) {
pd->PrefixExists(ttask, phrase);
}
}
// Look up each input in each model
BOOST_FOREACH(InputPath* inputPath, inputPathQueue) {
const Phrase &phrase = inputPath->GetPhrase();
TargetPhraseCollection::shared_ptr targetPhrases =
this->GetTargetPhraseCollectionLEGACY(ttask, phrase);
inputPath->SetTargetPhrases(*this, targetPhrases, NULL);
}
}
TargetPhraseCollection::shared_ptr PhraseDictionaryGroup::GetTargetPhraseCollectionLEGACY(
const Phrase& src) const
{
UTIL_THROW2("Don't call me without the translation task.");
}
TargetPhraseCollection::shared_ptr
PhraseDictionaryGroup::
GetTargetPhraseCollectionLEGACY(const ttasksptr& ttask, const Phrase& src) const
{
TargetPhraseCollection::shared_ptr ret
= CreateTargetPhraseCollection(ttask, src);
ret->NthElement(m_tableLimit); // sort the phrases for pruning later
const_cast<PhraseDictionaryGroup*>(this)->CacheForCleanup(ret);
return ret;
}
TargetPhraseCollection::shared_ptr
PhraseDictionaryGroup::
CreateTargetPhraseCollection(const ttasksptr& ttask, const Phrase& src) const
{
// Aggregation of phrases and corresponding statistics (scores, models seen by)
vector<TargetPhrase*> phraseList;
typedef unordered_map<const TargetPhrase*, PDGroupPhrase, UnorderedComparer<Phrase>, UnorderedComparer<Phrase> > PhraseMap;
PhraseMap phraseMap;
// For each model
size_t offset = 0;
for (size_t i = 0; i < m_numModels; ++i) {
// Collect phrases from this table
const PhraseDictionary& pd = *m_memberPDs[i];
TargetPhraseCollection::shared_ptr
ret_raw = pd.GetTargetPhraseCollectionLEGACY(ttask, src);
if (ret_raw != NULL) {
// Process each phrase from table
BOOST_FOREACH(const TargetPhrase* targetPhrase, *ret_raw) {
vector<float> raw_scores =
targetPhrase->GetScoreBreakdown().GetScoresForProducer(&pd);
// Phrase not in collection -> add if unrestricted or first model
PhraseMap::iterator iter = phraseMap.find(targetPhrase);
if (iter == phraseMap.end()) {
if (m_restrict && i > 0) {
continue;
}
// Copy phrase to avoid disrupting base model
TargetPhrase* phrase = new TargetPhrase(*targetPhrase);
// Correct future cost estimates and total score
phrase->GetScoreBreakdown().InvertDenseFeatures(&pd);
vector<FeatureFunction*> pd_feature;
pd_feature.push_back(m_memberPDs[i]);
const vector<FeatureFunction*> pd_feature_const(pd_feature);
phrase->EvaluateInIsolation(src, pd_feature_const);
// Zero out scores from original phrase table
phrase->GetScoreBreakdown().ZeroDenseFeatures(&pd);
// Add phrase entry
phraseList.push_back(phrase);
phraseMap[targetPhrase] = PDGroupPhrase(phrase, m_defaultScores, m_numModels);
} else {
// For existing phrases: merge extra scores (such as lr-func scores for mmsapt)
TargetPhrase* phrase = iter->second.m_targetPhrase;
BOOST_FOREACH(const TargetPhrase::ScoreCache_t::value_type pair, targetPhrase->GetExtraScores()) {
phrase->SetExtraScores(pair.first, pair.second);
}
}
// Don't repeat lookup if phrase already found
PDGroupPhrase& pdgPhrase = (iter == phraseMap.end()) ? phraseMap.find(targetPhrase)->second : iter->second;
// Copy scores from this model
for (size_t j = 0; j < pd.GetNumScoreComponents(); ++j) {
pdgPhrase.m_scores[offset + j] = raw_scores[j];
}
// Phrase seen by this model
pdgPhrase.m_seenBy[i] = true;
}
}
offset += pd.GetNumScoreComponents();
}
// Compute additional scores as phrases are added to return collection
TargetPhraseCollection::shared_ptr ret(new TargetPhraseCollection);
const vector<FeatureFunction*> pd_feature_const(m_pdFeature);
BOOST_FOREACH(TargetPhrase* phrase, phraseList) {
PDGroupPhrase& pdgPhrase = phraseMap.find(phrase)->second;
// Score order (example with 2 models)
// member1_scores member2_scores [m1_pc m2_pc] [m1_wc m2_wc]
// Extra scores added after member model scores
size_t offset = m_totalModelScores;
// Phrase count (per member model)
if (m_phraseCounts) {
for (size_t i = 0; i < m_numModels; ++i) {
if (pdgPhrase.m_seenBy[i]) {
pdgPhrase.m_scores[offset + i] = 1;
}
}
offset += m_numModels;
}
// Word count (per member model)
if (m_wordCounts) {
size_t wc = pdgPhrase.m_targetPhrase->GetSize();
for (size_t i = 0; i < m_numModels; ++i) {
if (pdgPhrase.m_seenBy[i]) {
pdgPhrase.m_scores[offset + i] = wc;
}
}
offset += m_numModels;
}
// Model bitmap features (one feature per possible bitmap)
// e.g. seen by models 1 and 3 but not 2 -> "101" fires
if (m_modelBitmapCounts) {
// Throws exception if someone tries to combine more than 64 models
pdgPhrase.m_scores[offset + (pdgPhrase.m_seenBy.to_ulong() - 1)] = 1;
offset += m_seenByAll.to_ulong();
}
// Average other-model scores to fill in defaults when models have not seen
// this phrase
if (m_defaultAverageOthers) {
// Average seen scores
if (pdgPhrase.m_seenBy != m_seenByAll) {
vector<float> avgScores(m_scoresPerModel, 0);
size_t seenBy = 0;
offset = 0;
// sum
for (size_t i = 0; i < m_numModels; ++i) {
if (pdgPhrase.m_seenBy[i]) {
for (size_t j = 0; j < m_scoresPerModel; ++j) {
avgScores[j] += pdgPhrase.m_scores[offset + j];
}
seenBy += 1;
}
offset += m_scoresPerModel;
}
// divide
for (size_t j = 0; j < m_scoresPerModel; ++j) {
avgScores[j] /= seenBy;
}
// copy
offset = 0;
for (size_t i = 0; i < m_numModels; ++i) {
if (!pdgPhrase.m_seenBy[i]) {
for (size_t j = 0; j < m_scoresPerModel; ++j) {
pdgPhrase.m_scores[offset + j] = avgScores[j];
}
}
offset += m_scoresPerModel;
}
#ifdef PT_UG
// Also average LexicalReordering scores if specified
// We don't necessarily have a lr-func for each model
if (m_haveMmsaptLrFunc) {
SPTR<Scores> avgLRScores;
size_t seenBy = 0;
// For each model
for (size_t i = 0; i < m_numModels; ++i) {
const LexicalReordering* lrFunc = *m_mmsaptLrFuncs[i];
// Add if phrase seen and model has lr-func
if (pdgPhrase.m_seenBy[i] && lrFunc != NULL) {
const Scores* scores = pdgPhrase.m_targetPhrase->GetExtraScores(lrFunc);
if (!avgLRScores) {
avgLRScores.reset(new Scores(*scores));
} else {
for (size_t j = 0; j < scores->size(); ++j) {
(*avgLRScores)[j] += (*scores)[j];
}
}
seenBy += 1;
}
}
// Make sure we have at least one lr-func
if (avgLRScores) {
// divide
for (size_t j = 0; j < avgLRScores->size(); ++j) {
(*avgLRScores)[j] /= seenBy;
}
// set
for (size_t i = 0; i < m_numModels; ++i) {
const LexicalReordering* lrFunc = *m_mmsaptLrFuncs[i];
if (!pdgPhrase.m_seenBy[i] && lrFunc != NULL) {
pdgPhrase.m_targetPhrase->SetExtraScores(lrFunc, avgLRScores);
}
}
}
}
#endif
}
}
// Assign scores
phrase->GetScoreBreakdown().Assign(this, pdgPhrase.m_scores);
// Correct future cost estimates and total score
phrase->EvaluateInIsolation(src, pd_feature_const);
ret->Add(phrase);
}
return ret;
}
ChartRuleLookupManager*
PhraseDictionaryGroup::
CreateRuleLookupManager(const ChartParser &,
const ChartCellCollectionBase&, size_t)
{
UTIL_THROW(util::Exception, "Phrase table used in chart decoder");
}
//copied from PhraseDictionaryCompact; free memory allocated to TargetPhraseCollection (and each TargetPhrase) at end of sentence
void PhraseDictionaryGroup::CacheForCleanup(TargetPhraseCollection::shared_ptr tpc)
{
PhraseCache &ref = GetPhraseCache();
ref.push_back(tpc);
}
void
PhraseDictionaryGroup::
CleanUpAfterSentenceProcessing(const InputType &source)
{
GetPhraseCache().clear();
CleanUpComponentModels(source);
}
void PhraseDictionaryGroup::CleanUpComponentModels(const InputType &source)
{
for (size_t i = 0; i < m_numModels; ++i) {
m_memberPDs[i]->CleanUpAfterSentenceProcessing(source);
}
}
} //namespace
| 35.5725 | 165 | 0.651416 | saeedesm |
125df8b5f954eddad4082bb67c7af71efd62f669 | 1,897 | cc | C++ | client/tsf/display_attribute_unittest.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | client/tsf/display_attribute_unittest.cc | DalavanCloud/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | client/tsf/display_attribute_unittest.cc | DalavanCloud/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <atlbase.h>
#include <atlcom.h>
#include "common/smart_com_ptr.h"
#include "tsf/display_attribute.h"
#include <gtest/gtest_prod.h>
namespace ime_goopy {
namespace tsf {
const GUID kInputAttributeGUID = {
0x87046dce,
0x8eca,
0x45c1,
{0xa2, 0xd8, 0xcf, 0x92, 0x20, 0x61, 0x65, 0x25}
};
// A global vairant is required to use ATL.
CComModule _module;
TEST(DisplayAttribute, Enumerator) {
SmartComPtr<IEnumTfDisplayAttributeInfo> enumerator;
SmartComPtr<ITfDisplayAttributeInfo> information;
GUID guid;
ASSERT_EQ(S_OK, DisplayAttribute::CreateEnumerator(&enumerator));
ULONG fetched = 0;
// Regular usage.
ASSERT_EQ(S_OK, enumerator->Next(1, &information, &fetched));
EXPECT_EQ(1, fetched);
EXPECT_EQ(S_OK, information->GetGUID(&guid));
EXPECT_TRUE(IsEqualGUID(kInputAttributeGUID, guid));
// Reached the end.
information = NULL;
fetched = 0;
EXPECT_EQ(S_FALSE, enumerator->Next(1, &information, &fetched));
EXPECT_EQ(0, fetched);
// After reset.
information = NULL;
fetched = 0;
EXPECT_EQ(S_OK, enumerator->Reset());
ASSERT_EQ(S_OK, enumerator->Next(1, &information, &fetched));
EXPECT_EQ(1, fetched);
EXPECT_EQ(S_OK, information->GetGUID(&guid));
EXPECT_TRUE(IsEqualGUID(kInputAttributeGUID, guid));
}
} // namespace tsf
} // namespace ime_goopy
| 28.742424 | 74 | 0.735899 | zamorajavi |
125dfa4fbc0f4c504f0bcc1b2116a3f49b7abe53 | 12,181 | hpp | C++ | memory/shared-pointer.hpp | daleksla/STL | c9b107cb7434e123dc25f3e0d9e8423f6be0030a | [
"BSL-1.0"
] | 1 | 2021-03-01T05:03:52.000Z | 2021-03-01T05:03:52.000Z | memory/shared-pointer.hpp | daleksla/STL | c9b107cb7434e123dc25f3e0d9e8423f6be0030a | [
"BSL-1.0"
] | 3 | 2021-03-01T04:21:26.000Z | 2021-06-28T18:30:52.000Z | memory/shared-pointer.hpp | daleksla/STL | c9b107cb7434e123dc25f3e0d9e8423f6be0030a | [
"BSL-1.0"
] | null | null | null | #ifndef SHARED_POINTER_HPP
#define SHARED_POINTER_HPP
#include "base-pointer.hpp"
/** @brief Shared pointer class, which persists a dynamic resource until the last Shared pointer object is destroyed or reset
@author Salih Mahmoud Sayed Ahmed
@email ahmed233@uni.coventry.ac.uk
@date May 2021
**/
namespace salih {
namespace memory {
template<class T>
class SharedPointer : public Pointer<T> {
/** This class is the derived-class shared smart pointer implementation, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/
private:
unsigned long* count ;
public:
/** Empty constructor, intialises shared smart pointer container
@return <initialised-object> **/
SharedPointer() ;
/** Regular constructor, intialises shared smart pointer container
@param nullptr_t (special type indicating NULL)
@return <initialised-object> **/
SharedPointer(const decltype(nullptr)) ;
/** Regular constructor, intialises shared smart pointer container to point at T-type pointer
@param T* (raw pointer to object of type T)
@return <initialised-object> **/
SharedPointer(T*) ;
/** Regular constructor, intialises shared smart pointer container to void pointer
@param void* (raw void pointer)
@return <initialised-object> **/
explicit SharedPointer(void*) ;
/** Regular assignment operator, assigns null pointer to shared smart pointer
@param nullptr_t (special type indicating NULL)
@return reference to modified smart pointer **/
SharedPointer& operator=(const decltype(nullptr)) ;
/** Regular assignment operator, assigns null pointer to shared smart pointer
@param T* (raw pointer to object of type T)
@return reference to modified smart pointer **/
SharedPointer& operator=(T*) ;
/** Copy constructor, creates copy of a given shared smart pointer
@param a (l-value) base class reference
@return <initialised-object> **/
SharedPointer(const SharedPointer&) ;
/** Pseudo-copy constructor, creates copy of a given specialised void smart pointer
@param a (l-value) base class reference
@return <initialised-object> **/
explicit SharedPointer(const SharedPointer<void>&) ;
/** Copy assignment operator, creates copy of a given shared smart pointer
@param a (l-value) base class reference
@return reference to modified smart pointer **/
SharedPointer& operator=(const SharedPointer&) ;
/** Move constructor, takes ownership of a given shared smart pointer
@param an r-value object reference
@return <initialised-object> **/
SharedPointer(SharedPointer&&) ;
/** Pseudo-move constructor, takes ownership of a given specialised void shared smart pointer
@param an r-value object reference
@return <initialised-object> **/
explicit SharedPointer(SharedPointer<void>&&) ;
/** Move assignment operator, takes ownership of a given shared smart pointer
@param an r-value object reference
@return reference to modified smart pointer **/
SharedPointer& operator=(SharedPointer&&) ;
/** reset method, to appropriately disengage from pointing at data **/
void reset() ;
/** Destructor, frees memory if appropriate and deletes objects **/
~SharedPointer() ;
friend class SharedPointer<void> ;
} ;
template<class T>
class SharedPointer<T[]> : public Pointer<T[]> {
/** This class is the derived-class shared smart pointer implementation, specialised for dynamically allocated arrays, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/
private:
unsigned long* count ;
public:
/** Empty constructor, intialises shared smart pointer container
@return <initialised-object> **/
SharedPointer() ;
/** Regular constructor, intialises shared smart pointer container
@param nullptr_t (special type indicating NULL)
@return <initialised-object> **/
SharedPointer(const decltype(nullptr)) ;
/** Regular constructor, intialises shared smart pointer container to point at T-type pointer
@param T* (raw pointer to object of type T)
@return <initialised-object> **/
SharedPointer(T*) ;
/** Regular constructor, intialises shared smart pointer container to void pointer
@param void* (raw void pointer)
@return <initialised-object> **/
explicit SharedPointer(void*) ;
/** Regular assignment operator, assigns null pointer to shared smart pointer
@param nullptr_t (special type indicating NULL)
@return reference to modified smart pointer **/
SharedPointer& operator=(const decltype(nullptr)) ;
/** Regular assignment operator, assigns null pointer to shared smart pointer
@param T* (raw pointer to object of type T)
@return reference to modified smart pointer **/
SharedPointer& operator=(T*) ;
/** Copy constructor, creates copy of a given shared smart pointer
@param a (l-value) base class reference
@return <initialised-object> **/
SharedPointer(const SharedPointer&) ;
/** Pseudo-copy constructor, creates copy of a given specialised void smart pointer
@param a (l-value) base class reference
@return <initialised-object> **/
explicit SharedPointer(const SharedPointer<void>&) ;
/** Copy assignment operator, creates copy of a given shared smart pointer
@param a (l-value) base class reference
@return reference to modified smart pointer **/
SharedPointer& operator=(const SharedPointer&) ;
/** Move constructor, takes ownership of a given shared smart pointer
@param an r-value object reference
@return <initialised-object> **/
SharedPointer(SharedPointer&&) ;
/** Pseudo-move constructor, takes ownership of a given specialised void shared smart pointer
@param an r-value object reference
@return <initialised-object> **/
explicit SharedPointer(SharedPointer<void>&&) ;
/** Move assignment operator, takes ownership of a given shared smart pointer
@param an r-value object reference
@return reference to modified smart pointer **/
SharedPointer& operator=(SharedPointer&&) ;
/** reset method, to appropriately disengage from pointing at data **/
void reset() ;
/** Destructor, frees memory if appropriate and deletes objects **/
~SharedPointer() ;
friend class SharedPointer<void> ;
} ;
template<>
class SharedPointer<void> : public Pointer<void> {
/** This class is the derived-class shared smart pointer implementation, specialised for void pointer usage, which allows for the sharing and existence of a piece of memory till no shared pointer at all is making use of the pointed-to resource **/
private:
unsigned long* count ;
public:
/** Empty constructor, intialises shared smart pointer container
@return <initialised-object> **/
SharedPointer() ;
/** Regular constructor, intialises shared smart pointer container
@param nullptr_t (special type indicating NULL)
@return <initialised-object> **/
SharedPointer(const decltype(nullptr)) ;
/** Regular constructor, intialises shared smart pointer container to point at T-type pointer
@param T* (raw pointer to object of type T)
@return <initialised-object> **/
template<typename T>
SharedPointer(T*) ;
SharedPointer(void*) = delete ;
/** Regular assignment operator, assigns null pointer to shared smart pointer
@param nullptr_t (special type indicating NULL)
@return reference to modified smart pointer **/
SharedPointer& operator=(const decltype(nullptr)) ;
/** Regular assignment operator, intialises shared smart pointer container to point at T-type pointer
@param T* (raw pointer to object of type T)
@return reference to modified smart pointer **/
template<typename T>
SharedPointer& operator=(T*) ;
SharedPointer& operator=(void*) = delete ;
/** Copy constructor, creates copy of a given shared smart pointer
@param a (l-value) object reference
@return <initialised-object> **/
SharedPointer(const SharedPointer&) ;
/** Pseudo-copy constructor, creates copy of a templated shared smart pointer
@param a (l-value) templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer(const SharedPointer<T>&) ;
/** Pseudo-copy constructor, creates copy of a templated shared smart pointer
@param a (l-value) templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer(const SharedPointer<T[]>&) ;
/** Copy constructor, creates copy (of base-properties) of a given shared smart pointer
@param a (l-value) object reference
@return reference to modified smart pointer **/
SharedPointer& operator=(const SharedPointer&) ;
/** Pseudo-copy constructor, creates copy of a given templated shared smart pointer
@param a (l-value) templated object reference
@return reference to modified smart pointer **/
template<typename T>
SharedPointer& operator=(const SharedPointer<T>&) ;
/** Pseudo-copy constructor, creates copy of a given templated shared smart pointer
@param a (l-value) templated object reference
@return reference to modified smart pointer **/
template<typename T>
SharedPointer& operator=(const SharedPointer<T[]>&) ;
/** Pseudo-move constructor, takes ownership of a given templated shared smart pointer
@param an r-value templated base class reference
@return <initialised-object> **/
SharedPointer(SharedPointer&&) ;
/** Pseudo-move constructor, takes ownership of a given templated shared smart pointer
@param an r-value templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer(SharedPointer<T>&&) ;
/** Pseudo-move constructor, takes ownership of a given templated shared smart pointer
@param an r-value templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer(SharedPointer<T[]>&&) ;
/** Move assignment operator, takes ownership of a given shared smart pointer
@param an r-value object reference
@return reference to modified smart pointer **/
SharedPointer& operator=(SharedPointer&&) ;
/** Pseudo-move assignment operator, takes ownership of a given templated shared smart pointer
@param an r-value templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer& operator=(SharedPointer<T>&&) ;
/** Pseudo-move assignment operator, takes ownership of a given templated shared smart pointer
@param an r-value templated-object reference
@return <initialised-object> **/
template<typename T>
SharedPointer& operator=(SharedPointer<T[]>&&) ;
/** reset method, to appropriately disengage from pointing at data **/
void reset() ;
/** Destructor, frees memory if appropriate and deletes objects **/
~SharedPointer() ;
template<typename T>
friend class SharedPointer ;
} ;
/** This is the makeShared function, which creates a SharedPointer object of type T on the heap (using said object's empty / default initialisation)
* @return SharedPointer of type T **/
template<class T>
SharedPointer<T> makeShared() ;
/** This is the makeShared function, which creates a SharedPointer object of type T on the heap, initialising the object using constructor determined by the parameters given
* @param Variadic template (arguments to pass in order to initialise object of type T)
* @return SharedPointer of type T **/
template<class T, class... Args>
SharedPointer<T> makeShared(Args&&...) ;
/** This is the makeShared function, which creates a SharedPointer object of an array of T's (T[]) on the heap,
* @param number of T's to allocate in contiguous block
* @return SharedPointer of type T[] **/
template<class T>
SharedPointer<T[]> makeShared(const unsigned long) ;
}
}
#include "shared-pointer.tpp"
#endif
| 40.069079 | 259 | 0.714638 | daleksla |
125e336a07455a86438ba298fdb4c87b9fd769c9 | 734 | cpp | C++ | SourceT/drlg_l3_test.cpp | madmaxoft/devilutionX | 5d2af51d01a31865e7384ba1fb0d24a2b2c55d26 | [
"Unlicense"
] | 54 | 2019-11-16T21:49:50.000Z | 2022-03-26T03:44:12.000Z | SourceT/drlg_l3_test.cpp | madmaxoft/devilutionX | 5d2af51d01a31865e7384ba1fb0d24a2b2c55d26 | [
"Unlicense"
] | 10 | 2019-08-20T16:54:37.000Z | 2020-05-06T08:30:53.000Z | SourceT/drlg_l3_test.cpp | madmaxoft/devilutionX | 5d2af51d01a31865e7384ba1fb0d24a2b2c55d26 | [
"Unlicense"
] | 5 | 2019-07-15T22:03:06.000Z | 2020-09-15T11:26:11.000Z | #include <gtest/gtest.h>
#include "all.h"
TEST(Drlg_l3, AddFenceDoors_x) {
memset(dvl::dungeon, 0, sizeof(dvl::dungeon));
dvl::dungeon[5][5] = 7;
dvl::dungeon[5 - 1][5] = 130;
dvl::dungeon[5 + 1][5] = 152;
dvl::AddFenceDoors();
EXPECT_EQ(dvl::dungeon[5][5], 146);
}
TEST(Drlg_l3, AddFenceDoors_y) {
memset(dvl::dungeon, 0, sizeof(dvl::dungeon));
dvl::dungeon[5][5] = 7;
dvl::dungeon[5][5 - 1] = 130;
dvl::dungeon[5][5 + 1] = 152;
dvl::AddFenceDoors();
EXPECT_EQ(dvl::dungeon[5][5], 147);
}
TEST(Drlg_l3, AddFenceDoors_no) {
memset(dvl::dungeon, 0, sizeof(dvl::dungeon));
dvl::dungeon[5][5] = 7;
dvl::dungeon[5 - 1][5] = 130;
dvl::dungeon[5 + 1][5] = 153;
dvl::AddFenceDoors();
EXPECT_EQ(dvl::dungeon[5][5], 7);
}
| 24.466667 | 47 | 0.626703 | madmaxoft |
126371e683839b64e953048e1e1c32452297038c | 1,030 | cpp | C++ | src/cpu-kernels/awkward_RegularArray_broadcast_tooffsets_size1.cpp | BioGeek/awkward-1.0 | 0cfb4e43c41d5c7d9830cc7b1d750485c0a93eb2 | [
"BSD-3-Clause"
] | 519 | 2019-10-17T12:36:22.000Z | 2022-03-26T23:28:19.000Z | src/cpu-kernels/awkward_RegularArray_broadcast_tooffsets_size1.cpp | BioGeek/awkward-1.0 | 0cfb4e43c41d5c7d9830cc7b1d750485c0a93eb2 | [
"BSD-3-Clause"
] | 924 | 2019-11-03T21:05:01.000Z | 2022-03-31T22:44:30.000Z | src/cpu-kernels/awkward_RegularArray_broadcast_tooffsets_size1.cpp | BioGeek/awkward-1.0 | 0cfb4e43c41d5c7d9830cc7b1d750485c0a93eb2 | [
"BSD-3-Clause"
] | 56 | 2019-12-17T15:49:22.000Z | 2022-03-09T20:34:06.000Z | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS_C("src/cpu-kernels/awkward_RegularArray_broadcast_tooffsets_size1.cpp", line)
#include "awkward/kernels.h"
template <typename T>
ERROR awkward_RegularArray_broadcast_tooffsets_size1(
T* tocarry,
const T* fromoffsets,
int64_t offsetslength) {
int64_t k = 0;
for (int64_t i = 0; i < offsetslength - 1; i++) {
int64_t count = (int64_t)(fromoffsets[i + 1] - fromoffsets[i]);
if (count < 0) {
return failure("broadcast's offsets must be monotonically increasing", i, kSliceNone, FILENAME(__LINE__));
}
for (int64_t j = 0; j < count; j++) {
tocarry[k] = (T)i;
k++;
}
}
return success();
}
ERROR awkward_RegularArray_broadcast_tooffsets_size1_64(
int64_t* tocarry,
const int64_t* fromoffsets,
int64_t offsetslength) {
return awkward_RegularArray_broadcast_tooffsets_size1<int64_t>(
tocarry,
fromoffsets,
offsetslength);
}
| 30.294118 | 124 | 0.708738 | BioGeek |
126ad39989b1dd64d34bee6b66df242d60a3d2a6 | 4,004 | cpp | C++ | rmw/test/test_qos_string_conversions.cpp | Ericsson/ros2-rmw | 6c535d1c89ea94efa10eb876bc39ee4c1d09d8e7 | [
"Apache-2.0"
] | 65 | 2015-09-26T18:43:05.000Z | 2022-02-24T14:37:48.000Z | rmw/test/test_qos_string_conversions.cpp | Ericsson/ros2-rmw | 6c535d1c89ea94efa10eb876bc39ee4c1d09d8e7 | [
"Apache-2.0"
] | 242 | 2015-03-07T00:33:20.000Z | 2022-03-21T16:04:20.000Z | rmw/test/test_qos_string_conversions.cpp | Ericsson/ros2-rmw | 6c535d1c89ea94efa10eb876bc39ee4c1d09d8e7 | [
"Apache-2.0"
] | 55 | 2015-07-21T02:28:39.000Z | 2022-03-15T07:24:16.000Z | // Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "rmw/qos_string_conversions.h"
#include "rmw/types.h"
// Converts to string and back to the policy value, check that it's the same
#define TEST_QOS_POLICY_VALUE_STRINGIFY(kind, value) \
do { \
EXPECT_EQ( \
value, rmw_qos_ ## kind ## _policy_from_str(rmw_qos_ ## kind ## _policy_to_str(value))); \
} while (0)
// Check unrecognized string as input of from_str, check UNKNOWN as input of to_str.
#define TEST_QOS_POLICY_STRINGIFY_CORNER_CASES(kind, kind_upper) \
do { \
EXPECT_EQ( \
NULL, rmw_qos_ ## kind ## _policy_to_str(RMW_QOS_POLICY_ ## kind_upper ## _UNKNOWN)); \
EXPECT_EQ( \
RMW_QOS_POLICY_ ## kind_upper ## _UNKNOWN, \
rmw_qos_ ## kind ## _policy_from_str("this could never be a stringified policy value")); \
EXPECT_EQ( \
RMW_QOS_POLICY_ ## kind_upper ## _UNKNOWN, \
rmw_qos_ ## kind ## _policy_from_str(NULL)); \
} while (0)
TEST(test_qos_policy_stringify, test_policy_values) {
TEST_QOS_POLICY_VALUE_STRINGIFY(durability, RMW_QOS_POLICY_DURABILITY_SYSTEM_DEFAULT);
TEST_QOS_POLICY_VALUE_STRINGIFY(durability, RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL);
TEST_QOS_POLICY_VALUE_STRINGIFY(durability, RMW_QOS_POLICY_DURABILITY_VOLATILE);
TEST_QOS_POLICY_VALUE_STRINGIFY(history, RMW_QOS_POLICY_HISTORY_KEEP_LAST);
TEST_QOS_POLICY_VALUE_STRINGIFY(history, RMW_QOS_POLICY_HISTORY_KEEP_ALL);
TEST_QOS_POLICY_VALUE_STRINGIFY(history, RMW_QOS_POLICY_HISTORY_SYSTEM_DEFAULT);
TEST_QOS_POLICY_VALUE_STRINGIFY(liveliness, RMW_QOS_POLICY_LIVELINESS_AUTOMATIC);
TEST_QOS_POLICY_VALUE_STRINGIFY(liveliness, RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC);
TEST_QOS_POLICY_VALUE_STRINGIFY(liveliness, RMW_QOS_POLICY_LIVELINESS_SYSTEM_DEFAULT);
TEST_QOS_POLICY_VALUE_STRINGIFY(reliability, RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
TEST_QOS_POLICY_VALUE_STRINGIFY(reliability, RMW_QOS_POLICY_RELIABILITY_RELIABLE);
TEST_QOS_POLICY_VALUE_STRINGIFY(reliability, RMW_QOS_POLICY_RELIABILITY_SYSTEM_DEFAULT);
TEST_QOS_POLICY_STRINGIFY_CORNER_CASES(durability, DURABILITY);
TEST_QOS_POLICY_STRINGIFY_CORNER_CASES(history, HISTORY);
TEST_QOS_POLICY_STRINGIFY_CORNER_CASES(liveliness, LIVELINESS);
TEST_QOS_POLICY_STRINGIFY_CORNER_CASES(reliability, RELIABILITY);
}
// Converts to string and back to the policy kind, check that it's the same
#define TEST_QOS_POLICY_KIND_STRINGIFY(kind) \
do { \
EXPECT_EQ( \
kind, rmw_qos_policy_kind_from_str(rmw_qos_policy_kind_to_str(kind))); \
} while (0)
TEST(test_qos_policy_stringify, test_policy_kinds) {
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_DURABILITY);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_DEADLINE);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_LIVELINESS);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_RELIABILITY);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_HISTORY);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_LIFESPAN);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_DEPTH);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_LIVELINESS_LEASE_DURATION);
TEST_QOS_POLICY_KIND_STRINGIFY(RMW_QOS_POLICY_AVOID_ROS_NAMESPACE_CONVENTIONS);
EXPECT_EQ(RMW_QOS_POLICY_INVALID, rmw_qos_policy_kind_from_str(NULL));
EXPECT_EQ(RMW_QOS_POLICY_INVALID, rmw_qos_policy_kind_from_str("this is not a policy kind!"));
EXPECT_FALSE(rmw_qos_policy_kind_to_str(RMW_QOS_POLICY_INVALID));
}
| 48.829268 | 96 | 0.811688 | Ericsson |
126c17506fd8252eb0ed18ce6c729342b30aef40 | 608 | cpp | C++ | tests/netuit/arrange/RingTopologyFactory.cpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 15 | 2020-07-31T23:06:09.000Z | 2022-01-13T18:05:33.000Z | tests/netuit/arrange/RingTopologyFactory.cpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 137 | 2020-08-13T23:32:17.000Z | 2021-10-16T04:00:40.000Z | tests/netuit/arrange/RingTopologyFactory.cpp | mmore500/pipe-profile | 861babd819909d1bda5e933269e7bc64018272d6 | [
"MIT"
] | 3 | 2020-08-09T01:52:03.000Z | 2020-10-02T02:13:47.000Z | #include "Catch/single_include/catch2/catch.hpp"
#include "netuit/arrange/RingTopologyFactory.hpp"
#include "NetworkXTester.hpp"
TEST_CASE("Test RingTopologyFactory", "[nproc:1]") {
// TODO flesh out stub test
netuit::RingTopologyFactory{}(100);
for (size_t i = 0; i < 150; ++i) {
REQUIRE( netuit::RingTopologyFactory{}(i).GetSize() == i );
}
for (const auto& node : netuit::RingTopologyFactory{}(100)) {
REQUIRE( node.GetNumInputs() == 1);
REQUIRE( node.GetNumOutputs() == 1);
}
}
TEST_CASE("Test Ring file output") {
REQUIRE(test_all_adj(netuit::RingTopologyFactory{}));
}
| 24.32 | 63 | 0.679276 | mmore500 |
126d72b5adedb55434b1eef86f6e9fe3817b4338 | 2,148 | cpp | C++ | oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/core/math/noise/WorleyCellNoise.cpp | skarik/1Engine | 84e846544b4a89af8fd7e9236131363096538ef4 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z | #include "WorleyCellNoise.h"
#include "core/math/Math.h"
#include <algorithm>
#include <random>
static Vector3f RandomCellPoint( int32 celX, int32 celY, int32 celZ, float offsets [1024] )
{
return Vector3f(
celX + offsets[(celX + celY^celZ) & (1024 - 1)],
celY + offsets[(celY * 912 + celX^celZ) & (1024 - 1)],
celZ + offsets[(celZ * 1024 * 871 + celX^celY) & (1024 - 1)]
);
}
// Noise ( vec3, randombuf ) : Performs 3x3 sample for worley
static float WorleyCell(float vec[3], float offsets [1024])
{
// Select proper unit cube with the point
const int32 X = ((int32)std::floor(vec[0])) & 0xFF;
const int32 Y = ((int32)std::floor(vec[1])) & 0xFF;
const int32 Z = ((int32)std::floor(vec[2])) & 0xFF;
float distance = 1.0e10F;
// Sample the 3x3 cells to get the minimum distance to a cell
for (int32 xo = -1; xo <= 1; xo++)
{
for (int32 yo = -1; yo <= 1; yo++)
{
for (int32 zo = -1; zo <= 1; zo++)
{
const int32 Xi = X + xo;
const int32 Yi = Y + yo;
const int32 Zi = Z + zo;
const Vector3f celPosition = RandomCellPoint(Xi, Yi, Zi, offsets);
distance = std::min<float>(distance, (celPosition - Vector3f(vec[0], vec[1], vec[2])).magnitude());
}
}
}
distance = math::saturate(distance);
return distance;
}
float WorleyCellNoise::Get (const float position)
{
float vec[3] = {position * m_cellcount, 0.0F, 0.0F};
float result = WorleyCell(vec, m_offset);
return (result - 0.5F) * 2.0F * m_amp;
}
float WorleyCellNoise::Get (const Vector2f& position)
{
float vec[3] = {position.x * m_cellcount, position.y * m_cellcount, 0.0F};
float result = WorleyCell(vec, m_offset);
return (result - 0.5F) * 2.0F * m_amp;
}
float WorleyCellNoise::Get (const Vector3f& position)
{
float vec[3] = {position.x * m_cellcount, position.y * m_cellcount, position.z * m_cellcount};
float result = WorleyCell(vec, m_offset);
return (result - 0.5F) * 2.0F * m_amp;
}
void WorleyCellNoise::init ( void )
{
std::mt19937 random_engine (m_seed);
std::uniform_real_distribution distro (0.0F, +1.0F);
for (int i = 0; i < 1024; ++i)
{
m_offset[i] = distro(random_engine);
}
} | 26.85 | 103 | 0.641061 | skarik |
12725a36a28dc5ce0025646519ad571e3c275e38 | 2,042 | cpp | C++ | ext/libigl/external/cgal/src/CGAL_Project/examples/Box_intersection_d/proximity_custom_box_traits.cpp | liminchen/OptCuts | cb85b06ece3a6d1279863e26b5fd17a5abb0834d | [
"MIT"
] | 187 | 2019-01-23T04:07:11.000Z | 2022-03-27T03:44:58.000Z | ext/libigl/external/cgal/src/CGAL_Project/examples/Box_intersection_d/proximity_custom_box_traits.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 8 | 2019-03-22T13:27:38.000Z | 2020-06-18T13:23:23.000Z | ext/libigl/external/cgal/src/CGAL_Project/examples/Box_intersection_d/proximity_custom_box_traits.cpp | xiaoxie5002/OptCuts | 1f4168fc867f47face85fcfa3a572be98232786f | [
"MIT"
] | 34 | 2019-02-13T01:11:12.000Z | 2022-02-28T03:29:40.000Z | #include <CGAL/Simple_cartesian.h>
#include <CGAL/box_intersection_d.h>
#include <vector>
#include <fstream>
typedef CGAL::Simple_cartesian<float> Kernel;
typedef Kernel::Point_3 Point_3;
std::vector<Point_3> points;
std::vector<Point_3*> boxes; // boxes are just pointers to points
const float eps = 0.1f; // finds point pairs of distance < 2*eps
// Boxes are just pointers to 3d points. The traits class adds the
// +- eps size to each interval around the point, effectively building
// on the fly a box of size 2*eps centered at the point.
struct Traits {
typedef float NT;
typedef Point_3* Box_parameter;
typedef std::ptrdiff_t ID;
static int dimension() { return 3; }
static float coord( Box_parameter b, int d) {
return (d == 0) ? b->x() : ((d == 1) ? b->y() : b->z());
}
static float min_coord( Box_parameter b, int d) { return coord(b,d)-eps;}
static float max_coord( Box_parameter b, int d) { return coord(b,d)+eps;}
// id-function using address of current box,
// requires to work with pointers to boxes later
static std::ptrdiff_t id(Box_parameter b) { return (std::ptrdiff_t)(b); }
};
// callback function reports pairs in close proximity
void report( const Point_3* a, const Point_3* b) {
float dist = std::sqrt( CGAL::squared_distance( *a, *b));
if ( dist < 2*eps) {
std::cout << "Point " << (a - &(points.front())) << " and Point "
<< (b - &(points.front())) << " have distance " << dist
<< "." << std::endl;
}
}
int main(int argc, char*argv[]) {
std::ifstream in((argc>1)?argv[1]:"data/points.xyz");
Point_3 p;
while(in >> p){
points.push_back(p);
}
for(std::size_t i = 0; i< points.size();++i) {
boxes.push_back( &points[i]);
}
// run the intersection algorithm and report proximity pairs
CGAL::box_self_intersection_d( boxes.begin(), boxes.end(),
report, Traits());
return 0;
}
| 35.824561 | 77 | 0.606758 | liminchen |
127bf5ca58020439263bc71b18088083af902bec | 4,806 | hpp | C++ | include/sharpen/IoEvent.hpp | Kylepoops/Sharpen | 5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132 | [
"MIT"
] | 13 | 2020-10-25T04:02:07.000Z | 2022-03-29T13:21:30.000Z | include/sharpen/IoEvent.hpp | Kylepoops/Sharpen | 5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132 | [
"MIT"
] | 18 | 2020-10-09T04:51:03.000Z | 2022-03-01T06:24:23.000Z | include/sharpen/IoEvent.hpp | Kylepoops/Sharpen | 5ef19d89ddab0b63ffc4d2489a1cd50e2d5bb132 | [
"MIT"
] | 7 | 2020-10-23T04:25:28.000Z | 2022-03-23T06:52:39.000Z | #pragma once
#ifndef _SHARPEN_IOEVENT_HPP
#define _SHARPEN_IOEVENT_HPP
#include "TypeDef.hpp"
#include "Noncopyable.hpp"
#include "Nonmovable.hpp"
#include "SystemError.hpp"
#include "IChannel.hpp"
namespace sharpen
{
class IoEvent
{
public:
//event type
struct EventTypeEnum
{
enum
{
//empty event
None = 0,
//read event
Read = 1,
//write event
Write = 2,
//close by peer
Close = 4,
//error
Error = 8,
//iocp only
//io completed
Completed = 16,
//io request
Request = 32,
//accept handle
Accept = 64,
//connect
Connect = 128,
//send file
Sendfile = 256,
//poll
Poll = 512
};
};
using EventType = sharpen::Uint32;
private:
using Self = sharpen::IoEvent;
using WeakChannel = std::weak_ptr<sharpen::IChannel>;
EventType type_;
WeakChannel channel_;
void *data_;
sharpen::ErrorCode errorCode_;
public:
IoEvent()
:type_(EventTypeEnum::None)
,channel_()
,data_(nullptr)
,errorCode_(0)
{}
IoEvent(EventType type,sharpen::ChannelPtr channel,void *data,sharpen::ErrorCode error)
:type_(type)
,channel_(channel)
,data_(data)
,errorCode_(error)
{}
IoEvent(const Self &other)
:type_(other.type_)
,channel_(other.channel_)
,data_(other.data_)
,errorCode_(other.errorCode_)
{}
IoEvent(Self &&other) noexcept
:type_(other.type_)
,channel_(other.channel_)
,data_(other.data_)
,errorCode_(other.errorCode_)
{
other.type_ = EventTypeEnum::None;
other.channel_.reset();
other.data_ = nullptr;
other.errorCode_ = 0;
}
Self &operator=(const Self &other)
{
this->type_ = other.type_;
this->channel_ = other.channel_;
this->data_ = other.data_;
this->errorCode_ = other.errorCode_;
return *this;
}
Self &operator=(Self &&other) noexcept
{
this->type_ = other.type_;
this->channel_ = other.channel_;
this->data_ = other.data_;
this->errorCode_ = other.errorCode_;
other.type_ = EventTypeEnum::None;
other.channel_.reset();
other.data_ = nullptr;
other.errorCode_ = 0;
return *this;
}
~IoEvent() noexcept = default;
bool IsReadEvent() const noexcept
{
return this->type_ & EventTypeEnum::Read;
}
bool IsWriteEvent() const noexcept
{
return this->type_ & EventTypeEnum::Write;
}
bool IsCloseEvent() const noexcept
{
return this->type_ & EventTypeEnum::Close;
}
bool IsErrorEvent() const noexcept
{
return this->type_ & EventTypeEnum::Error;
}
bool IsCompletedEvent() const noexcept
{
return this->type_ & EventTypeEnum::Completed;
}
bool IsRequestEvent() const noexcept
{
return this->type_ & EventTypeEnum::Request;
}
sharpen::ChannelPtr GetChannel() const noexcept
{
return this->channel_.lock();
}
void *GetData() const noexcept
{
return this->data_;
}
void SetData(void *data)
{
this->data_ = data;
}
sharpen::ErrorCode GetErrorCode() const noexcept
{
return this->errorCode_;
}
void SetErrorCode(sharpen::ErrorCode error)
{
this->errorCode_ = error;
}
void SetChannel(const sharpen::ChannelPtr &channel)
{
this->channel_ = channel;
}
void SetEvent(EventType ev)
{
this->type_ = ev;
}
EventType GetEventType() const noexcept
{
return this->type_;
}
void AddEvent(EventType ev)
{
this->type_ |= ev;
}
void RemoveEvent(EventType ev)
{
this->type_ ^= ev;
}
};
}
#endif
| 24.150754 | 95 | 0.468997 | Kylepoops |
127fb3226a474e1e0f3d11b6c08c424db1b1eb57 | 3,226 | cc | C++ | ElectroWeakAnalysis/ZMuMu/plugins/ZMassHistogrammer.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | ElectroWeakAnalysis/ZMuMu/plugins/ZMassHistogrammer.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | ElectroWeakAnalysis/ZMuMu/plugins/ZMassHistogrammer.cc | SWuchterl/cmssw | 769b4a7ef81796579af7d626da6039dfa0347b8e | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | #include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Candidate/interface/Candidate.h"
#include "DataFormats/Candidate/interface/CandidateFwd.h"
#include "TH1.h"
class ZMassHistogrammer : public edm::EDAnalyzer {
public:
ZMassHistogrammer(const edm::ParameterSet& pset);
private:
void analyze(const edm::Event& event, const edm::EventSetup& setup) override;
edm::EDGetTokenT<reco::CandidateView> zToken_;
edm::EDGetTokenT<reco::CandidateView> genToken_;
TH1F *h_mZ_, *h_mZMC_;
};
#include "DataFormats/HepMCCandidate/interface/GenParticle.h"
#include "DataFormats/HepMCCandidate/interface/GenParticleFwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include <iostream>
using namespace std;
using namespace reco;
using namespace edm;
ZMassHistogrammer::ZMassHistogrammer(const ParameterSet& pset)
: zToken_(consumes<reco::CandidateView>(pset.getParameter<InputTag>("z"))),
genToken_(consumes<reco::CandidateView>(pset.getParameter<InputTag>("gen"))) {
cout << ">>> Z Mass constructor" << endl;
Service<TFileService> fs;
h_mZ_ = fs->make<TH1F>("ZMass", "Z mass (GeV/c^{2})", 100, 0, 200);
h_mZMC_ = fs->make<TH1F>("ZMCMass", "Z MC mass (GeV/c^{2})", 100, 0, 200);
}
void ZMassHistogrammer::analyze(const edm::Event& event, const edm::EventSetup& setup) {
cout << ">>> Z Mass analyze" << endl;
Handle<CandidateCollection> z;
Handle<CandidateCollection> gen;
event.getByToken(zToken_, z);
event.getByToken(genToken_, gen);
for (unsigned int i = 0; i < z->size(); ++i) {
const Candidate& zCand = (*z)[i];
h_mZ_->Fill(zCand.mass());
}
for (unsigned int i = 0; i < gen->size(); ++i) {
const Candidate& genCand = (*gen)[i];
if ((genCand.pdgId() == 23) && (genCand.status() == 2)) //this is an intermediate Z0
cout << ">>> intermediate Z0 found, with " << genCand.numberOfDaughters() << " daughters" << endl;
if ((genCand.pdgId() == 23) && (genCand.status() == 3)) { //this is a Z0
cout << ">>> Z0 found, with " << genCand.numberOfDaughters() << " daughters" << endl;
h_mZMC_->Fill(genCand.mass());
if (genCand.numberOfDaughters() == 3) { //Z0 decays in mu+ mu-, the 3rd daughter is the same Z0
const Candidate* dauGen0 = genCand.daughter(0);
const Candidate* dauGen1 = genCand.daughter(1);
const Candidate* dauGen2 = genCand.daughter(2);
cout << ">>> daughter MC 0 PDG Id " << dauGen0->pdgId() << ", status " << dauGen0->status() << ", charge "
<< dauGen0->charge() << endl;
cout << ">>> daughter MC 1 PDG Id " << dauGen1->pdgId() << ", status " << dauGen1->status() << ", charge "
<< dauGen1->charge() << endl;
cout << ">>> daughter MC 2 PDG Id " << dauGen2->pdgId() << ", status " << dauGen2->status() << ", charge "
<< dauGen2->charge() << endl;
}
}
}
}
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(ZMassHistogrammer);
| 43.013333 | 114 | 0.66305 | SWuchterl |
12833c6d942dc11ae96ab4e0cbe07d686a2ee19d | 1,073 | hpp | C++ | include/cpppid/composers/adder.hpp | rvarago/cpppid | 0ca84beafd3bc68f2cbfd4f5b93b5ea66fe5e289 | [
"MIT"
] | 3 | 2019-07-17T14:08:22.000Z | 2021-09-18T19:08:43.000Z | include/cpppid/composers/adder.hpp | rvarago/cpppid | 0ca84beafd3bc68f2cbfd4f5b93b5ea66fe5e289 | [
"MIT"
] | 1 | 2019-01-05T09:07:49.000Z | 2019-04-14T14:13:13.000Z | include/cpppid/composers/adder.hpp | rvarago/cpppid | 0ca84beafd3bc68f2cbfd4f5b93b5ea66fe5e289 | [
"MIT"
] | null | null | null | #ifndef ADDER_HPP
#define ADDER_HPP
#include <type_traits>
#include <utility>
#include <tuple>
namespace cpppid::composers {
template <typename TotalOutput = double, typename... Controllers>
class adder {
using ControllersCollection = std::tuple<Controllers...>;
template <typename T>
static constexpr bool is_expected_output = std::is_same_v<std::decay_t<T>, TotalOutput>;
public:
explicit adder(Controllers... controllers)
: m_controllers{std::make_tuple(controllers...)} {}
template <typename Error>
auto operator()(Error const& current_error) {
auto const total_output = std::apply([¤t_error](auto &... ctrl) {return (ctrl(current_error) + ...);}, m_controllers);
static_assert(is_expected_output<decltype(total_output)>, "type of the sum of outputs must be equal to TotalOutput");
return total_output;
}
private:
ControllersCollection m_controllers;
};
}
#endif
| 31.558824 | 140 | 0.627213 | rvarago |
1283e20a085c260f030a1be7cfdcfc3d69945ee3 | 1,996 | cpp | C++ | TextOverviewTextEdit.cpp | B1anky/CppEditor | bb68ca521c35a8d7e658f9ddf789201d7b269a08 | [
"MIT"
] | 1 | 2020-09-11T12:42:15.000Z | 2020-09-11T12:42:15.000Z | TextOverviewTextEdit.cpp | B1anky/CppEditor | bb68ca521c35a8d7e658f9ddf789201d7b269a08 | [
"MIT"
] | null | null | null | TextOverviewTextEdit.cpp | B1anky/CppEditor | bb68ca521c35a8d7e658f9ddf789201d7b269a08 | [
"MIT"
] | null | null | null | #include "TextOverviewTextEdit.h"
#include <QVBoxLayout>
#include "TextEditor.h"
TextOverviewTextEdit::TextOverviewTextEdit(QWidget* parent) : QPlainTextEdit(parent){
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//setReadOnly(true);
setFrameStyle(QFrame::NoFrame);
setLineWrapMode(QPlainTextEdit::NoWrap);
if(qobject_cast<TextEditor*>(parentWidget())){
setFocusProxy(parentWidget());
}
}
//This widget will not scroll on its own, its companion text editor will do that
void TextOverviewTextEdit::wheelEvent(QWheelEvent* event){
if(qobject_cast<TextEditor*>(parentWidget())){
qobject_cast<TextEditor*>(parentWidget())->wheelEvent(event);
}else{
event->accept();
}
}
void TextOverviewTextEdit::keyPressEvent(QKeyEvent* event){
setReadOnly(false);
QPlainTextEdit::keyPressEvent(event);
setReadOnly(true);
}
void TextOverviewTextEdit::keyReleaseEvent(QKeyEvent* event){
/*
if(qobject_cast<TextEditor*>(parentWidget())){
qobject_cast<TextEditor*>(parentWidget())->keyReleaseEvent(event);
}else{
event->accept();
}
*/
setReadOnly(false);
QPlainTextEdit::keyPressEvent(event);
setReadOnly(true);
}
void TextOverviewTextEdit::mousePressEvent(QMouseEvent* event){
if(qobject_cast<TextEditor*>(parentWidget())){
qobject_cast<TextEditor*>(parentWidget())->mousePressEvent(event);
}else{
event->accept();
}
}
void TextOverviewTextEdit::mouseReleaseEvent(QMouseEvent* event){
if(qobject_cast<TextEditor*>(parentWidget())){
qobject_cast<TextEditor*>(parentWidget())->mouseReleaseEvent(event);
}else{
event->accept();
}
}
void TextOverviewTextEdit::mouseMoveEvent(QMouseEvent* event){
if(qobject_cast<TextEditor*>(parentWidget())){
qobject_cast<TextEditor*>(parentWidget())->mouseMoveEvent(event);
}else{
event->accept();
}
}
| 26.263158 | 85 | 0.700401 | B1anky |
12846557f534c7c4c4b801379967939dcbf2bbc2 | 140 | cpp | C++ | cf/contest/741/d/temp.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | cf/contest/741/d/temp.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | cf/contest/741/d/temp.cpp | woshiluo/oi | 5637fb81b0e25013314783dc387f7fc93bf9d4b9 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
int main() {
int n = 500000;
printf( "%d\n", n );
for( int i = 1; i < n; i ++ ) {
printf( "%d %c\n", i, 'a' );
}
}
| 14 | 32 | 0.435714 | woshiluo |
128d156ffe4c9892fda317bf3f879e2164f6870d | 17,927 | cpp | C++ | i18n/tzfmt.cpp | tizenorg/external.icu | 5b69033400476be749862631609f60bd7daaacd7 | [
"ICU"
] | 3 | 2016-03-25T14:11:57.000Z | 2021-08-24T19:46:11.000Z | i18n/tzfmt.cpp | tizenorg/external.icu | 5b69033400476be749862631609f60bd7daaacd7 | [
"ICU"
] | null | null | null | i18n/tzfmt.cpp | tizenorg/external.icu | 5b69033400476be749862631609f60bd7daaacd7 | [
"ICU"
] | 2 | 2018-01-18T04:38:16.000Z | 2019-05-29T02:20:44.000Z | /*
*******************************************************************************
* Copyright (C) 2011, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "tzfmt.h"
#include "tzgnames.h"
#include "cmemory.h"
#include "cstring.h"
#include "putilimp.h"
#include "uassert.h"
#include "ucln_in.h"
#include "uhash.h"
#include "umutex.h"
#include "zonemeta.h"
U_NAMESPACE_BEGIN
// ---------------------------------------------------
// TimeZoneFormatImpl - the TimeZoneFormat implementation
// ---------------------------------------------------
class TimeZoneFormatImpl : public TimeZoneFormat {
public:
TimeZoneFormatImpl(const Locale& locale, UErrorCode& status);
virtual ~TimeZoneFormatImpl();
const TimeZoneNames* getTimeZoneNames() const;
UnicodeString& format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date,
UnicodeString& name, UTimeZoneTimeType* timeType = NULL) const;
UnicodeString& parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos,
UnicodeString& tzID, UTimeZoneTimeType* timeType = NULL) const;
private:
UMTX fLock;
Locale fLocale;
char fTargetRegion[ULOC_COUNTRY_CAPACITY];
TimeZoneNames* fTimeZoneNames;
TimeZoneGenericNames* fTimeZoneGenericNames;
UnicodeString& formatGeneric(const TimeZone& tz, UTimeZoneGenericNameType genType, UDate date, UnicodeString& name) const;
UnicodeString& formatSpecific(const TimeZone& tz, UTimeZoneNameType stdType, UTimeZoneNameType dstType,
UDate date, UnicodeString& name, UTimeZoneTimeType *timeType) const;
const TimeZoneGenericNames* getTimeZoneGenericNames(UErrorCode& status) const;
};
TimeZoneFormatImpl::TimeZoneFormatImpl(const Locale& locale, UErrorCode& status)
: fLock(NULL),fLocale(locale), fTimeZoneNames(NULL), fTimeZoneGenericNames(NULL) {
const char* region = fLocale.getCountry();
int32_t regionLen = uprv_strlen(region);
if (regionLen == 0) {
char loc[ULOC_FULLNAME_CAPACITY];
uloc_addLikelySubtags(fLocale.getName(), loc, sizeof(loc), &status);
regionLen = uloc_getCountry(loc, fTargetRegion, sizeof(fTargetRegion), &status);
if (U_SUCCESS(status)) {
fTargetRegion[regionLen] = 0;
} else {
return;
}
} else if (regionLen < (int32_t)sizeof(fTargetRegion)) {
uprv_strcpy(fTargetRegion, region);
} else {
fTargetRegion[0] = 0;
}
fTimeZoneNames = TimeZoneNames::createInstance(locale, status);
// fTimeZoneGenericNames is lazily instantiated
}
TimeZoneFormatImpl::~TimeZoneFormatImpl() {
if (fTimeZoneNames != NULL) {
delete fTimeZoneNames;
}
if (fTimeZoneGenericNames != NULL) {
delete fTimeZoneGenericNames;
}
umtx_destroy(&fLock);
}
const TimeZoneNames*
TimeZoneFormatImpl::getTimeZoneNames() const {
return fTimeZoneNames;
}
const TimeZoneGenericNames*
TimeZoneFormatImpl::getTimeZoneGenericNames(UErrorCode& status) const {
if (U_FAILURE(status)) {
return NULL;
}
UBool create;
UMTX_CHECK(&gZoneMetaLock, (fTimeZoneGenericNames == NULL), create);
if (create) {
TimeZoneFormatImpl *nonConstThis = const_cast<TimeZoneFormatImpl *>(this);
umtx_lock(&nonConstThis->fLock);
{
if (fTimeZoneGenericNames == NULL) {
nonConstThis->fTimeZoneGenericNames = new TimeZoneGenericNames(fLocale, status);
if (U_SUCCESS(status) && fTimeZoneGenericNames == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
}
}
umtx_unlock(&nonConstThis->fLock);
}
return fTimeZoneGenericNames;
}
UnicodeString&
TimeZoneFormatImpl::format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date,
UnicodeString& name, UTimeZoneTimeType* timeType /* = NULL */) const {
if (timeType) {
*timeType = UTZFMT_TIME_TYPE_UNKNOWN;
}
switch (style) {
case UTZFMT_STYLE_LOCATION:
formatGeneric(tz, UTZGNM_LOCATION, date, name);
break;
case UTZFMT_STYLE_GENERIC_LONG:
formatGeneric(tz, UTZGNM_LONG, date, name);
break;
case UTZFMT_STYLE_GENERIC_SHORT:
formatGeneric(tz, UTZGNM_SHORT, date, name);
break;
case UTZFMT_STYLE_SPECIFIC_LONG:
formatSpecific(tz, UTZNM_LONG_STANDARD, UTZNM_LONG_DAYLIGHT, date, name, timeType);
break;
case UTZFMT_STYLE_SPECIFIC_SHORT:
formatSpecific(tz, UTZNM_SHORT_STANDARD, UTZNM_SHORT_DAYLIGHT, date, name, timeType);
break;
case UTZFMT_STYLE_SPECIFIC_SHORT_COMMONLY_USED:
formatSpecific(tz, UTZNM_SHORT_STANDARD_COMMONLY_USED, UTZNM_SHORT_DAYLIGHT_COMMONLY_USED, date, name, timeType);
break;
}
return name;
}
UnicodeString&
TimeZoneFormatImpl::parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos,
UnicodeString& tzID, UTimeZoneTimeType* timeType /* = NULL */) const {
if (timeType) {
*timeType = UTZFMT_TIME_TYPE_UNKNOWN;
}
tzID.setToBogus();
int32_t startIdx = pos.getIndex();
UBool isGeneric = FALSE;
uint32_t types = 0;
switch (style) {
case UTZFMT_STYLE_LOCATION:
isGeneric = TRUE;
types = UTZGNM_LOCATION;
break;
case UTZFMT_STYLE_GENERIC_LONG:
isGeneric = TRUE;
types = UTZGNM_LOCATION | UTZGNM_LONG;
break;
case UTZFMT_STYLE_GENERIC_SHORT:
isGeneric = TRUE;
types = UTZGNM_LOCATION | UTZGNM_SHORT;
break;
case UTZFMT_STYLE_SPECIFIC_LONG:
types = UTZNM_LONG_STANDARD | UTZNM_LONG_DAYLIGHT;
break;
case UTZFMT_STYLE_SPECIFIC_SHORT:
types = UTZNM_SHORT_STANDARD | UTZNM_SHORT_DAYLIGHT;
break;
case UTZFMT_STYLE_SPECIFIC_SHORT_COMMONLY_USED:
types = UTZNM_SHORT_STANDARD_COMMONLY_USED | UTZNM_SHORT_DAYLIGHT_COMMONLY_USED;
break;
}
UTimeZoneTimeType parsedTimeType = UTZFMT_TIME_TYPE_UNKNOWN;
UnicodeString parsedTzID;
UErrorCode status = U_ZERO_ERROR;
if (isGeneric) {
int32_t len = 0;
const TimeZoneGenericNames *gnames = getTimeZoneGenericNames(status);
if (U_SUCCESS(status)) {
len = gnames->findBestMatch(text, startIdx, types, parsedTzID, parsedTimeType, status);
}
if (U_FAILURE(status) || len == 0) {
pos.setErrorIndex(startIdx);
return tzID;
}
pos.setIndex(startIdx + len);
} else {
TimeZoneNameMatchInfo *matchInfo = fTimeZoneNames->find(text, startIdx, types, status);
if (U_FAILURE(status) || matchInfo == NULL) {
pos.setErrorIndex(startIdx);
return tzID;
}
int32_t bestLen = 0;
int32_t bestIdx = -1;
for (int32_t i = 0; i < matchInfo->size(); i++) {
int32_t matchLen = matchInfo->getMatchLength(i);
if (matchLen > bestLen) {
bestLen = matchLen;
bestIdx = i;
}
}
if (bestIdx >= 0) {
matchInfo->getTimeZoneID(bestIdx, parsedTzID);
if (parsedTzID.isEmpty()) {
UnicodeString mzID;
matchInfo->getMetaZoneID(bestIdx, mzID);
U_ASSERT(mzID.length() > 0);
fTimeZoneNames->getReferenceZoneID(mzID, fTargetRegion, parsedTzID);
}
UTimeZoneNameType nameType = matchInfo->getNameType(bestIdx);
switch (nameType) {
case UTZNM_LONG_STANDARD:
case UTZNM_SHORT_STANDARD:
case UTZNM_SHORT_STANDARD_COMMONLY_USED:
parsedTimeType = UTZFMT_TIME_TYPE_STANDARD;
break;
case UTZNM_LONG_DAYLIGHT:
case UTZNM_SHORT_DAYLIGHT:
case UTZNM_SHORT_DAYLIGHT_COMMONLY_USED:
parsedTimeType = UTZFMT_TIME_TYPE_DAYLIGHT;
break;
default:
parsedTimeType = UTZFMT_TIME_TYPE_UNKNOWN;
break;
}
pos.setIndex(startIdx + bestLen);
}
delete matchInfo;
}
if (timeType) {
*timeType = parsedTimeType;
}
tzID.setTo(parsedTzID);
return tzID;
}
UnicodeString&
TimeZoneFormatImpl::formatGeneric(const TimeZone& tz, UTimeZoneGenericNameType genType, UDate date, UnicodeString& name) const {
UErrorCode status = U_ZERO_ERROR;
const TimeZoneGenericNames* gnames = getTimeZoneGenericNames(status);
if (U_FAILURE(status)) {
name.setToBogus();
return name;
}
if (genType == UTZGNM_LOCATION) {
const UChar* canonicalID = ZoneMeta::getCanonicalCLDRID(tz);
if (canonicalID == NULL) {
name.setToBogus();
return name;
}
return gnames->getGenericLocationName(UnicodeString(canonicalID), name);
}
return gnames->getDisplayName(tz, genType, date, name);
}
UnicodeString&
TimeZoneFormatImpl::formatSpecific(const TimeZone& tz, UTimeZoneNameType stdType, UTimeZoneNameType dstType,
UDate date, UnicodeString& name, UTimeZoneTimeType *timeType) const {
if (fTimeZoneNames == NULL) {
name.setToBogus();
return name;
}
UErrorCode status = U_ZERO_ERROR;
UBool isDaylight = tz.inDaylightTime(date, status);
const UChar* canonicalID = ZoneMeta::getCanonicalCLDRID(tz);
if (U_FAILURE(status) || canonicalID == NULL) {
name.setToBogus();
return name;
}
if (isDaylight) {
fTimeZoneNames->getDisplayName(UnicodeString(canonicalID), dstType, date, name);
} else {
fTimeZoneNames->getDisplayName(UnicodeString(canonicalID), stdType, date, name);
}
if (timeType && !name.isEmpty()) {
*timeType = isDaylight ? UTZFMT_TIME_TYPE_DAYLIGHT : UTZFMT_TIME_TYPE_STANDARD;
}
return name;
}
// TimeZoneFormat object cache handling
static UMTX gTimeZoneFormatLock = NULL;
static UHashtable *gTimeZoneFormatCache = NULL;
static UBool gTimeZoneFormatCacheInitialized = FALSE;
// Access count - incremented every time up to SWEEP_INTERVAL,
// then reset to 0
static int32_t gAccessCount = 0;
// Interval for calling the cache sweep function - every 100 times
#define SWEEP_INTERVAL 100
// Cache expiration in millisecond. When a cached entry is no
// longer referenced and exceeding this threshold since last
// access time, then the cache entry will be deleted by the sweep
// function. For now, 3 minutes.
#define CACHE_EXPIRATION 180000.0
typedef struct TimeZoneFormatCacheEntry {
TimeZoneFormat* tzfmt;
int32_t refCount;
double lastAccess;
} TimeZoneNameFormatCacheEntry;
U_CDECL_BEGIN
/**
* Cleanup callback func
*/
static UBool U_CALLCONV timeZoneFormat_cleanup(void)
{
umtx_destroy(&gTimeZoneFormatLock);
if (gTimeZoneFormatCache != NULL) {
uhash_close(gTimeZoneFormatCache);
gTimeZoneFormatCache = NULL;
}
gTimeZoneFormatCacheInitialized = FALSE;
return TRUE;
}
/**
* Deleter for TimeZoneNamesCacheEntry
*/
static void U_CALLCONV
deleteTimeZoneFormatCacheEntry(void *obj) {
TimeZoneNameFormatCacheEntry *entry = (TimeZoneNameFormatCacheEntry *)obj;
delete (TimeZoneFormat *) entry->tzfmt;
uprv_free((void *)entry);
}
U_CDECL_END
/**
* Function used for removing unreferrenced cache entries exceeding
* the expiration time. This function must be called with in the mutex
* block.
*/
static void sweepCache() {
int32_t pos = -1;
const UHashElement* elem;
double now = (double)uprv_getUTCtime();
while ((elem = uhash_nextElement(gTimeZoneFormatCache, &pos))) {
TimeZoneFormatCacheEntry *entry = (TimeZoneFormatCacheEntry *)elem->value.pointer;
if (entry->refCount <= 0 && (now - entry->lastAccess) > CACHE_EXPIRATION) {
// delete this entry
uhash_removeElement(gTimeZoneFormatCache, elem);
}
}
}
// ---------------------------------------------------
// TimeZoneFormatDelegate
// This class wraps a TimeZoneFormatImpl singleton
// per locale and maintain the reference count.
// ---------------------------------------------------
class TimeZoneFormatDelegate : public TimeZoneFormat {
public:
TimeZoneFormatDelegate(const Locale& locale, UErrorCode& status);
virtual ~TimeZoneFormatDelegate();
const TimeZoneNames* getTimeZoneNames() const;
UnicodeString& format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date,
UnicodeString& name, UTimeZoneTimeType* timeType = NULL) const;
UnicodeString& parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos,
UnicodeString& tzID, UTimeZoneTimeType* timeType = NULL) const;
private:
TimeZoneFormatCacheEntry* fTZfmtCacheEntry;
};
TimeZoneFormatDelegate::TimeZoneFormatDelegate(const Locale& locale, UErrorCode& status) {
UBool initialized;
UMTX_CHECK(&gTimeZoneFormatLock, gTimeZoneFormatCacheInitialized, initialized);
if (!initialized) {
// Create empty hashtable
umtx_lock(&gTimeZoneFormatLock);
{
if (!gTimeZoneFormatCacheInitialized) {
gTimeZoneFormatCache = uhash_open(uhash_hashChars, uhash_compareChars, NULL, &status);
if (U_SUCCESS(status)) {
uhash_setKeyDeleter(gTimeZoneFormatCache, uhash_freeBlock);
uhash_setValueDeleter(gTimeZoneFormatCache, deleteTimeZoneFormatCacheEntry);
gTimeZoneFormatCacheInitialized = TRUE;
ucln_i18n_registerCleanup(UCLN_I18N_TIMEZONEFORMAT, timeZoneFormat_cleanup);
}
}
}
umtx_unlock(&gTimeZoneFormatLock);
}
// Check the cache, if not available, create new one and cache
TimeZoneFormatCacheEntry *cacheEntry = NULL;
umtx_lock(&gTimeZoneFormatLock);
{
const char *key = locale.getName();
cacheEntry = (TimeZoneFormatCacheEntry *)uhash_get(gTimeZoneFormatCache, key);
if (cacheEntry == NULL) {
TimeZoneFormat *tzfmt = NULL;
char *newKey = NULL;
tzfmt = new TimeZoneFormatImpl(locale, status);
if (tzfmt == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
if (U_SUCCESS(status)) {
newKey = (char *)uprv_malloc(uprv_strlen(key) + 1);
if (newKey == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
} else {
uprv_strcpy(newKey, key);
}
}
if (U_SUCCESS(status)) {
cacheEntry = (TimeZoneFormatCacheEntry *)uprv_malloc(sizeof(TimeZoneFormatCacheEntry));
if (cacheEntry == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
} else {
cacheEntry->tzfmt = tzfmt;
cacheEntry->refCount = 1;
cacheEntry->lastAccess = (double)uprv_getUTCtime();
uhash_put(gTimeZoneFormatCache, newKey, cacheEntry, &status);
}
}
if (U_FAILURE(status)) {
if (tzfmt != NULL) {
delete tzfmt;
}
if (newKey != NULL) {
uprv_free(newKey);
}
if (cacheEntry != NULL) {
uprv_free(cacheEntry);
}
return;
}
} else {
// Update the reference count
cacheEntry->refCount++;
cacheEntry->lastAccess = (double)uprv_getUTCtime();
}
gAccessCount++;
if (gAccessCount >= SWEEP_INTERVAL) {
// sweep
sweepCache();
gAccessCount = 0;
}
}
umtx_unlock(&gTimeZoneFormatLock);
fTZfmtCacheEntry = cacheEntry;
}
TimeZoneFormatDelegate::~TimeZoneFormatDelegate() {
umtx_lock(&gTimeZoneFormatLock);
{
U_ASSERT(fTZfmtCacheEntry->refCount > 0);
// Just decrement the reference count
fTZfmtCacheEntry->refCount--;
}
umtx_unlock(&gTimeZoneFormatLock);
}
const TimeZoneNames*
TimeZoneFormatDelegate::getTimeZoneNames() const {
return fTZfmtCacheEntry->tzfmt->getTimeZoneNames();
}
UnicodeString&
TimeZoneFormatDelegate::format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date,
UnicodeString& name, UTimeZoneTimeType* timeType /* = NULL */) const {
return fTZfmtCacheEntry->tzfmt->format(style, tz, date, name, timeType);
}
UnicodeString&
TimeZoneFormatDelegate::parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos,
UnicodeString& tzID, UTimeZoneTimeType* timeType /* = NULL */) const {
return fTZfmtCacheEntry->tzfmt->parse(style, text, pos, tzID, timeType);
}
// ---------------------------------------------------
// TimeZoneFormat base class
// ---------------------------------------------------
TimeZoneFormat::~TimeZoneFormat() {
}
TimeZone*
TimeZoneFormat::parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos,
UTimeZoneTimeType* timeType /*= NULL*/) const {
UnicodeString tzID;
parse(style, text, pos, tzID, timeType);
if (pos.getErrorIndex() < 0) {
return TimeZone::createTimeZone(tzID);
}
return NULL;
}
TimeZoneFormat* U_EXPORT2
TimeZoneFormat::createInstance(const Locale& locale, UErrorCode& status) {
TimeZoneFormat* tzfmt = new TimeZoneFormatDelegate(locale, status);
if (U_SUCCESS(status) && tzfmt == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
return tzfmt;
}
U_NAMESPACE_END
#endif
| 33.508411 | 128 | 0.636637 | tizenorg |
1290663a44741135dd5057b4b4deb77c8507cf2b | 5,538 | cc | C++ | chrome/browser/chromeos/login/multi_profile_user_controller.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | chrome/browser/chromeos/login/multi_profile_user_controller.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | chrome/browser/chromeos/login/multi_profile_user_controller.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // 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 "chrome/browser/chromeos/login/multi_profile_user_controller.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/pref_change_registrar.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/chromeos/login/multi_profile_user_controller_delegate.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/prefs/pref_service_syncable.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "google_apis/gaia/gaia_auth_util.h"
namespace chromeos {
namespace {
std::string SanitizeBehaviorValue(const std::string& value) {
if (value == MultiProfileUserController::kBehaviorUnrestricted ||
value == MultiProfileUserController::kBehaviorPrimaryOnly ||
value == MultiProfileUserController::kBehaviorNotAllowed) {
return value;
}
return std::string(MultiProfileUserController::kBehaviorUnrestricted);
}
} // namespace
// static
const char MultiProfileUserController::kBehaviorUnrestricted[] = "unrestricted";
const char MultiProfileUserController::kBehaviorPrimaryOnly[] = "primary-only";
const char MultiProfileUserController::kBehaviorNotAllowed[] = "not-allowed";
MultiProfileUserController::MultiProfileUserController(
MultiProfileUserControllerDelegate* delegate,
PrefService* local_state)
: delegate_(delegate),
local_state_(local_state) {
}
MultiProfileUserController::~MultiProfileUserController() {}
// static
void MultiProfileUserController::RegisterPrefs(
PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(prefs::kCachedMultiProfileUserBehavior);
}
// static
void MultiProfileUserController::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterStringPref(
prefs::kMultiProfileUserBehavior,
kBehaviorUnrestricted,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
bool MultiProfileUserController::IsUserAllowedInSession(
const std::string& user_email) const {
UserManager* user_manager = UserManager::Get();
CHECK(user_manager);
std::string primary_user_email;
if (user_manager->GetPrimaryUser())
primary_user_email = user_manager->GetPrimaryUser()->email();
// Always allow if there is no primary user or user being checked is the
// primary user.
if (primary_user_email.empty() || primary_user_email == user_email)
return true;
// Owner is not allowed to be secondary user.
if (user_manager->GetOwnerEmail() == user_email)
return false;
// No user is allowed if the primary user policy forbids it.
const std::string primary_user_behavior = GetCachedValue(primary_user_email);
if (primary_user_behavior == kBehaviorNotAllowed)
return false;
// The user must have 'unrestricted' policy to be a secondary user.
const std::string behavior = GetCachedValue(user_email);
return behavior == kBehaviorUnrestricted;
}
void MultiProfileUserController::StartObserving(Profile* user_profile) {
// Profile name could be empty during tests.
if (user_profile->GetProfileName().empty())
return;
scoped_ptr<PrefChangeRegistrar> registrar(new PrefChangeRegistrar);
registrar->Init(user_profile->GetPrefs());
registrar->Add(
prefs::kMultiProfileUserBehavior,
base::Bind(&MultiProfileUserController::OnUserPrefChanged,
base::Unretained(this),
user_profile));
pref_watchers_.push_back(registrar.release());
OnUserPrefChanged(user_profile);
}
void MultiProfileUserController::RemoveCachedValue(
const std::string& user_email) {
DictionaryPrefUpdate update(local_state_,
prefs::kCachedMultiProfileUserBehavior);
update->RemoveWithoutPathExpansion(user_email, NULL);
}
std::string MultiProfileUserController::GetCachedValue(
const std::string& user_email) const {
const DictionaryValue* dict =
local_state_->GetDictionary(prefs::kCachedMultiProfileUserBehavior);
std::string value;
if (dict && dict->GetStringWithoutPathExpansion(user_email, &value))
return SanitizeBehaviorValue(value);
return std::string(kBehaviorUnrestricted);
}
void MultiProfileUserController::SetCachedValue(
const std::string& user_email,
const std::string& behavior) {
DictionaryPrefUpdate update(local_state_,
prefs::kCachedMultiProfileUserBehavior);
update->SetStringWithoutPathExpansion(user_email,
SanitizeBehaviorValue(behavior));
}
void MultiProfileUserController::CheckSessionUsers() {
const UserList& users = UserManager::Get()->GetLoggedInUsers();
for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
if (!IsUserAllowedInSession((*it)->email())) {
delegate_->OnUserNotAllowed();
return;
}
}
}
void MultiProfileUserController::OnUserPrefChanged(
Profile* user_profile) {
std::string user_email = user_profile->GetProfileName();
CHECK(!user_email.empty());
user_email = gaia::CanonicalizeEmail(user_email);
PrefService* prefs = user_profile->GetPrefs();
const std::string behavior =
prefs->GetString(prefs::kMultiProfileUserBehavior);
SetCachedValue(user_email, behavior);
CheckSessionUsers();
}
} // namespace chromeos
| 34.185185 | 81 | 0.752618 | nagineni |
129327ac92ab53807fd23e9ec0dfb564ab1f1f43 | 64 | cpp | C++ | src/gitcpp/implementation/config/ConfigLevel.cpp | ekuch/gitcpp | 8f29d4fd3f63a6a52885505983c756e5b5ee27dc | [
"MIT"
] | 1 | 2017-02-07T14:20:59.000Z | 2017-02-07T14:20:59.000Z | src/gitcpp/implementation/config/ConfigLevel.cpp | ekuch/gitcpp | 8f29d4fd3f63a6a52885505983c756e5b5ee27dc | [
"MIT"
] | null | null | null | src/gitcpp/implementation/config/ConfigLevel.cpp | ekuch/gitcpp | 8f29d4fd3f63a6a52885505983c756e5b5ee27dc | [
"MIT"
] | null | null | null | //
// Created by ekuch on 10/5/15.
//
#include "ConfigLevel.h"
| 10.666667 | 31 | 0.625 | ekuch |
129c88974c7d201c1913af5167e4c02189ce2c68 | 991 | cpp | C++ | code/WPILib/NetworkTables/Confirmation.cpp | trc492/Frc2012ReboundRumble | b1e60e8bcd43a0a86d0dfefe094a017f9ecf34c8 | [
"MIT"
] | null | null | null | code/WPILib/NetworkTables/Confirmation.cpp | trc492/Frc2012ReboundRumble | b1e60e8bcd43a0a86d0dfefe094a017f9ecf34c8 | [
"MIT"
] | null | null | null | code/WPILib/NetworkTables/Confirmation.cpp | trc492/Frc2012ReboundRumble | b1e60e8bcd43a0a86d0dfefe094a017f9ecf34c8 | [
"MIT"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "NetworkTables/Confirmation.h"
#include "NetworkTables/Buffer.h"
#include "NetworkTables/InterfaceConstants.h"
namespace NetworkTables
{
Confirmation::Confirmation(int count) :
m_count(count)
{
}
void Confirmation::Encode(Buffer *buffer)
{
for (int i = m_count; i > 0; i -= kNetworkTables_CONFIRMATION - 1)
{
buffer->WriteByte(kNetworkTables_CONFIRMATION | std::min(kNetworkTables_CONFIRMATION - 1, i));
}
}
// Currently unused
Confirmation *Confirmation::Combine(Confirmation *a, Confirmation *b)
{
a->m_count = a->m_count + b->m_count;
delete b;
return a;
}
}
| 27.527778 | 96 | 0.587286 | trc492 |
129da0e743365641ddfc5dc386643ed650fed279 | 5,995 | cpp | C++ | src/mame/drivers/altos2.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/altos2.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/altos2.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:AJR
/***********************************************************************************************************************************
2017-11-03 Skeleton
Altos II terminal. Green screen.
Chips: Z80A, 2x Z80DART, Z80CTC, X2210D, 2x CRT9006, CRT9007, CRT9021A, 8x 6116
Other: Beeper. Crystals: 4.9152, 8.000, 40.000
Keyboard: P8035L CPU, undumped 2716 labelled "358_2758", XTAL marked "4608-300-107 KSS4C"
************************************************************************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "machine/z80daisy.h"
#include "machine/z80ctc.h"
#include "machine/z80sio.h"
#include "machine/x2212.h"
#include "sound/beep.h"
//#include "video/crt9006.h"
#include "video/crt9007.h"
//#include "video/crt9021.h"
#include "screen.h"
#include "speaker.h"
class altos2_state : public driver_device
{
public:
altos2_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_novram(*this, "novram")
, m_vpac(*this, "vpac")
, m_bell(*this, "bell")
, m_p_chargen(*this, "chargen")
, m_p_videoram(*this, "videoram")
{ }
void altos2(machine_config &config);
private:
u8 vpac_r(offs_t offset);
void vpac_w(offs_t offset, u8 data);
void video_mode_w(u8 data);
u32 screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
virtual void machine_reset() override;
void io_map(address_map &map);
void mem_map(address_map &map);
required_device<z80_device> m_maincpu;
required_device<x2210_device> m_novram;
required_device<crt9007_device> m_vpac;
required_device<beep_device> m_bell;
required_region_ptr<u8> m_p_chargen;
required_shared_ptr<u8> m_p_videoram;
};
void altos2_state::machine_reset()
{
m_novram->recall(ASSERT_LINE);
m_novram->recall(CLEAR_LINE);
}
u8 altos2_state::vpac_r(offs_t offset)
{
return m_vpac->read(offset >> 1);
}
void altos2_state::vpac_w(offs_t offset, u8 data)
{
m_vpac->write(offset >> 1, data);
}
void altos2_state::video_mode_w(u8 data)
{
if (BIT(data, 5))
{
// D5 = 1 for 132-column mode
m_vpac->set_unscaled_clock(40_MHz_XTAL / 12);
m_vpac->set_character_width(6);
}
else
{
// D5 = 0 for 80-column mode
m_vpac->set_unscaled_clock(40_MHz_XTAL / 20);
m_vpac->set_character_width(10);
}
m_bell->set_state(BIT(data, 4));
//logerror("Writing %02X to mode register at %s\n", data, machine().describe_context());
}
u32 altos2_state::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
return 0;
}
void altos2_state::mem_map(address_map &map)
{
map(0x0000, 0x3fff).rom().region("roms", 0);
map(0xc000, 0xffff).ram().share("videoram");
}
void altos2_state::io_map(address_map &map)
{
map.global_mask(0xff);
map.unmap_value_high();
map(0x00, 0x03).rw("dart1", FUNC(z80dart_device::ba_cd_r), FUNC(z80dart_device::ba_cd_w));
map(0x04, 0x07).rw("dart2", FUNC(z80dart_device::ba_cd_r), FUNC(z80dart_device::ba_cd_w));
map(0x08, 0x0b).rw("ctc", FUNC(z80ctc_device::read), FUNC(z80ctc_device::write));
map(0x0c, 0x0c).w(FUNC(altos2_state::video_mode_w));
map(0x40, 0x7f).rw(m_novram, FUNC(x2210_device::read), FUNC(x2210_device::write));
map(0x80, 0xff).rw(FUNC(altos2_state::vpac_r), FUNC(altos2_state::vpac_w));
}
static INPUT_PORTS_START(altos2)
INPUT_PORTS_END
static const z80_daisy_config daisy_chain[] =
{
{ "dart1" },
{ "dart2" },
{ "ctc" },
{ nullptr }
};
void altos2_state::altos2(machine_config &config)
{
Z80(config, m_maincpu, 8_MHz_XTAL / 2);
m_maincpu->set_addrmap(AS_PROGRAM, &altos2_state::mem_map);
m_maincpu->set_addrmap(AS_IO, &altos2_state::io_map);
m_maincpu->set_daisy_config(daisy_chain);
z80ctc_device &ctc(Z80CTC(config, "ctc", 8_MHz_XTAL / 2));
ctc.intr_callback().set_inputline(m_maincpu, INPUT_LINE_IRQ0);
ctc.set_clk<0>(4.9152_MHz_XTAL / 4);
ctc.set_clk<1>(4.9152_MHz_XTAL / 4);
ctc.set_clk<2>(4.9152_MHz_XTAL / 4);
ctc.zc_callback<0>().set("dart1", FUNC(z80dart_device::txca_w));
ctc.zc_callback<0>().append("dart1", FUNC(z80dart_device::rxca_w));
ctc.zc_callback<1>().set("dart2", FUNC(z80dart_device::rxca_w));
ctc.zc_callback<1>().append("dart2", FUNC(z80dart_device::txca_w));
ctc.zc_callback<2>().set("dart1", FUNC(z80dart_device::rxtxcb_w));
z80dart_device &dart1(Z80DART(config, "dart1", 8_MHz_XTAL / 2));
dart1.out_int_callback().set_inputline(m_maincpu, INPUT_LINE_IRQ0);
z80dart_device &dart2(Z80DART(config, "dart2", 8_MHz_XTAL / 2)); // channel B not used for communications
dart2.out_int_callback().set_inputline(m_maincpu, INPUT_LINE_IRQ0);
dart2.out_dtrb_callback().set(m_novram, FUNC(x2210_device::store)).invert(); // FIXME: no inverter should be needed
X2210(config, m_novram);
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_raw(40_MHz_XTAL / 2, 960, 0, 800, 347, 0, 325);
screen.set_screen_update(FUNC(altos2_state::screen_update));
CRT9007(config, m_vpac, 40_MHz_XTAL / 20);
m_vpac->set_screen("screen");
m_vpac->set_character_width(10);
m_vpac->int_callback().set("ctc", FUNC(z80ctc_device::trg3));
SPEAKER(config, "mono").front_center();
BEEP(config, m_bell, 1000).add_route(ALL_OUTPUTS, "mono", 0.50);
}
ROM_START( altos2 )
ROM_REGION( 0x4000, "roms", 0 )
ROM_LOAD( "us_v1.2_15732.u32", 0x0000, 0x2000, CRC(a85f7be0) SHA1(3cfa954c916258d86f7f745d10ec2ff5e33261b3) )
ROM_LOAD( "us_v1.2_15733.u19", 0x2000, 0x2000, CRC(45ebe88a) SHA1(33f16b382a2b365122ebf5e5f7312f8afa45ad15) )
ROM_REGION( 0x2000, "chargen", 0 )
ROM_LOAD( "us_v1.1_14410.u34", 0x0000, 0x2000, CRC(0ebb78bf) SHA1(96a1f7d34ff35037cbbc93049c0e2b9c9f11f1db) )
ROM_REGION( 0x0800, "keyboard", 0 )
ROM_LOAD( "358_7258", 0x0000, 0x0800, NO_DUMP )
ROM_END
COMP(1983, altos2, 0, 0, altos2, altos2, altos2_state, empty_init, "Altos Computer Systems", "Altos II Terminal", MACHINE_NOT_WORKING | MACHINE_IMPERFECT_GRAPHICS)
| 32.058824 | 163 | 0.704754 | Robbbert |
129f96c927ff41c3ec0f996122ad6086a5c11357 | 3,421 | cpp | C++ | Source/ee/VuAnalysis.cpp | maximu/Play- | c9ea635c66a5cc939b8719b634bc8135ec0d67ce | [
"BSD-2-Clause"
] | 1 | 2021-03-30T16:23:17.000Z | 2021-03-30T16:23:17.000Z | Source/ee/VuAnalysis.cpp | maximu/Play- | c9ea635c66a5cc939b8719b634bc8135ec0d67ce | [
"BSD-2-Clause"
] | null | null | null | Source/ee/VuAnalysis.cpp | maximu/Play- | c9ea635c66a5cc939b8719b634bc8135ec0d67ce | [
"BSD-2-Clause"
] | null | null | null | #include "VuAnalysis.h"
#include "../MIPS.h"
#include "../Ps2Const.h"
#include "VUShared.h"
void CVuAnalysis::Analyse(CMIPS* ctx, uint32 begin, uint32 end)
{
int routineCount = 0;
begin &= ~0x07;
end &= ~0x07;
std::set<uint32> subroutineAddresses;
//First pass: Check for BAL
for(uint32 address = begin; address <= end; address += 8)
{
uint32 lowerInstruction = ctx->m_pMemoryMap->GetInstruction(address + 0);
uint32 upperInstruction = ctx->m_pMemoryMap->GetInstruction(address + 4);
//Check for LOI (skip)
if(upperInstruction & 0x80000000) continue;
//Check for BAL
if((lowerInstruction & 0xFE000000) == (0x21 << 25))
{
uint32 jumpTarget = address + VUShared::GetBranch(lowerInstruction & 0x07FF) + 8;
if(jumpTarget < begin) continue;
if(jumpTarget >= end) continue;
subroutineAddresses.insert(jumpTarget);
}
}
//Second pass: Check for END bit and JR
uint32 potentialRoutineStart = 0;
for(uint32 address = begin; address <= end; address += 8)
{
uint32 lowerInstruction = ctx->m_pMemoryMap->GetInstruction(address + 0);
uint32 upperInstruction = ctx->m_pMemoryMap->GetInstruction(address + 4);
if(lowerInstruction == 0 && upperInstruction == 0)
{
potentialRoutineStart = address + 8;
continue;
}
//Check for LOI (skip)
if(upperInstruction & 0x80000000) continue;
//Check for JR or END bit
if(
(lowerInstruction & 0xFE000000) == (0x24 << 25) ||
(upperInstruction & 0x40000000)
)
{
subroutineAddresses.insert(potentialRoutineStart);
potentialRoutineStart = address + 8;
}
}
//Create subroutines
for(const auto& subroutineAddress : subroutineAddresses)
{
//Don't bother if we already found it
if(ctx->m_analysis->FindSubroutine(subroutineAddress)) continue;
//Otherwise, try to find a function that already exists
for(uint32 address = subroutineAddress; address <= end; address += 8)
{
uint32 lowerInstruction = ctx->m_pMemoryMap->GetInstruction(address + 0);
uint32 upperInstruction = ctx->m_pMemoryMap->GetInstruction(address + 4);
//Check for LOI (skip)
if(upperInstruction & 0x80000000) continue;
//Check for JR or END bit
if(
(lowerInstruction & 0xFE000000) == (0x24 << 25) ||
(upperInstruction & 0x40000000)
)
{
ctx->m_analysis->InsertSubroutine(subroutineAddress, address + 8, 0, 0, 0, 0);
routineCount++;
break;
}
auto subroutine = ctx->m_analysis->FindSubroutine(address);
if(subroutine)
{
//Function already exists, merge.
ctx->m_analysis->ChangeSubroutineStart(subroutine->start, subroutineAddress);
break;
}
}
}
//Find orphaned branches
for(uint32 address = begin; address <= end; address += 8)
{
//Address already associated with subroutine, don't bother
if(ctx->m_analysis->FindSubroutine(address)) continue;
uint32 lowerInstruction = ctx->m_pMemoryMap->GetInstruction(address + 0);
uint32 upperInstruction = ctx->m_pMemoryMap->GetInstruction(address + 4);
auto branchType = ctx->m_pArch->IsInstructionBranch(ctx, address, lowerInstruction);
if(branchType == MIPS_BRANCH_NORMAL)
{
uint32 branchTarget = ctx->m_pArch->GetInstructionEffectiveAddress(ctx, address, lowerInstruction);
if(branchTarget != 0)
{
auto subroutine = ctx->m_analysis->FindSubroutine(branchTarget);
if(subroutine)
{
ctx->m_analysis->ChangeSubroutineEnd(subroutine->start, address + 8);
}
}
}
}
}
| 28.272727 | 102 | 0.699503 | maximu |
12a0d514f63d3ce45c69c31f0d3021ddc0bdc0ff | 4,776 | cpp | C++ | LeetCode/0018/0018_3.cpp | samsonwang/ToyCpp | a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c | [
"MIT"
] | null | null | null | LeetCode/0018/0018_3.cpp | samsonwang/ToyCpp | a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c | [
"MIT"
] | null | null | null | LeetCode/0018/0018_3.cpp | samsonwang/ToyCpp | a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c | [
"MIT"
] | null | null | null |
#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
static const auto fast = [](){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
// 下面这个是leetcode上的解法,运行速度很快
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if (nums.size() < 4) return res;
sort(nums.begin(), nums.end());
int len = nums.size();
for (int i = 0; i < len-3; i++) {
//avoid duplicate
if (i > 0 && nums[i] == nums[i-1]) continue;
// if (nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;
// if (nums[i] + nums[len-3] + nums[len-2] + nums[len-1] < target) continue;
//version3: less tight pruning
if (4 * nums[i] > target) break;
if (nums[i] + 3 * nums[len-1] < target) continue;
for (int j = i+1; j < len-2; ++j) {
if (j > i+1 && nums[j] == nums[j-1]) continue;
// if (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break;
// if (nums[i] + nums[j] + nums[len-2] + nums[len-1] < target) continue;
//version3: less tight pruning
if (nums[i] + 3* nums[j] > target) break;
if (nums[i] + nums[j] + 2 * nums[len-1] < target) continue;
//now the problems becomes 3 sum problem and only two other elements only to be considered
int left = j+1, right = len-1;
int sofar = nums[i] + nums[j];
while (left < right) {
if (sofar + nums[left] + nums[right] == target) {
res.push_back(vector<int>({nums[i], nums[j], nums[left], nums[right]}));
//how to skip the duplicate left and right
//version1: my own version
// left++;
// right--;
// while (left < right && nums[left-1] == nums[left]) ++left;
// while (right > left && nums[right+1] == nums[right]) --right;
//version2: refer others
do{left++;} while (left < right && nums[left] == nums[left-1]);
do{right--;} while (right > left && nums[right] == nums[right+1]);
}
else if (sofar + nums[left] + nums[right] < target) left++;
else right--;
}
}
}
return res;
}
// struct vector_hash {
// size_t operator()(const std::vector<int>& v) const {
// std::hash<int> hasher;
// size_t seed = 0;
// for (int i : v) {
// seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
// }
// return seed;
// }
// };
// vector<vector<int>> fourSum(vector<int>& nums, int target) {
// vector<vector<int>> res;
// if (nums.size() <= 3) return res;
// sort(nums.begin(), nums.end());
// unordered_map<long, vector<pair<int, int>>> om;
// for (int i = 0; i < nums.size(); i++)
// for (int j = i+1; j < nums.size(); j++) {
// auto vp = make_pair(i,j);
// auto it = om.find(nums[i] + nums[j]);
// if (it != om.end())
// it->second.push_back(vp);
// else {
// vector<pair<int, int>> vt;
// vt.push_back(vp);
// om.insert({nums[i] + nums[j], vt});
// }
// }
// unordered_set<vector<int>, vector_hash> s;
// for (const auto & entry : om) {
// long cur = entry.first;
// long rem = target - cur;
// if (om.find(rem) != om.end()) {
// auto it = om.find(rem);
// for (const auto & e : entry.second)
// for (const auto & v : it->second) {
// vector<int> tmp = {e.first, e.second, v.first, v.second};// sort the rank
// sort(tmp.begin(), tmp.end());
// if (tmp[0] == tmp[1] || tmp[1] == tmp[2] || tmp[2] == tmp[3]) continue;
// vector<int> newvec = {nums[tmp[0]], nums[tmp[1]], nums[tmp[2]], nums[tmp[3]]};
// s.insert(newvec);
// }
// }
// }
// vector<vector<int>> v(s.begin(), s.end());
// return v;
// }
int main(int argc, char* argv[]) {
vector<int> nums {1,0,-1,0,-2,2};
vector<int> nums2 {-3,-1,0,2,4,5};
vector<vector<int>> ans = fourSum(nums, 0);
for (const auto& v : ans) {
for (int n : v) {
cout << n << "\t";
}
cout << endl;
}
return 0;
}
| 38.516129 | 102 | 0.439698 | samsonwang |
12a15ab2534c96d692424ec4d7ef0e76165f9c6e | 651 | cpp | C++ | Problems/0123. Best Time to Buy and Sell Stock III.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0123. Best Time to Buy and Sell Stock III.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | Problems/0123. Best Time to Buy and Sell Stock III.cpp | KrKush23/LeetCode | 2a87420a65347a34fba333d46e1aa6224c629b7a | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy1{INT_MIN},sell1{0},buy2{INT_MIN},sell2{0};
for(auto p: prices){
buy1 = max(buy1, -p);
sell1 = max(sell1, buy1 + p);
buy2 = max(buy2, sell1 - p);
sell2 = max(sell2, buy2 + p);
}
return sell2;
}
};
/* Note that buying stock means we are spending money equivalent to the price of the stock,
* thus subtract the price. On selling the stock we add the price because the associated
* price is getting added to our profit.
* Final Profit = (Initial Profit — Buying Price) + Selling Price
*/
| 32.55 | 92 | 0.602151 | KrKush23 |
12a50b1caf5331662b94d734b46dd2ae4bffebfb | 537 | cpp | C++ | src/bindings/python/src/pyopenvino/core/containers.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 1 | 2021-02-01T06:35:55.000Z | 2021-02-01T06:35:55.000Z | src/bindings/python/src/pyopenvino/core/containers.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 58 | 2020-11-06T12:13:45.000Z | 2022-03-28T13:20:11.000Z | src/bindings/python/src/pyopenvino/core/containers.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 4 | 2021-09-29T20:44:49.000Z | 2021-10-20T13:02:12.000Z | // Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "pyopenvino/core/containers.hpp"
#include <pybind11/stl_bind.h>
PYBIND11_MAKE_OPAQUE(Containers::TensorIndexMap);
PYBIND11_MAKE_OPAQUE(Containers::TensorNameMap);
namespace py = pybind11;
namespace Containers {
void regclass_TensorIndexMap(py::module m) {
py::bind_map<TensorIndexMap>(m, "TensorIndexMap");
}
void regclass_TensorNameMap(py::module m) {
py::bind_map<TensorNameMap>(m, "TensorNameMap");
}
} // namespace Containers
| 22.375 | 54 | 0.759777 | pazamelin |
12a684ba6c8a436019a10870c9623e98a9da4849 | 1,414 | cpp | C++ | 14502/14502.cpp17.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 14 | 2017-05-02T02:00:42.000Z | 2021-11-16T07:25:29.000Z | 14502/14502.cpp17.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 1 | 2017-12-25T14:18:14.000Z | 2018-02-07T06:49:44.000Z | 14502/14502.cpp17.cpp | isac322/BOJ | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | [
"MIT"
] | 9 | 2016-03-03T22:06:52.000Z | 2020-04-30T22:06:24.000Z | #include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
char map[9][9], tmp[9][9];
int n, m;
int dfs(int r, int c) {
if (r < 0 or c < 0) return 0;
else if (tmp[r][c] == 0 or tmp[r][c] == '1' or tmp[r][c] == '3') return 0;
tmp[r][c] = '3';
return 1 + dfs(r - 1, c) + dfs(r, c - 1) + dfs(r + 1, c) + dfs(r, c + 1);
}
int main() {
int wall_cnt = 0;
vector<pair<int, int>> vi_locs;
scanf("%d %d\n", &n, &m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%c%*c", &map[i][j]);
if (map[i][j] == '1') wall_cnt++;
else if (map[i][j] == '2') vi_locs.emplace_back(i, j);
}
}
const int tot = n * m;
int ans = 0;
for (int i = 0; i < tot; ++i) {
if (map[i / m][i % m] != '0') continue;
for (int j = i + 1; j < tot; ++j) {
if (map[j / m][j % m] != '0') continue;
for (int k = j + 1; k < tot; ++k) {
if (map[k / m][k % m] != '0') continue;
memcpy(tmp, map, 9 * 9);
tmp[i / m][i % m] = tmp[j / m][j % m] = tmp[k / m][k % m] = '1';
int vi_cnt = 0;
for (auto &p: vi_locs) {
vi_cnt += dfs(p.first, p.second);
}
ans = max(ans, tot - wall_cnt - 3 - vi_cnt);
}
}
}
printf("%d\n", ans);
} | 27.192308 | 80 | 0.387553 | isac322 |
12a6f310d7f06fdd53725b1a419520478ac8522b | 2,298 | cxx | C++ | Servers/ServerManager/vtkSMSILDomain.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Servers/ServerManager/vtkSMSILDomain.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Servers/ServerManager/vtkSMSILDomain.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: vtkSMSILDomain.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMSILDomain.h"
#include "vtkObjectFactory.h"
#include "vtkSMProperty.h"
#include "vtkSMSILInformationHelper.h"
vtkStandardNewMacro(vtkSMSILDomain);
//----------------------------------------------------------------------------
vtkSMSILDomain::vtkSMSILDomain()
{
}
//----------------------------------------------------------------------------
vtkSMSILDomain::~vtkSMSILDomain()
{
}
//----------------------------------------------------------------------------
const char* vtkSMSILDomain::GetSubtree()
{
vtkSMProperty* req_prop = this->GetRequiredProperty("ArrayList");
if (!req_prop)
{
vtkErrorMacro("Required property 'ArrayList' missing."
"Cannot fetch the SIL");
return 0;
}
vtkSMSILInformationHelper* helper =
vtkSMSILInformationHelper::SafeDownCast(req_prop->GetInformationHelper());
if (!helper)
{
vtkErrorMacro("Failed to locate vtkSMSILInformationHelper.");
return 0;
}
return helper->GetSubtree();
}
//----------------------------------------------------------------------------
vtkGraph* vtkSMSILDomain::GetSIL()
{
vtkSMProperty* req_prop = this->GetRequiredProperty("ArrayList");
if (!req_prop)
{
vtkErrorMacro("Required property 'ArrayList' missing."
"Cannot fetch the SIL");
return 0;
}
vtkSMSILInformationHelper* helper =
vtkSMSILInformationHelper::SafeDownCast(req_prop->GetInformationHelper());
if (!helper)
{
vtkErrorMacro("Failed to locate vtkSMSILInformationHelper.");
return 0;
}
return helper->GetSIL();
}
//----------------------------------------------------------------------------
void vtkSMSILDomain::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| 27.357143 | 79 | 0.549173 | utkarshayachit |
12a7ce2f5f6b72d3eafe6d221e132d044295020f | 13,044 | cpp | C++ | data/cwru-ros-pkg/catkin/src/cwru_376_student/wsn_examples/example_robot_commander/src/interactive_robot_commander_v2.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/cwru-ros-pkg/catkin/src/cwru_376_student/wsn_examples/example_robot_commander/src/interactive_robot_commander_v2.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | data/cwru-ros-pkg/catkin/src/cwru_376_student/wsn_examples/example_robot_commander/src/interactive_robot_commander_v2.cpp | khairulislam/phys | fc702520fcd3b23022b9253e7d94f878978b4500 | [
"MIT"
] | null | null | null | //simple interactive motion commander v2:
// this version (v2) also responds to 2D Nav Goal inputs from Rviz;
// such inputs trigger automatically--do not require external trigger
// ALSO, with rviz in "map" as fixed frame, this version uses tf
// to convert goal coords from map frame to odom frame
// receive goal coords from interactive marker
// receive "execute" signals via ROS service client
// execute motion as: 1) spin towards goal; 2) move towards goal x,y; 3: spin to align w/ target orientation
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <visualization_msgs/InteractiveMarkerFeedback.h>
#include <cwru_srv/simple_bool_service_message.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_listener.h>
#include <math.h>
// mnemonics:
const int STAND_STILL = 0;
const int INIT_SPIN = 1;
const int FWD_MOVE = 2;
const int FINAL_SPIN = 3;
const double OMEGA = 0.1;
const double VEL = 0.1;
//globals:
//geometry_msgs::Point marker_point_;
double marker_x_ = 0.0;
double marker_y_ = 0.0;
double marker_phi_ = 0.0;
//geometry_msgs::Point vertex_start;
double target_phi_ = 0.0;
double target_x_ = 0.0;
double target_y_ = 0.0;
// globals for communication w/ callbacks:
double odom_vel_ = 0.0; // measured/published system speed
double odom_omega_ = 0.0; // measured/published system yaw rate (spin)
double odom_x_ = 0.0;
double odom_y_ = 0.0;
double odom_phi_ = 0.0;
double del_phi_init_ = 0.0;
double del_phi_final_ = 0.0;
double phi_start_to_goal_ = 0.0;
double del_dist_ = 0.0;
tf::TransformListener* tfListener_;
bool new_goal_ = false;
//function to strip off sign of x
double sgn(double x) {
if (x > 0.0) return 1.0;
else if (x < 0.0) return -1.0;
else return 0.0;
}
void init_move(void) {
new_goal_ = true; // we received a request, so interpret this as a trigger
//compute the initial heading change, distance to travel, and terminal heading change
target_x_ = marker_x_;
target_y_ = marker_y_;
target_phi_ = marker_phi_;
ROS_INFO(" desired x,y,phi = %f, %f, %f", target_x_, target_y_, target_phi_);
double dx = marker_x_ - odom_x_;
double dy = marker_y_ - odom_y_;
del_dist_ = sqrt(dx * dx + dy * dy);
if (del_dist_ > 0.1) {
phi_start_to_goal_ = atan2(dy, dx);
} else { // for tiny move distance, skip translation and only do rotation
phi_start_to_goal_ = target_phi_;
del_dist_ = 0.0;
}
del_phi_init_ = phi_start_to_goal_ - odom_phi_;
//choose smallest periodic solution to desired heading change;
if (del_phi_init_ > M_PI)
del_phi_init_ -= 2 * M_PI;
if (del_phi_init_<-M_PI)
del_phi_init_ += 2 * M_PI;
del_phi_final_ = target_phi_ - phi_start_to_goal_;
if (del_phi_final_ > M_PI)
del_phi_final_ -= 2 * M_PI;
if (del_phi_final_<-M_PI)
del_phi_final_ += 2 * M_PI;
ROS_INFO("dphi init, phi to goal, dphi final, dist to goal = %f %f %f %f", del_phi_init_, phi_start_to_goal_, del_phi_final_, del_dist_);
}
void processFeedbackFinalPose(
const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback) {
ROS_INFO_STREAM(feedback->marker_name << "marker is now at "
<< feedback->pose.position.x << ", " << feedback->pose.position.y
<< ", " << feedback->pose.position.z);
//ROS_INFO_STREAM("reference frame is: "<<feedback->header.frame_id);
marker_x_ = feedback->pose.position.x;
marker_y_ = feedback->pose.position.y;
double quat_z = feedback->pose.orientation.z;
double quat_w = feedback->pose.orientation.w;
marker_phi_ = 2.0 * atan2(quat_z, quat_w); // cheap conversion from quaternion to heading for planar motion
ROS_INFO_STREAM("heading: " << marker_phi_);
}
void navGoalCallback(
const geometry_msgs::PoseStamped::ConstPtr navPoseMsg) {
//tf::StampedTransform mapToOdom;
//tf::Stamped<tf::Pose> navGoalInMapFrame;
//tf::Stamped<tf::Pose> navGoalInOdomFrame;
//tf::poseStampedMsgToTF(*navPoseMsg, navGoalInMapFrame);
geometry_msgs::PoseStamped navGoalInOdomFrame;
//ROS_INFO_STREAM("reference frame is: "<<feedback->header.frame_id);
double map_goal_x = navPoseMsg->pose.position.x;
double map_goal_y = navPoseMsg->pose.position.y;
//double map_goal_phi;
//marker_x_ = feedback->pose.position.x;
//marker_y_ = feedback->pose.position.y;
//double quat_z = navPoseMsg->pose.orientation.z;
//double quat_w = navPoseMsg->pose.orientation.w;
//map_goal_phi = 2.0 * atan2(quat_z, quat_w); // cheap conversion from quaternion to heading for planar motion
ROS_INFO("new nav goal in map frame: x,y = %f, %f",map_goal_x,map_goal_y);
//ROS_INFO_STREAM("heading: " << map_goal_phi);
//tfListener_->lookupTransform("odom", "map", ros::Time(0), mapToOdom);
//navGoalInOdomFrame = mapToOdom*navGoalInMapFrame;
tfListener_->transformPose("odom",*navPoseMsg,navGoalInOdomFrame);
// tf::Transform handle_pose_in_torso_frame = door_to_torso * handle_pose_in_door_frame;
//navGoalInOdomFrame = mapToOdom*navGoalInMapFrame;
marker_x_ = navGoalInOdomFrame.pose.position.x;
marker_y_ = navGoalInOdomFrame.pose.position.y;
double quat_z = navGoalInOdomFrame.pose.orientation.z;
double quat_w = navGoalInOdomFrame.pose.orientation.w;
marker_phi_ = 2.0 * atan2(quat_z, quat_w); // cheap conversion from quaternion to heading for planar motion
ROS_INFO("nav goal in odom frame: x,y = %f, %f",marker_x_,marker_y_);
ROS_INFO("heading: %f",marker_phi_);
init_move();
}
void odomCallback(const nav_msgs::Odometry& odom_rcvd) {
// copy some of the components of the received message into global vars, for use by "main()"
// we care about speed and spin, as well as position estimates x,y and heading
odom_vel_ = odom_rcvd.twist.twist.linear.x;
odom_omega_ = odom_rcvd.twist.twist.angular.z;
odom_x_ = odom_rcvd.pose.pose.position.x;
odom_y_ = odom_rcvd.pose.pose.position.y;
//odom publishes orientation as a quaternion. Convert this to a simple heading
// see notes above for conversion for simple planar motion
double quat_z = odom_rcvd.pose.pose.orientation.z;
double quat_w = odom_rcvd.pose.pose.orientation.w;
odom_phi_ = 2.0 * atan2(quat_z, quat_w); // cheap conversion from quaternion to heading for planar motion
}
bool triggerCallback(cwru_srv::simple_bool_service_messageRequest& request, cwru_srv::simple_bool_service_messageResponse& response) {
ROS_INFO("path goal trigger callback activated");
response.resp = true; // not really useful in this case--and not necessary
init_move();
return true;
}
int main(int argc, char **argv) {
double dt=0.01;
ros::init(argc, argv, "interactive_robot_commander"); // name of this node
ros::NodeHandle nh; // two lines to create a publisher object that can talk to ROS
//stdr "robot0" is expecting to receive commands on topic: /robot0/cmd_vel
// commands are of type geometry_msgs/Twist, but they use only velocity in x dir and
// yaw rate in z-dir; other 4 fields will be ignored
ros::Publisher cmd_publisher = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1);
// change topic to command abby...
//ros::Publisher cmd_publisher = nh.advertise<geometry_msgs::Twist>("abby/cmd_vel",1);
ros::Subscriber subFinal = nh.subscribe("/path_end/feedback", 1, processFeedbackFinalPose);
ros::Subscriber subNavGoal = nh.subscribe("/move_base_simple/goal", 1, navGoalCallback);
ros::Subscriber subOdom = nh.subscribe("/odom", 1, odomCallback);
ros::ServiceServer service = nh.advertiseService("trigger_path_goal", triggerCallback);
ros::Rate sleep_timer(1/dt); //let's make a 100Hz timer
odom_phi_ = -1000; // impossible value; fix this with odom call
while (odom_phi_ < -100) {
ROS_INFO("waiting for odom");
ros::Duration(0.5).sleep(); // sleep for half a second
ros::spinOnce();
}
// now have a valid odom value, so init marker to these values
ROS_INFO("got valid odom value");
marker_x_ = odom_x_;
marker_y_ = odom_y_;
marker_phi_ = odom_phi_;
//tf::TransformListener tfListener;
tfListener_ = new tf::TransformListener;
tf::StampedTransform mapToOdom;
bool tferr=true;
ROS_INFO("waiting for tf...");
while (tferr) {
tferr=false;
try {
//try to lookup transform from target frame "odom" to source frame "map"
//The direction of the transform returned will be from the target_frame to the source_frame.
//Which if applied to data, will transform data in the source_frame into the target_frame. See tf/CoordinateFrameConventions#Transform_Direction
tfListener_->lookupTransform("odom", "map", ros::Time(0), mapToOdom);
} catch(tf::TransformException &exception) {
ROS_ERROR("%s", exception.what());
tferr=true;
ros::Duration(0.5).sleep(); // sleep for half a second
ros::spinOnce();
}
}
ROS_INFO("tf is good");
//tfListener.transform
//create a variable of type "Twist", as defined in: /opt/ros/hydro/share/geometry_msgs
// any message published on a ROS topic must have a pre-defined format, so subscribers know how to
// interpret the serialized data transmission
geometry_msgs::Twist twist_cmd;
// look at the components of a message of type geometry_msgs::Twist by typing:
// rosmsg show geometry_msgs/Twist
// It has 6 fields. Let's fill them all in with some data:
twist_cmd.linear.x = 0.0;
twist_cmd.linear.y = 0.0;
twist_cmd.linear.z = 0.0;
twist_cmd.angular.x = 0.0;
twist_cmd.angular.y = 0.0;
twist_cmd.angular.z = 0.0;
int phase = 0;
double phase1_spin_to_go = 0.0;
double dist_to_go = 0.0;
double phase3_spin_to_go = 0.0;
double phase1_omega = 0.0;
double phase3_omega = 0.0;
double phase1_spin_sign = 0.0;
double phase3_spin_sign = 0.0;
double fwd_speed = 0.0;
double phi_tol = OMEGA*dt*1.5;
double fwd_tol = VEL*dt*1.5;
while (ros::ok()) {
// if we have a new goal (from trigger), initialize values for a new 3-part move
if (new_goal_) {
ROS_INFO("main: new goal");
new_goal_ = false; //reset the trigger
phase = INIT_SPIN; //restart the spin-move-spin sequence
//initialize distances to go:
phase1_spin_to_go = del_phi_init_;
phase1_spin_sign = sgn(phase1_spin_to_go);
ROS_INFO("phi to go: %f; sgn: %f",phase1_spin_to_go,phase1_spin_sign);
dist_to_go = del_dist_;
phase3_spin_to_go = del_phi_final_;
phase3_spin_sign = sgn(phase3_spin_to_go);
// set speeds for 3 phases:
phase1_omega = phase1_spin_sign*OMEGA;
phase3_omega = phase3_spin_sign*OMEGA;
fwd_speed = VEL;
}
// move incrementally through 3 phases
switch (phase) {
case INIT_SPIN:
ROS_INFO("INIT_SPIN; omega = %f",phase1_omega);
twist_cmd.linear.x = 0.0;
twist_cmd.angular.z = phase1_omega;
phase1_spin_to_go-= phase1_omega*dt;
if (phase1_spin_to_go*phase1_spin_sign<phi_tol) { //test for done with spin
phase=FWD_MOVE;
}
break;
case FWD_MOVE:
ROS_INFO("FWD_MOVE");
twist_cmd.linear.x = fwd_speed;
twist_cmd.angular.z = 0.0;
dist_to_go-= fwd_speed*dt;
if (dist_to_go<fwd_tol) { //test for done with fwd motion
phase=FINAL_SPIN;
}
break;
case FINAL_SPIN:
ROS_INFO("FINAL_SPIN");
twist_cmd.linear.x = 0.0;
twist_cmd.angular.z = phase3_omega;
phase3_spin_to_go-= phase3_omega*dt;
if (phase3_spin_to_go*phase3_spin_sign<phi_tol) { //test for done with spin
phase=STAND_STILL;
ROS_INFO("STAND_STILL");
}
break;
case STAND_STILL:
default:
//ROS_INFO("STAND_STILL");
twist_cmd.linear.x = 0.0;
twist_cmd.linear.y = 0.0;
twist_cmd.linear.z = 0.0;
twist_cmd.angular.x = 0.0;
twist_cmd.angular.y = 0.0;
twist_cmd.angular.z = 0.0;
}
cmd_publisher.publish(twist_cmd); //
sleep_timer.sleep(); // sleep for (remainder of) 10ms
ros::spinOnce();
}
return 0;
} | 40.01227 | 157 | 0.650874 | khairulislam |
12a9eb8a4a390166a79cd5287179c03fe7b75d60 | 14,479 | cpp | C++ | src/Core/Input/InputManager.cpp | lukefelsberg/ObEngine | a0385df4944adde7c1c8073ead15419286c70019 | [
"MIT"
] | 442 | 2017-03-03T11:42:11.000Z | 2021-05-20T13:40:02.000Z | src/Core/Input/InputManager.cpp | lukefelsberg/ObEngine | a0385df4944adde7c1c8073ead15419286c70019 | [
"MIT"
] | 308 | 2017-02-21T10:39:31.000Z | 2021-05-14T21:30:56.000Z | src/Core/Input/InputManager.cpp | lukefelsberg/ObEngine | a0385df4944adde7c1c8073ead15419286c70019 | [
"MIT"
] | 45 | 2017-03-11T15:24:28.000Z | 2021-05-09T15:21:42.000Z | #include <set>
#include <Input/Exceptions.hpp>
#include <Input/InputManager.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Input
{
bool updateOrCleanMonitor(
Event::EventGroupPtr events, const std::weak_ptr<InputButtonMonitor>& element)
{
if (auto monitor = element.lock())
{
monitor->update(events);
return false;
}
else
{
return true;
}
}
bool InputManager::isActionCurrentlyInUse(const std::string& actionId)
{
for (const auto& action : m_currentActions)
{
if (action->getId() == actionId)
{
return true;
}
}
return false;
}
InputManager::InputManager(Event::EventNamespace& eventNamespace)
: e_actions(eventNamespace.createGroup("Actions"))
, e_inputs(eventNamespace.createGroup("Keys"))
, Togglable(true)
{
this->createInputMap();
this->createEvents();
}
InputAction& InputManager::getAction(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return *action.get();
}
}
std::vector<std::string> actionIds;
actionIds.reserve(m_allActions.size());
for (auto& action : m_allActions)
{
actionIds.push_back(action->getId());
}
throw Exceptions::UnknownInputAction(actionId, actionIds, EXC_INFO);
}
void InputManager::update()
{
if (m_enabled)
{
auto actionBuffer = m_currentActions;
for (auto action : actionBuffer)
{
action->update();
}
if (m_refresh)
{
bool shouldRefresh = false;
for (auto& [_, input] : m_inputs)
{
if (input->isPressed())
{
shouldRefresh = true;
break;
}
}
m_monitors.erase(std::remove_if(m_monitors.begin(), m_monitors.end(),
[this](const std::weak_ptr<InputButtonMonitor>& element)
{ return updateOrCleanMonitor(e_inputs, element); }),
m_monitors.end());
for (const auto& monitorPtr : m_monitors)
{
if (const auto& monitor = monitorPtr.lock())
{
if (monitor->checkForRefresh())
{
shouldRefresh = true;
break;
}
}
}
m_refresh = shouldRefresh;
}
}
}
bool InputManager::actionExists(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return true;
}
}
return false;
}
void InputManager::clear()
{
m_currentActions.clear();
for (auto& action : m_allActions)
e_actions->remove(action->getId());
m_allActions.clear();
}
void InputManager::configure(vili::node& config)
{
std::vector<std::string> alreadyInFile;
for (auto& [contextName, context] : config.items())
{
for (auto& [actionName, condition] : context.items())
{
if (!this->actionExists(actionName))
{
m_allActions.push_back(
std::make_unique<InputAction>(e_actions.get(), actionName));
}
else if (!Utils::Vector::contains(actionName, alreadyInFile))
{
this->getAction(actionName).clearConditions();
}
auto inputCondition = [this](InputManager* inputManager, const std::string& action,
vili::node& condition)
{
InputCondition actionCondition;
InputCombination combination;
try
{
combination = this->makeCombination(condition);
}
catch (const BaseException& e)
{
throw Exceptions::InvalidInputCombinationCode(action, condition, EXC_INFO)
.nest(e);
}
actionCondition.setCombination(combination);
Debug::Log->debug(
"<InputManager> Associated Key '{0}' for Action '{1}'", condition, action);
inputManager->getAction(action).addCondition(actionCondition);
};
if (condition.is_primitive())
{
inputCondition(this, actionName, condition);
}
else if (condition.is<vili::array>())
{
for (vili::node& singleCondition : condition)
{
inputCondition(this, actionName, singleCondition);
}
}
this->getAction(actionName).addContext(contextName);
alreadyInFile.push_back(actionName);
}
}
// Add Context keys in real time <REVISION>
}
void InputManager::clearContexts()
{
for (InputAction* action : m_currentActions)
{
action->disable();
}
m_currentActions.clear();
// m_monitors.clear();
}
InputManager& InputManager::addContext(const std::string& context)
{
Debug::Log->debug("<InputManager> Adding Context '{0}'", context);
for (auto& action : m_allActions)
{
if (Utils::Vector::contains(context, action->getContexts())
&& !isActionCurrentlyInUse(action->getId()))
{
Debug::Log->debug(
"<InputManager> Add Action '{0}' in Context '{1}'", action->getId(), context);
m_currentActions.push_back(action.get());
std::vector<InputButtonMonitorPtr> monitors;
for (InputButton* button : action->getInvolvedButtons())
{
monitors.push_back(this->monitor(*button));
}
action->enable(monitors);
}
}
return *this;
}
InputManager& InputManager::removeContext(const std::string& context)
{
//<REVISION> Multiple context, keep which one, remove keys of wrong
// context
m_currentActions.erase(std::remove_if(m_currentActions.begin(), m_currentActions.end(),
[&context](auto& action) -> bool
{
const auto& contexts = action->getContexts();
auto isActionInContext
= std::find(contexts.begin(), contexts.end(), context)
!= contexts.end();
if (isActionInContext)
{
Debug::Log->debug("<InputManager> Remove Action '{0}' "
"from Context '{1}'",
action->getId(), context);
action->disable();
return true;
}
else
{
return false;
}
}),
m_currentActions.end());
return *this;
}
void InputManager::setContext(const std::string& context)
{
this->clearContexts();
this->addContext(context);
}
std::vector<std::string> InputManager::getContexts()
{
std::set<std::string> allContexts;
for (const auto& action : m_currentActions)
{
for (const auto& context : action->getContexts())
{
allContexts.emplace(context);
}
}
return std::vector<std::string>(allContexts.begin(), allContexts.end());
}
InputButton& InputManager::getInput(const std::string& keyId)
{
if (m_inputs.find(keyId) != m_inputs.end())
return *m_inputs[keyId].get();
throw Exceptions::UnknownInputButton(keyId, this->getAllInputButtonNames(), EXC_INFO);
}
std::vector<InputButton*> InputManager::getInputs()
{
std::vector<InputButton*> inputs;
inputs.reserve(m_inputs.size());
for (auto& [_, input] : m_inputs)
{
inputs.push_back(input.get());
}
return inputs;
}
std::vector<InputButton*> InputManager::getInputs(InputType filter)
{
std::vector<InputButton*> inputs;
for (auto& keyIterator : m_inputs)
{
if (keyIterator.second->is(filter))
{
inputs.push_back(keyIterator.second.get());
}
}
return inputs;
}
std::vector<InputButton*> InputManager::getPressedInputs()
{
std::vector<InputButton*> allPressedButtons;
for (auto& keyIterator : m_inputs)
{
if (keyIterator.second->isPressed())
{
allPressedButtons.push_back(keyIterator.second.get());
}
}
return allPressedButtons;
}
InputButtonMonitorPtr InputManager::monitor(const std::string& name)
{
return this->monitor(this->getInput(name));
}
InputButtonMonitorPtr InputManager::monitor(InputButton& input)
{
for (auto& monitor : m_monitors)
{
if (const auto sharedMonitor = monitor.lock())
{
if (&sharedMonitor->getButton() == &input)
return InputButtonMonitorPtr(sharedMonitor);
}
}
InputButtonMonitorPtr monitor = std::make_shared<InputButtonMonitor>(input);
m_monitors.push_back(monitor);
return std::move(monitor);
}
void InputManager::requireRefresh()
{
m_refresh = true;
}
bool isKeyAlreadyInCombination(InputCombination& combination, InputButton* button)
{
for (auto& [monitoredButton, _] : combination)
{
if (monitoredButton == button)
{
return true;
}
}
return false;
}
InputCombination InputManager::makeCombination(const std::string& code)
{
InputCombination combination;
std::vector<std::string> elements = Utils::String::split(code, "+");
if (code != "NotAssociated")
{
for (std::string element : elements)
{
Utils::String::replaceInPlace(element, " ", "");
std::vector<std::string> stateAndButton = Utils::String::split(element, ":");
if (stateAndButton.size() == 1 || stateAndButton.size() == 2)
{
if (stateAndButton.size() == 1)
{
stateAndButton.push_back(stateAndButton[0]);
stateAndButton[0] = "Pressed";
}
std::vector<std::string> stateList
= Utils::String::split(stateAndButton[0], ",");
Types::FlagSet<InputButtonState> buttonStates;
for (std::string& buttonState : stateList)
{
if (Utils::Vector::contains(
buttonState, { "Idle", "Hold", "Pressed", "Released" }))
{
buttonStates |= stringToInputButtonState(buttonState);
}
else
{
throw Exceptions::InvalidInputButtonState(buttonState, EXC_INFO);
}
}
const std::string keyId = stateAndButton[1];
// Detect gamepad button / axis and initialize whole gamepad
if (keyId.substr(0, 3) == "GP_")
{
auto gamepadParts = Utils::String::split(keyId, "_");
unsigned int gamepadIndex;
try
{
gamepadIndex = std::stoi(gamepadParts[1]);
}
catch (const std::invalid_argument& exc)
{
throw Exceptions::InvalidGamepadButton(keyId, EXC_INFO);
}
catch (const std::out_of_range& exc)
{
throw Exceptions::InvalidGamepadButton(keyId, EXC_INFO);
}
this->initializeGamepad(gamepadIndex);
}
if (m_inputs.find(keyId) != m_inputs.end())
{
InputButton& button = this->getInput(keyId);
if (!isKeyAlreadyInCombination(combination, &button))
{
combination.emplace_back(&button, buttonStates);
}
else
{
throw Exceptions::InputButtonAlreadyInCombination(
button.getName(), EXC_INFO);
}
}
else
{
throw Exceptions::UnknownInputButton(
keyId, this->getAllInputButtonNames(), EXC_INFO);
}
}
}
}
return combination;
}
} // namespace obe::Input
| 34.638756 | 99 | 0.457421 | lukefelsberg |
12aa7fa7dcac95d6dcc6274d18bd45dcc4753ecd | 3,342 | cxx | C++ | vital/types/camera_rpc.cxx | judajake/kwiver | 303a11ebb43c020ab8e48b6ef70407b460dba46b | [
"BSD-3-Clause"
] | null | null | null | vital/types/camera_rpc.cxx | judajake/kwiver | 303a11ebb43c020ab8e48b6ef70407b460dba46b | [
"BSD-3-Clause"
] | null | null | null | vital/types/camera_rpc.cxx | judajake/kwiver | 303a11ebb43c020ab8e48b6ef70407b460dba46b | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +29
* Copyright 2013-2018 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 name of Kitware, Inc. nor the names of any contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
* \brief Implementation of \link kwiver::vital::camera_rpc
* camera_rpc \endlink class
*/
#include <vital/types/camera_rpc.h>
#include <vital/io/eigen_io.h>
#include <vital/types/matrix.h>
#include <Eigen/Geometry>
#include <iomanip>
namespace kwiver {
namespace vital {
camera_rpc
::camera_rpc()
: m_logger( kwiver::vital::get_logger( "vital.camera_rpc" ) )
{
}
/// Project a 3D point into a 2D image point
vector_2d
camera_rpc
::project( const vector_3d& pt ) const
{
// Normalize points
vector_3d norm_pt =
( pt - world_offset() ).cwiseQuotient( world_scale() );
// Calculate polynomials
// TODO: why doesn't this work ?
// auto polys = this->rpc_coeffs()*this->power_vector(norm_pt);
auto rpc = this->rpc_coeffs();
auto pv = this->power_vector(norm_pt);
auto polys = rpc*pv;
vector_2d image_pt( polys[0] / polys[1], polys[2] / polys[3]);
// Un-normalize
return image_pt.cwiseProduct( image_scale() ) + image_offset();
}
Eigen::Matrix<double, 20, 1>
simple_camera_rpc
::power_vector( const vector_3d& pt ) const
{
// Form the monomials in homogeneous form
double w = 1.0;
double x = pt.x();
double y = pt.y();
double z = pt.z();
double xx = x * x;
double xy = x * y;
double xz = x * z;
double yy = y * y;
double yz = y * z;
double zz = z * z;
double xxx = xx * x;
double xxy = xx * y;
double xxz = xx * z;
double xyy = xy * y;
double xyz = xy * z;
double xzz = xz * z;
double yyy = yy * y;
double yyz = yy * z;
double yzz = yz * z;
double zzz = zz * z;
// Fill in vector
Eigen::Matrix<double, 20, 1> retVec;
retVec << w, x, y, z, xy, xz, yz, xx, yy, zz,
xyz, xxx, xyy, xzz, xxy, yyy, yzz, xxz, yyz, zzz;
return retVec;
}
} } // end namespace
| 29.839286 | 81 | 0.691203 | judajake |
12aaa1f523e7d7863e05204b6c41eeb1e63a610a | 3,244 | cpp | C++ | ReviewTheMovie/common.cpp | fathurmh/MultiLinkedList | 2343744155c934f24b46c5e4171a395cd143ed65 | [
"MIT"
] | null | null | null | ReviewTheMovie/common.cpp | fathurmh/MultiLinkedList | 2343744155c934f24b46c5e4171a395cd143ed65 | [
"MIT"
] | null | null | null | ReviewTheMovie/common.cpp | fathurmh/MultiLinkedList | 2343744155c934f24b46c5e4171a395cd143ed65 | [
"MIT"
] | null | null | null | // include library c++
#include <conio.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
// include library buatan
#include "common.h"
// using namespace
using namespace std;
// alokasi array 2 dimensi
int *Allocate(int row, int col)
{
// instansiasi baris array
int *arr = new int [row * col + 1];
// kembalikan array
return arr;
}
// dealokasi array 2 dimensi
void Deallocate(int *(&arr))
{
// dealokasi memory baris array
delete[] arr;
}
void Tukar(int *nilai_a, int *nilai_b)
{
int temp = *nilai_a;
*nilai_a = *nilai_b;
*nilai_b = temp;
}
// prosedur menghapus text pada console
void ClearScreen()
{
system("cls");
}
// prosedur menghapus text pada console
// https://stackoverflow.com/questions/10058050/how-to-go-up-a-line-in-console-programs-c
void RemoveLastLine()
{
cout << "\x1b[A";
cout << " ";
cout << "\r";
}
// prosedur cetak text header
void PrintHeader()
{
ClearScreen();
// cetak header
cout << "================================" << endl
<< "======= REVIEW THE MOVIE =======" << endl
<< "================================" << endl << endl;
}
// prosedur cetak text title
void PrintTitle(const char *text)
{
// cetak title
printf("=== %s ===\n\n", text);
}
// prosedur cetak text failed
void Failed(const char *text)
{
// cetak text berwarna merah
printf("\x1B[31m%s\033[0m\n", text);
}
// prosedur cetak text success
void Success(const char *text)
{
// cetak text berwarna hijau
printf("\x1B[32m%s\033[0m\n", text);
}
void Success(const vector<string> ¶ms)
{
stringstream stream;
for (size_t i = 0; i < params.size(); ++i)
{
stream << params[i];
}
Success(stream.str().c_str());
}
// prosedur cetak text warning
void Warning(const char *text)
{
// cetak text berwarna jingga
printf("\x1B[33m%s\033[0m\n", text);
}
void Warning(const vector<string> ¶ms)
{
stringstream stream;
for (size_t i = 0; i < params.size(); ++i)
{
stream << params[i];
}
Warning(stream.str().c_str());
}
// prosedur cetak text information
void Information(const char *text)
{
// cetak text berwarna biru
printf("\x1B[34m%s\033[0m\n", text);
}
// fungsi agar input password menjadi simbol *
// http://www.cplusplus.com/articles/E6vU7k9E/
string GetPassword(const char *prompt, bool show_asterisk)
{
const char BACKSPACE = 8;
const char RETURN = 13;
unsigned char ch = 0;
string password;
cout << prompt;
while ((ch = getch()) != RETURN)
{
if (ch == BACKSPACE)
{
if (password.length() != 0)
{
if (show_asterisk)
{
cout << "\b \b";
}
password.resize(password.length() - 1);
}
}
else if (ch == 0 || ch == 224)
{
getch();
continue;
}
else
{
password += ch;
if (show_asterisk)
{
cout << '*';
}
}
}
cout << endl;
return password;
}
| 19.780488 | 90 | 0.532984 | fathurmh |
12ad891131d3699076a86ccfb91948b790002eb7 | 861 | cpp | C++ | HDU/Bestcoder/87/C/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | HDU/Bestcoder/87/C/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | HDU/Bestcoder/87/C/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#define cls(a) memset(a,0,sizeof(a))
#define rg register
#define rep(i,x,y) for(rg int i=(x);i<=(y);++i)
#define per(i,x,y) for(rg int i=(x);i>=(y);--i)
const int maxn=1e6+10,maxm=1e6+10;
inline void up(int&x,int y){if(y>x)x=y;}
using namespace std;
int n,m,a[maxn],b[maxn],da[maxn],db[maxn],pa[maxn],pb[maxn],c[maxm],la[maxm],lb[maxn];
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
rep(i,1,n)scanf("%d",&a[i]);
rep(i,1,m)scanf("%d",&b[i]);
cls(c);
rep(i,1,n)pa[i]=c[a[i]-1],c[a[i]]=i;
cls(c);
rep(i,1,m)pb[i]=c[b[i]-1],c[b[i]]=i;
rep(i,1,n)da[i]=da[pa[i]]+1;
rep(i,1,m)db[i]=db[pb[i]]+1;
cls(la);cls(lb);
rep(i,1,n)up(la[a[i]],da[i]);
rep(i,1,m)up(lb[b[i]],db[i]);
int ans=0;
rep(i,1,maxm-1)up(ans,min(la[i],lb[i]));
printf("%d\n",ans);
}
return 0;
}
| 26.090909 | 86 | 0.557491 | sjj118 |
12aedf4cb4475e1ce53ffae84dab0f2ac3d35105 | 8,577 | cc | C++ | paddle/phi/kernels/cpu/group_norm_kernel.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 11 | 2016-08-29T07:43:26.000Z | 2016-08-29T07:51:24.000Z | paddle/phi/kernels/cpu/group_norm_kernel.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | null | null | null | paddle/phi/kernels/cpu/group_norm_kernel.cc | L-Net-1992/Paddle | 4d0ca02ba56760b456f3d4b42a538555b9b6c307 | [
"Apache-2.0"
] | 1 | 2021-09-24T11:23:36.000Z | 2021-09-24T11:23:36.000Z | // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/phi/kernels/group_norm_kernel.h"
#include <algorithm>
#include <array>
#include <numeric>
#include <string>
#include "paddle/phi/backends/cpu/cpu_context.h"
#include "paddle/phi/common/layout.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/eigen/extensions.h"
#include "paddle/phi/kernels/funcs/math_function.h"
namespace phi {
template <typename T, typename Context>
void GroupNormKernel(const Context& dev_ctx,
const DenseTensor& x,
const paddle::optional<DenseTensor>& scale,
const paddle::optional<DenseTensor>& bias,
float epsilon,
int groups,
const std::string& data_layout_str,
DenseTensor* y,
DenseTensor* mean,
DenseTensor* var) {
const DataLayout data_layout =
paddle::framework::StringToDataLayout(data_layout_str);
const auto scale_ptr = scale.get_ptr();
const auto bias_ptr = bias.get_ptr();
const auto x_dims = x.dims();
const int C = (data_layout == DataLayout::kNCHW ? x_dims[1]
: x_dims[x_dims.size() - 1]);
const int group_size = C / groups;
dev_ctx.template Alloc<T>(y);
dev_ctx.template Alloc<T>(mean);
dev_ctx.template Alloc<T>(var);
auto* x_data = x.data<T>();
auto* y_data = y->data<T>();
auto* mean_data = mean->data<T>();
auto* var_data = var->data<T>();
const T* scale_data = nullptr;
if (scale_ptr) scale_data = scale_ptr->data<T>();
const T* bias_data = nullptr;
if (bias_ptr) bias_data = bias_ptr->data<T>();
int imsize = 1;
if (data_layout == DataLayout::kNCHW) {
for (int i = 2; i < x_dims.size(); ++i) {
imsize *= x_dims[i];
}
} else {
for (int i = 1; i < x_dims.size() - 1; ++i) {
imsize *= x_dims[i];
}
}
auto* iter_x_data = x_data;
auto* iter_y_data = y_data;
for (int bid = 0; bid < x_dims[0]; bid++) {
for (int gid = 0; gid < groups; gid++) {
const int64_t M = 8;
std::array<T, M> x_mean_arr;
std::array<T, M> x_var_arr;
std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
T x_mean = 0, x_var = 0;
int number = std::min(group_size, static_cast<int>(C - gid * group_size));
auto* tmp_x = iter_x_data;
auto* x_src_data = iter_x_data;
auto* tmp_y = iter_y_data;
auto* y_src_data = iter_y_data;
if (data_layout == DataLayout::kNCHW) {
for (int cid = 0; cid < number; cid++) {
int imid;
for (imid = 0; imid < imsize - (imsize % M);
imid += M, iter_x_data += M) {
// TODO(gaoxiang): Because AVX/AVX2/AVX512 can not directly used
// in template class/function, before we complete high
// performance cpu vector extension, temporarily unrolling
// loop to get high precision and performance
x_mean_arr[0] += iter_x_data[0];
x_var_arr[0] += iter_x_data[0] * iter_x_data[0];
x_mean_arr[1] += iter_x_data[1];
x_var_arr[1] += iter_x_data[1] * iter_x_data[1];
x_mean_arr[2] += iter_x_data[2];
x_var_arr[2] += iter_x_data[2] * iter_x_data[2];
x_mean_arr[3] += iter_x_data[3];
x_var_arr[3] += iter_x_data[3] * iter_x_data[3];
x_mean_arr[4] += iter_x_data[4];
x_var_arr[4] += iter_x_data[4] * iter_x_data[4];
x_mean_arr[5] += iter_x_data[5];
x_var_arr[5] += iter_x_data[5] * iter_x_data[5];
x_mean_arr[6] += iter_x_data[6];
x_var_arr[6] += iter_x_data[6] * iter_x_data[6];
x_mean_arr[7] += iter_x_data[7];
x_var_arr[7] += iter_x_data[7] * iter_x_data[7];
}
x_mean =
std::accumulate(x_mean_arr.cbegin(), x_mean_arr.cend(), x_mean);
x_var = std::accumulate(x_var_arr.cbegin(), x_var_arr.cend(), x_var);
std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
for (; imid < imsize; imid++, iter_x_data++) {
x_mean += iter_x_data[0];
x_var += iter_x_data[0] * iter_x_data[0];
}
}
} else {
for (int cid = 0; cid < number; cid++) {
iter_x_data = tmp_x + cid;
int imid;
for (imid = 0; imid < imsize - (imsize % M);
imid += M, iter_x_data += M * C) {
// TODO(gaoxiang): Because AVX/AVX2/AVX512 can not directly used
// in template class/function, before we complete high
// performance cpu vector extension, temporarily unrolling
// loop to get high precision and performance
x_mean_arr[0] += iter_x_data[0 * C];
x_var_arr[0] += iter_x_data[0 * C] * iter_x_data[0 * C];
x_mean_arr[1] += iter_x_data[1 * C];
x_var_arr[1] += iter_x_data[1 * C] * iter_x_data[1 * C];
x_mean_arr[2] += iter_x_data[2 * C];
x_var_arr[2] += iter_x_data[2 * C] * iter_x_data[2 * C];
x_mean_arr[3] += iter_x_data[3 * C];
x_var_arr[3] += iter_x_data[3 * C] * iter_x_data[3 * C];
x_mean_arr[4] += iter_x_data[4 * C];
x_var_arr[4] += iter_x_data[4 * C] * iter_x_data[4 * C];
x_mean_arr[5] += iter_x_data[5 * C];
x_var_arr[5] += iter_x_data[5 * C] * iter_x_data[5 * C];
x_mean_arr[6] += iter_x_data[6 * C];
x_var_arr[6] += iter_x_data[6 * C] * iter_x_data[6 * C];
x_mean_arr[7] += iter_x_data[7 * C];
x_var_arr[7] += iter_x_data[7 * C] * iter_x_data[7 * C];
}
x_mean =
std::accumulate(x_mean_arr.cbegin(), x_mean_arr.cend(), x_mean);
x_var = std::accumulate(x_var_arr.cbegin(), x_var_arr.cend(), x_var);
std::fill(x_mean_arr.begin(), x_mean_arr.end(), T(0));
std::fill(x_var_arr.begin(), x_var_arr.end(), T(0));
for (; imid < imsize; imid++, iter_x_data += C) {
x_mean += iter_x_data[0];
x_var += iter_x_data[0] * iter_x_data[0];
}
}
iter_x_data = tmp_x + group_size;
}
x_mean /= number * imsize;
x_var /= number * imsize;
x_var = std::max(x_var - x_mean * x_mean, T(0));
T var_inv = T(1) / std::sqrt(x_var + epsilon);
mean_data[bid * groups + gid] = x_mean;
var_data[bid * groups + gid] = x_var;
if (data_layout == DataLayout::kNCHW) {
for (int cid = 0; cid < number; cid++) {
for (int imid = 0; imid < imsize; imid++, tmp_x++, iter_y_data++) {
T val = (tmp_x[0] - x_mean) * var_inv;
if (scale_data) val *= scale_data[gid * group_size + cid];
if (bias_data) val += bias_data[gid * group_size + cid];
iter_y_data[0] = val;
}
}
} else {
for (int cid = 0; cid < number; cid++) {
tmp_x = x_src_data + cid;
iter_y_data = y_src_data + cid;
for (int imid = 0; imid < imsize;
imid++, tmp_x += C, iter_y_data += C) {
T val = (tmp_x[0] - x_mean) * var_inv;
if (scale_data) val *= scale_data[gid * group_size + cid];
if (bias_data) val += bias_data[gid * group_size + cid];
iter_y_data[0] = val;
}
}
iter_y_data = tmp_y + group_size;
}
}
if (data_layout == DataLayout::kNHWC) {
iter_x_data = x_data + (bid + 1) * C * imsize;
iter_y_data = y_data + (bid + 1) * C * imsize;
}
}
}
} // namespace phi
PD_REGISTER_KERNEL(
group_norm, CPU, ALL_LAYOUT, phi::GroupNormKernel, float, double) {}
| 40.649289 | 80 | 0.565932 | L-Net-1992 |
12b3a8f7536adbc3e318bac566e8c329658d45d0 | 20,896 | cpp | C++ | FinalProject/src/preprocess.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | 1 | 2018-06-20T12:29:52.000Z | 2018-06-20T12:29:52.000Z | FinalProject/src/preprocess.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | null | null | null | FinalProject/src/preprocess.cpp | zuimrs/ImageProcess | 8a699668c71e45e7910a6bfcb3ab0589d878cbfa | [
"MIT"
] | null | null | null | #include "preprocess.h"
#include <iostream>
#include <cmath>
#include <algorithm>
#define PI 3.14159265
#define gFilterx 5
#define gFiltery 5
#define sigma 1
#define threshold_low 100
#define threshold_high 120
#define theta_size 500
using namespace std;
using namespace cimg_library;
Preprocess::Preprocess(string input,string output)
{
// 读取图片
this->point_num = 4;
this->img.load(input.c_str());
CImg<float> temp = this->img;
// 下采样,增加运算速度
this-> scale = temp._width / 300;
temp.resize(img._width/scale,img._height/scale);
// 转灰度图
CImg<float> gray =this->toGrayScale(temp);
// this->gray = this->toGrayScale(this->img);
// 高斯滤波
this->filter = createFilter(gFilterx,gFiltery,sigma);
CImg<float> gFiltered = this->useFilter(gray,this->filter);
// Canny
CImg<float> angles;
CImg<float> sFiltered = this->sobel(gFiltered,angles);
CImg<float> non = this->nonMaxSupp(sFiltered,angles);
this->thres = this->threshold(non,threshold_low,threshold_high);
// 霍夫变换
for(int i = 0 ; i < theta_size; ++i)
{
tabSin.push_back(sin(PI*i/(theta_size)));
tabCos.push_back(cos(PI*i/(theta_size)));
}
this->houghLinesTransform(thres);
this->houghLinesDetect();
// 检测边界
this->findEdge();
this->findPoint();
this->edge_line.display();
// morphing
// 读取并标定角点顺序
this->sort_corner = this->SortCorner(this->corner);
// 判断方向
if(this->direction == VERTICAL)
this->result = CImg<unsigned char>(210*2,297*2,1,3,0);
else
this->result = CImg<unsigned char>(297*2,210*2,1,3,0);
// 初始化投影坐标
vector<pair<int,int> > uv;
uv.push_back(make_pair(0,0));
uv.push_back(make_pair(0,this->result._height));
uv.push_back(make_pair(this->result._width,this->result._height));
uv.push_back(make_pair(this->result._width,0));
// 计算投影矩阵
this->trans_matrix = ComputeMatrix(this->sort_corner,uv);
// 投影
cimg_forXY(this->result,x,y)
{
pair<int, int> point = this->Transform(this->trans_matrix, make_pair(x,y));
int u = point.first;
int v = point.second;
this->result._atXY(x,y,0,0) = this->img._atXY(u,v,0,0);
this->result._atXY(x,y,0,1) = this->img._atXY(u,v,0,1);
this->result._atXY(x,y,0,2) = this->img._atXY(u,v,0,2);
}
this->result.display();
gray = this->toGrayScale(this->result);
// Canny
// gray = this->useFilter(gray,this->filter);
// gray.display();
sFiltered = this->sobel(gray,angles);
non = this->nonMaxSupp(sFiltered,angles);
CImg<float> binary = this->threshold(non,127,180);
binary.display();
CImg<bool> se0(3,3),se1(3,3);
se0.fill(1); // Structuring element 1
se1.fill(0,1,0,1,1,1,0,1,0);
binary = binary.get_dilate(se0);
binary.display();
binary = binary.get_erode(se1);
binary.display();
binary = toBinaryScale(binary);
// // binary = this->useFilter(binary,this->filter);
binary.save(output.c_str());
}
CImg<float> Preprocess::toBinaryScale(CImg<float> input){
CImg<float> output = CImg<float>(input._width,input._height,1,1);
cimg_forXY(input,x,y)
{
if(input._atXY(x,y) == 255){
output._atXY(x,y) = 0;
}else{
output._atXY(x,y) = 255;
}
}
return output;
}
float Preprocess::getMeanPixel(CImg<float> input,int x,int y,int window_size)
{
float sum = 0;
int width = input._width;
int height = input._height;
for(int i = x - window_size/2; i < x + window_size/2;++i)
{
if(i < 0 || i > width)
continue;
for(int j = y - window_size/2;j < y+window_size/2;++j)
{
if(j < 0 || j > height)
continue;
sum += input._atXY(i,j);
}
}
return sum/(window_size*window_size);
}
CImg<float> Preprocess::toGrayScale(CImg<float> input)
{
CImg<float>output = CImg<float>(input._width,input._height,1,1);
cimg_forXY(input,x,y)
{
float r = input._atXY(x,y,0,0);
float g = input._atXY(x,y,0,1);
float b = input._atXY(x,y,0,2);
int newValue = (r * 0.2126 + g * 0.7152 + b * 0.0722);
output._atXY(x,y) = newValue;
}
return output;
}
vector<vector<float> > Preprocess::createFilter(int row,int column,float sigmaIn)
{
vector<vector<float> > filter;
for (int i = 0; i < row; i++)
{
vector<float> col;
for (int j = 0; j < column; j++)
{
col.push_back(-1);
}
filter.push_back(col);
}
float coordSum = 0;
float constant = 2.0 * sigmaIn * sigmaIn;
// Sum is for normalization
float sum = 0.0;
for (int x = - row/2; x <= row/2; x++)
{
for (int y = -column/2; y <= column/2; y++)
{
coordSum = (x*x + y*y);
filter[x + row/2][y + column/2] = (exp(-(coordSum) / constant)) / (M_PI * constant);
sum += filter[x + row/2][y + column/2];
}
}
// Normalize the Filter
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
filter[i][j] /= sum;
return filter;
}
CImg<float> Preprocess::useFilter(CImg<float> & img_in,vector<vector<float> >& filterIn)
{
int size = (int)filterIn.size()/2;
CImg<float> filteredImg(img_in._width , img_in._height , 1,1);
filteredImg.fill(0);
for (int i = size; i < img_in._width - size; i++)
{
for (int j = size; j < img_in._height - size; j++)
{
float sum = 0;
for (int x = 0; x < filterIn.size(); x++)
for (int y = 0; y < filterIn.size(); y++)
{
sum += filterIn[x][y] * (float)(img_in._atXY(i + x - size, j + y - size));
}
filteredImg._atXY(i, j) = sum;
}
}
return filteredImg;
}
CImg<float> Preprocess::sobel(CImg<float> & gFiltered,CImg<float>& angles )
{
//Sobel X Filter
float x1[] = {-1.0, 0, 1.0};
float x2[] = {-2.0, 0, 2.0};
float x3[] = {-1.0, 0, 1.0};
vector<vector<float> > xFilter(3);
xFilter[0].assign(x1, x1+3);
xFilter[1].assign(x2, x2+3);
xFilter[2].assign(x3, x3+3);
//Sobel Y Filter
float y1[] = {-1.0, -2.0, -1.0};
float y2[] = {0, 0, 0};
float y3[] = {1.0, 2.0, 1.0};
vector<vector<float> > yFilter(3);
yFilter[0].assign(y1, y1+3);
yFilter[1].assign(y2, y2+3);
yFilter[2].assign(y3, y3+3);
//Limit Size
int size = (int)xFilter.size()/2;
CImg<float> filteredImg(gFiltered._width , gFiltered._height ,1,1);
filteredImg.fill(0);
angles = CImg<float>(gFiltered._width , gFiltered._height ,1,1); //AngleMap
angles.fill(0);
for (int i = size + gFilterx/2; i < gFiltered._width - size - gFilterx/2 ; i++)
{
for (int j = size + gFilterx/2; j < gFiltered._height - size - gFilterx/2; j++)
{
float sumx = 0;
float sumy = 0;
for (int x = 0; x < xFilter.size(); x++)
for (int y = 0; y < xFilter.size(); y++)
{
sumx += xFilter[y][x] * (float)(gFiltered._atXY(i + x - size, j + y - size)); //Sobel_X Filter Value
sumy += yFilter[y][x] * (float)(gFiltered._atXY(i + x - size, j + y - size)); //Sobel_Y Filter Value
}
float sumxsq = sumx*sumx;
float sumysq = sumy*sumy;
float sq2 = sqrt(sumxsq + sumysq);
if(sq2 > 255) //Unsigned Char Fix
sq2 =255;
filteredImg._atXY(i, j) = sq2;
if(sumx==0) //Arctan Fix
angles._atXY(i, j) = 90;
else
angles._atXY(i, j) = atan(sumy/sumx) * 180 / PI;
}
}
return filteredImg;
}
CImg<float> Preprocess::nonMaxSupp(CImg<float> & sFiltered,CImg<float> & angles)
{
CImg<float> nonMaxSupped (sFiltered._width, sFiltered._height, 1,1);
nonMaxSupped.fill(0);
for (int i=1; i< sFiltered._width - 1; i++) {
for (int j=1; j<sFiltered._height - 1; j++) {
float Tangent = angles._atXY(i,j);
nonMaxSupped._atXY(i, j) = sFiltered._atXY(i,j);
//Horizontal Edge
if ((-22.5 < Tangent) && (Tangent <= 22.5))
{
if ((sFiltered._atXY(i,j) < sFiltered._atXY(i,j+1)) || (sFiltered._atXY(i,j) < sFiltered._atXY(i,j-1)))
nonMaxSupped._atXY(i, j) = 0;
}
//Vertical Edge
if ((Tangent <= -67.5) || (67.5 < Tangent))
{
if ((sFiltered._atXY(i,j) < sFiltered._atXY(i+1,j)) || (sFiltered._atXY(i,j) < sFiltered._atXY(i-1,j)))
nonMaxSupped._atXY(i, j) = 0;
}
//-45 Degree Edge
if ((-67.5 < Tangent) && (Tangent <= -22.5))
{
if ((sFiltered._atXY(i,j) < sFiltered._atXY(i-1,j+1)) || (sFiltered._atXY(i,j) < sFiltered._atXY(i+1,j-1)))
nonMaxSupped._atXY(i, j) = 0;
}
//45 Degree Edge
if ((22.5 < Tangent) && (Tangent <= 67.5))
{
if ((sFiltered._atXY(i,j) < sFiltered._atXY(i+1,j+1)) || (sFiltered._atXY(i,j) < sFiltered._atXY(i-1,j-1)))
nonMaxSupped._atXY(i, j) = 0;
}
}
}
return nonMaxSupped;
}
CImg<float> Preprocess::threshold(CImg<float> & imgin,int low, int high)
{
if(low > 255)
low = 255;
if(high > 255)
high = 255;
CImg<float> EdgeMat(imgin._width, imgin._height, 1,1);
for (int i=0; i<imgin._width; i++)
{
for (int j = 0; j<imgin._height; j++)
{
EdgeMat._atXY(i,j) = imgin._atXY(i,j);
if(EdgeMat._atXY(i,j) > high)
EdgeMat._atXY(i,j) = 255;
else if(EdgeMat._atXY(i,j) < low)
EdgeMat._atXY(i,j) = 0;
else
{
bool anyHigh = false;
bool anyBetween = false;
for (int x=i-1; x < i+2; x++)
{
for (int y = j-1; y<j+2; y++)
{
if(x <= 0 || y <= 0 || EdgeMat._height || y > EdgeMat._width) //Out of bounds
continue;
else
{
if(EdgeMat._atXY(x,y) > high)
{
EdgeMat._atXY(i,j) = 255;
anyHigh = true;
break;
}
else if(EdgeMat._atXY(x,y) <= high && EdgeMat._atXY(x,y) >= low)
anyBetween = true;
}
}
if(anyHigh)
break;
}
if(!anyHigh && anyBetween)
for (int x=i-2; x < i+3; x++)
{
for (int y = j-1; y<j+3; y++)
{
if(x < 0 || y < 0 || x > EdgeMat._height || y > EdgeMat._width) //Out of bounds
continue;
else
{
if(EdgeMat._atXY(x,y) > high)
{
EdgeMat._atXY(i,j) = 255;
anyHigh = true;
break;
}
}
}
if(anyHigh)
break;
}
if(!anyHigh)
EdgeMat._atXY(i,j) = 0;
}
}
}
return EdgeMat;
}
// 映射到霍夫空间
void Preprocess::houghLinesTransform(CImg<float> &imgin)
{
int width = imgin._width;
int height = imgin._height;
int max_length = sqrt((width/2)*(width/2) + (height/2)*(height/2));
int rows = theta_size,cols = max_length*2;
this->houghspace = CImg<float>(cols,rows);
this->houghspace.fill(0);
cimg_forXY(imgin,x,y)
{
int p = imgin._atXY(x,y);
if(p == 0 )
{
continue;
}
int x0 = x - width/2;
int y0 = height/2 - y;
for(int i = 0 ; i < theta_size;++i)
{
int r = int(x0 * tabCos[i] + y0 * tabSin[i] ) + max_length;
if(r < 0 || r >= max_length*2)
{
continue;
}
this->houghspace ._atXY(r,i) += 1;
}
}
}
bool compare(pair<int,int> a,pair<int,int> b)
{
return a.second > b.second;
}
void Preprocess::houghLinesDetect()
{
int width = this->houghspace._width;
int height = this->houghspace._height;
// 霍夫空间取极大值点
int window_size = 40;
for(int i = 0 ; i < height ;i += window_size/2)
{
for(int j = 0 ; j < width ;j += window_size/2)
{
int max = getMaxValue(this->houghspace,window_size,i,j);
int y_max = i + window_size < height?i + window_size : height;
int x_max = j + window_size < width?j + window_size:width;
bool is_max = true;
for(int y = i; y < i + window_size;++y)
{
for(int x = j;x < j + window_size;++x)
{
if(this->houghspace._atXY(x,y) < max)
this->houghspace._atXY(x,y) = 0;
else if(!is_max)
{
this->houghspace._atXY(x,y) = 0;
}
else
{
is_max = false;
}
}
}
}
}
// 所有的极大值点保存到line数组中
cimg_forXY(this->houghspace,x,y)
{
if(this->houghspace._atXY(x,y)>0)
this->lines.push_back(make_pair(y*width+x,this->houghspace._atXY(x,y)));
}
// 根据权重从大到小排序
sort(this->lines.begin(),this->lines.end(),compare);
}
// 获取一个窗口内最大权重
int Preprocess::getMaxValue(CImg<float> &img,int &size,int &y,int &x)
{
int max = 0;
int width = x+size > img._width?img._width:x+size;
int height = y + size > img._height?img._height:y + size;
for(int j = x; j < width;++j )
{
for(int i = y ; i < height ;++i)
{
if(img._atXY(j,i) > max)
max = img._atXY(j,i);
}
}
return max;
}
void Preprocess::findEdge()
{
int max_length = this->houghspace._width / 2;
this->edge_line = CImg<float>(this->thres._width,this->thres._height,1,1,0);
// 取前point_num条边
for(int i = 0 ; i < this->point_num; ++i)
{
int n = this->lines[i].first;
int theta = n / this->houghspace._width;
int r = n % this->houghspace._width - max_length;
this->edge.push_back(make_pair(theta,r));
cout <<"theta:"<< (theta*1.0/500)*180 << " r:" << r <<" weight:" << this->lines[i].second<< endl;
for(int x = 0 ; x < this->thres._width ;++x)
{
for(int y = 0 ; y < this->thres._height ; ++y )
{
int x0 = x - this->thres._width/2 ;
int y0 = this->thres._height/2 - y ;
if(r == int(x0 * tabCos[theta] + y0 * tabSin[theta] ))
{
this->edge_line._atXY(x,y) += 255.0/2;
}
}
}
}
}
void Preprocess::findPoint()
{
int width = this->thres._width;
int height = this->thres._height;
int max_length = this->houghspace._width / 2;
int n1,n2,r1,r2,theta1,theta2;
double x,y;
unsigned char red[3] = {255,0,0};
for(int i = 0; i < this->point_num;++i){
for(int j=i+1;j< this->point_num;++j){
r1 = this->edge[i].second;
r2 = this->edge[j].second;
theta1 =this->edge[i].first;
theta2 =this->edge[j].first;
if(abs(theta1-theta2)<40)
continue;
y = (r2)*1.0/tabCos[int(theta2)] - (r1)*1.0/tabCos[int(theta1)];
y = y*1.0/(tabSin[int(theta2)]/tabCos[int(theta2)] - tabSin[int(theta1)]/tabCos[int(theta1)]);
x = r1/tabCos[int(theta1)] - y*tabSin[int(theta1)]/tabCos[int(theta1)];
cout <<"x: " << (x+width/2) <<" y:" << (height/2-y) << endl;
this->corner.push_back(make_pair(int(scale*(x+width/2)),int(scale*(height/2-y))));
// this->img.draw_circle(int(scale*(x+width/2)) ,int(scale*(height/2-y)) ,3,red);
}
}
}
vector<pair<int,int> > Preprocess::SortCorner(vector<pair<int,int> > & corner)
{
vector<pair<int,int> >result(4);
int center_x = 0,center_y = 0;
for(int i = 0 ; i < corner.size(); ++i)
{
center_x += corner[i].first;
center_y += corner[i].second;
}
center_x /= corner.size();
center_y /= corner.size();
int count = 0;
for(int i = 0 ; i < corner.size(); ++i)
{
if(corner[i].first <= center_x &&
corner[i].second <= center_y)
{
count ++;
}
}
if(count ==1 )
{
for(int i = 0 ; i < corner.size(); ++i)
{
if(corner[i].first <= center_x &&
corner[i].second <= center_y)
result[0] = corner[i];
else if(corner[i].first <= center_x &&
corner[i].second >= center_y)
result[1] = corner[i];
else if(corner[i].first >= center_x &&
corner[i].second >= center_y)
result[2] = corner[i];
else if(corner[i].first >= center_x &&
corner[i].second <= center_y)
result[3] = corner[i];
}
int delta_x = abs(result[0].first - center_x);
int delta_y = abs(result[0].second - center_y);
this->direction = delta_x < delta_y?VERTICAL:HORIZONTAL;
}else if(count == 2)
{
vector<pair<int,int> >left;
vector<pair<int,int> >right;
for(int i = 0 ; i < corner.size(); ++i)
{
if(corner[i].first <= center_x &&
corner[i].second <= center_y)
{
left.push_back(corner[i]);
}
else if(corner[i].first >= center_x &&
corner[i].second >= center_y)
{
right.push_back(corner[i]);
}
}
result[0] = left[0].first > left[1].first ? left[0]:left[1];
result[1] = left[0].first < left[1].first ? left[0]:left[1];
result[2] = right[0].first < right[1].first ? right[0]:right[1];
result[3] = right[0].first > right[1].first ? right[0]:right[1];
int delta_x = abs(result[0].first - center_x);
int delta_y = abs(result[0].second - center_y);
this->direction = delta_x > delta_y?VERTICAL:HORIZONTAL;
}
return result;
}
vector<float> Preprocess::ComputeMatrix(vector<pair<int,int> > uv,vector<pair<int,int> >xy)
{
//get the 8 point
float u1 = uv[0].first;
float u2 = uv[1].first;
float u3 = uv[2].first;
float u4 = uv[3].first;
float x1 = xy[0].first;
float x2 = xy[1].first;
float x3 = xy[2].first;
float x4 = xy[3].first;
float v1 = uv[0].second;
float v2 = uv[1].second;
float v3 = uv[2].second;
float v4 = uv[3].second;
float y1 = xy[0].second;
float y2 = xy[1].second;
float y3 = xy[2].second;
float y4 = xy[3].second;
float A[8][9] = {
{x1, y1, 1, 0, 0, 0, -u1*x1, -u1*y1, u1},
{0, 0, 0, x1, y1, 1, -v1*x1, -v1*y1, v1},
{x2, y2, 1, 0, 0, 0, -u2*x2, -u2*y2, u2},
{0, 0, 0, x2, y2, 1, -v2*x2, -v2*y2, v2},
{x3, y3, 1, 0, 0, 0, -u3*x3, -u3*y3, u3},
{0, 0, 0, x3, y3, 1, -v3*x3, -v3*y3, v3},
{x4, y4, 1, 0, 0, 0, -u4*x4, -u4*y4, u4},
{0, 0, 0, x4, y4, 1, -v4*x4, -v4*y4, v4},
};
if(A[0][0] == 0)
{
for(int i = 1;i < 8;i++)
{
if(A[i][0] != 0)
{
//swap the row and break
float temp;
for(int j = 0;j < 9;j++)
{
temp = A[0][j];
A[0][j] = A[i][j];
A[i][j] = temp;
}
break;
}
}
}
for(int i = 1;i < 8;i++)
{
float max = 0;
int index;
for(int j = i-1;j < 8;j++)
{
if(abs(A[j][i-1]) > max)
{
max = abs(A[j][i-1]);
index = j;
}
}
for(int j = 0;j < 9;j++)
{
float temp = A[i-1][j];
A[i-1][j] = A[index][j];
A[index][j] = temp;
}
for(int j = i;j < 8;j++)
{
float x = A[j][i-1] / A[i-1][i-1];
for(int k = i-1;k < 9;k++)
{
A[j][k] = A[j][k] - x*A[i-1][k];
}
}
if(A[i][i] == 0)
{
for(int j = i+1;j < 8;j++)
{
if(A[j][i] != 0)
{
float temp;
for(int k = 0;k < 9;k++)
{
temp = A[i][k];
A[i][k] = A[j][k];
A[j][k] = temp;
}
break;
}
}
}
}
vector<float> result(8);
for(int i = 7;i >= 0;i--)
{
float b = A[i][8];
for(int j = 7;j >= i+1;j--)
b = b - A[i][j] * result[j];
result[i] = b/A[i][i];
}
return result;
}
pair<int, int> Preprocess::Transform(vector<float> matrix, pair<int,int> point)
{
int u = point.first;
int v = point.second;
float q = matrix[6]*u + matrix[7]*v + 1;
float x = (matrix[0]*u + matrix[1]*v + matrix[2])/q;
float y = (matrix[3]*u + matrix[4]*v + matrix[5])/q;
// 四舍五入,最近临
return pair<int, int>((int)x+0.5f, (int)y+0.5f);
}
| 29.266106 | 123 | 0.496746 | zuimrs |
12b59315bad515d1e38175454fc0687f05006d38 | 586 | hpp | C++ | bnl/base/include/bnl/ip/host.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | 4 | 2019-07-29T07:54:20.000Z | 2020-05-14T10:12:59.000Z | bnl/base/include/bnl/ip/host.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | null | null | null | bnl/base/include/bnl/ip/host.hpp | DaanDeMeyer/h3c | 5fe5705afeebda94eb2fc8483dac6846b2deb85f | [
"MIT"
] | 1 | 2020-05-14T10:12:58.000Z | 2020-05-14T10:12:58.000Z | #pragma once
#include <bnl/base/string.hpp>
#include <bnl/base/string_view.hpp>
#include <iosfwd>
namespace bnl {
namespace ip {
class BNL_BASE_EXPORT host {
public:
host() = default;
host(std::string name) noexcept; // NOLINT
host(const char *name) noexcept; // NOLINT
host(const host &) = default;
host &operator=(const host &) = default;
host(host &&) = default;
host &operator=(host &&) = default;
base::string_view name() const noexcept;
private:
base::string name_;
};
BNL_BASE_EXPORT std::ostream &
operator<<(std::ostream &os, const host &host);
}
}
| 17.235294 | 47 | 0.679181 | DaanDeMeyer |
12b9950e74d79f79af2f0875a57b17c00dc10b4c | 1,125 | cpp | C++ | src/DecayingShapesFromNotes.cpp | kant/GeoLEDic | 3cfb343576c9fb1a5470b0f604891b7d9033cdbb | [
"MIT"
] | null | null | null | src/DecayingShapesFromNotes.cpp | kant/GeoLEDic | 3cfb343576c9fb1a5470b0f604891b7d9033cdbb | [
"MIT"
] | 8 | 2021-06-14T09:09:28.000Z | 2021-12-05T04:56:08.000Z | src/DecayingShapesFromNotes.cpp | kant/GeoLEDic | 3cfb343576c9fb1a5470b0f604891b7d9033cdbb | [
"MIT"
] | 1 | 2021-11-12T01:39:56.000Z | 2021-11-12T01:39:56.000Z | #include "DecayingShapesFromNotes.hpp"
DecayingShapesFromNotes::DecayingShapesFromNotes():
m_decay_rate(10),
m_any_triangle_set(false)
{
std::fill_n(m_decaying_triangles, DOME_NUM_TRIANGLES, 0);
}
void DecayingShapesFromNotes::run()
{
bool triangle_set = false;
for (uint8_t k = 0; k < DOME_NUM_TRIANGLES; k++)
{
uint8_t vel = ShapesFromNotes::getTriangleValue(k);
if (vel == m_decaying_triangles[k])
{
triangle_set |= vel > 0;
continue;
}
if (vel > 0)
{
m_decaying_triangles[k] = vel;
}
else
{
m_decaying_triangles[k] = std::max(0, int(m_decaying_triangles[k]) - m_decay_rate);
}
if (m_decaying_triangles[k] > 0)
{
triangle_set = true;
}
}
m_any_triangle_set = triangle_set;
}
void DecayingShapesFromNotes::setDecayRate(uint8_t rate)
{
m_decay_rate = rate;
}
uint8_t DecayingShapesFromNotes::getTriangleValue(uint8_t note) const
{
return m_decaying_triangles[note];
}
bool DecayingShapesFromNotes::isAnyTriangleSet() const
{
return m_any_triangle_set;
}
| 20.833333 | 92 | 0.655111 | kant |
12ba26c5dee285dbb83297a364b73d1766fc7e38 | 21,042 | cc | C++ | src/Point_ClosedOrbitCheby.cc | PaulMcMillan-Astro/TorusLight | 4a08998a5cc918b369414437ae8df109d7a926ee | [
"MIT"
] | 1 | 2015-12-18T16:27:53.000Z | 2015-12-18T16:27:53.000Z | src/Point_ClosedOrbitCheby.cc | PaulMcMillan-Astro/TorusLight | 4a08998a5cc918b369414437ae8df109d7a926ee | [
"MIT"
] | null | null | null | src/Point_ClosedOrbitCheby.cc | PaulMcMillan-Astro/TorusLight | 4a08998a5cc918b369414437ae8df109d7a926ee | [
"MIT"
] | null | null | null |
/*
*
* C++ code written by Paul McMillan, 2008 *
* e-mail: paul@astro.lu.se *
* github: https://github.com/PaulMcMillan-Astro/Torus *
*/
#include "Point_ClosedOrbitCheby.h"
#include "PJMNum.h"
#include "Orb.h"
// Routine needed for external integration routines ----------------------------
double PoiClosedOrbit::actint(double theta) const {
double psi = asin(theta/thmaxforactint);
double tmp = vr2.unfit1(psi) * drdth2.unfit1(psi) + pth2.unfit1(psi*psi);
return tmp;
}
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// function: do_orbit - Integrates an orbit from z=0 upwards and back to z=0
// Tabulates coordinates in between.
void PoiClosedOrbit::do_orbit(PSPD clo, double delt, Potential* Phi,
double* time, double* tbR, double* tbz,
double* tbr, double* tbvr, double* tbpth,
double* tbdrdth, int &np, int Nt, double &zmax)
{
double dt, ot,t=0.;
zmax = 0.;
Record X(clo,Phi,1.e-12);
X.set_maxstep(delt);
PSPD W = clo;
dt = delt;
for(np=0; np!=Nt && W(1)*X.QP(1) > 0;np++) {
ot = t;
W = X.QP();
do {
X.stepRK_by(dt);
t += dt;
} while(t-ot < delt);
time[np] = t;
tbR[np] = X.QP(0);
tbz[np] = X.QP(1);
if( X.QP(1) > zmax ) zmax = X.QP(1);
tbr[np] = hypot(X.QP(0),X.QP(1));
tbvr[np] = (X.QP(0)*X.QP(2) + X.QP(1)*X.QP(3))/tbr[np];
tbpth[np] = X.QP(0)*X.QP(3) - X.QP(1)*X.QP(2);
tbdrdth[np]= tbr[np]*tbr[np]*tbvr[np]/tbpth[np];
}
}
////////////////////////////////////////////////////////////////////////////////
// function: set_Rstart - iterates towards correct Rstart for given energy (E)
void PoiClosedOrbit::set_Rstart(double& Rstart,double Rstop, double& odiff,
double& dr, double zmax,
bool& done, bool& either_side, bool& first)
{
double diff, small =1.e-6, smallish = 1.e-4;
double criterion = (smallish*zmax<small*Rstart) ? smallish*zmax : small*Rstart;
if(fabs(diff=Rstart-Rstop) < criterion) done = true;
else done = false;
if(either_side && !done) {
if(diff*odiff>0.) dr *= 0.5;
else dr *=-0.5;
odiff = diff;
} else if(first && !done) {
odiff = diff;
first=false;
} else if(diff*odiff < 0. && !done) {
either_side = true;
odiff = diff;
dr *= -0.5;
} else if(fabs(diff) > fabs(odiff) && !done) {
dr *= -1.;
Rstart += dr;
}
if(!done) Rstart += dr;
}
////////////////////////////////////////////////////////////////////////////////
// function: set_E - iterates towards correct energy (E) for given J_l
void PoiClosedOrbit::set_E(const double tJl,double& odiffJ,double& E,
double& dE, bool& done,bool& es_Jl,bool& firstE)
{
double diffJ;
if(fabs(diffJ=tJl-Jl)>0.0005*Jl) done = false;
if(es_Jl && !done) {
if(diffJ*odiffJ>0.) dE *= 0.5;
else dE *=-0.5;
odiffJ = diffJ;
} else if(firstE && !done) {
odiffJ = diffJ;
firstE=false;
} else if(diffJ*odiffJ < 0. && !done) {
es_Jl = true;
odiffJ = diffJ;
dE *= -0.5;
} else if(fabs(diffJ) > fabs(odiffJ) && !done) {
dE *= -1.;
E += dE;
}
if(!done) E = (E+dE<0.)? E+dE : 0.95*E;
}
////////////////////////////////////////////////////////////////////////////////
// RewriteTables - organise so we have only the upwards movement, to thmax
void PoiClosedOrbit::RewriteTables(const int n, double *time, double *tbR,double *tbz,
double *tbr, double *tbvr, double *tbpth,
double *tbir, double *tbth, int &imax)
{
int klo,khi;
double tmax,rmax;
thmax=0.;
for(int i=0;i!=n;i++) {
tbth[i] = atan2(tbz[i],tbR[i]);
if(tbth[i] > thmax) {
imax=i; thmax=tbth[i];
}
}
klo = (tbpth[imax] > 0.)? imax : imax-1;
khi = klo + 1;
// Estimate maximum th, and r at that point, assuming ~const acceleration
tmax=(time[klo]*tbpth[khi]-time[khi]*tbpth[klo])/(tbpth[khi]-tbpth[klo]);
thmax=tbth[klo]+(tbpth[klo] + .5*(tbpth[khi]-tbpth[klo])*(tmax-time[klo])
/(time[khi]-time[klo]))*(tmax-time[klo])/pow(.5*(tbr[khi]+tbr[klo]),2);
rmax=tbr[klo]+(tbvr[klo]+.5*(tbvr[khi]-tbvr[klo])*(tmax-time[klo])
/(time[khi]-time[klo]))*(tmax-time[klo]);
imax = khi;
omz = Pih/tmax; // Frequency of vertical oscillation
tbth[imax] = thmax;
tbpth[imax] = 0.;
tbvr[imax] = 0.;
tbr[imax] = rmax;
imax++;
for(int i=0;i!=imax;i++) tbir[i] = 1./tbr[i];
}
////////////////////////////////////////////////////////////////////////////////
// chebderivs - returns dy/dth and dz/dth using Chebyshev fits to the orbit
vec2 PoiClosedOrbit::chebderivs(const double psi, const vec2 yz) {
double t = thmax * sin(psi), t0 = yz[0]*yz[1], ptho,
tvr,tdrdth,tpth,tiny=1.e-20,tmp,tmp2;
vec2 dyzdt;
tvr = vr2.unfit1(psi);
tdrdth = drdth2.unfit1(psi);
tpth = pth2.unfit1(psi*psi);
if(psi == 0.) tdrdth = 0.; // symmetry, should be firmly stated
tmp2 = cos(t0);
tmp = alt2-Lz*Lz/(tmp2*tmp2);
ptho = (tmp>tiny)? sqrt(tmp) : sqrt(tiny);
tmp = (yz[1]>tiny)? yz[1] : tiny;
dyzdt[0] = tvr*tdrdth/(tmp*ptho) * thmax*cos(psi);
dyzdt[1] = tpth/(yz[0]*ptho) * thmax*cos(psi);
return dyzdt;
}
////////////////////////////////////////////////////////////////////////////////
// stepper - take a Runge-Kutta step in y and z, return uncertainty
double PoiClosedOrbit::stepper(vec2 &tyz,vec2 &dyzdt,const double psi,const double h)
{
double hh=h*0.5, psihh=psi+hh;
vec2 tmpyz, k2, tmpyz2, k2b, tmpyz3;
tmpyz = tyz + hh*dyzdt;
k2 = chebderivs(psihh, tmpyz);
tmpyz = tyz + h*k2;
// Try doing that twice:
tmpyz2 = tyz + 0.25*h*dyzdt;
k2b = chebderivs(psi+0.25*h, tmpyz2);
tmpyz2 = tyz+ 0.5*h*k2b;
k2b = chebderivs(psi+0.5*h, tmpyz2);
tmpyz3 = tmpyz2 + 0.25*h*k2b;
k2b = chebderivs(psi+0.75*h, tmpyz3);
tyz = tmpyz2+ 0.5*h*k2b;
double err0 = fabs(tyz[0]-tmpyz[0])*0.15,
err1 = fabs(tyz[1]-tmpyz[1])*0.15; // error estimates (as O(h^3))
tyz = tmpyz;
return (err0>err1)? err0 : err1;
}
////////////////////////////////////////////////////////////////////////////////
// yzrkstep - take a RK step in y & z, step size determined by uncertainty.
void PoiClosedOrbit::yzrkstep(vec2 &yz, vec2 &dyzdt, const double tol, double& psi,
const double h0, double& hnext, const double hmin,
const double hmax) {
bool done=false;
double err,fac =1.4, fac3=pow(fac,3), h=h0;
vec2 tmpyz;
do {
tmpyz = yz;
err = stepper(tmpyz,dyzdt,psi,h);
if(err*fac3<tol && h*fac<hmax) h*=fac;
else done = true;
} while(!done);
while(err>tol && h>hmin) {
h /=fac;
if(h<hmin) h=hmin;
tmpyz = yz;
err = stepper(tmpyz,dyzdt,psi,h);
}
psi += h;
yz = tmpyz;
hnext=h;
}
////////////////////////////////////////////////////////////////////////////////
// yfn - Interpolate to return y(th) or z(th) for given th=t
double PoiClosedOrbit::yfn(double t, vec2 * ys,const int which,double * thet, int n)
{
int klo=0,khi=n-1,k;
while(khi-klo > 1) {
k=(khi+klo)/2;
if(thet[k]>t) khi = k;
else klo = k;
}
double h = thet[khi] - thet[klo];
if(h==0.) cerr << "bad theta input to yfn: klo= "<<klo<<" khi= "<< khi<<"\n";
double a = (thet[khi] - t), b = (t - thet[klo]);
return (a*ys[klo][which] + b*ys[khi][which])/h;
}
////////////////////////////////////////////////////////////////////////////////
// Find point transform suitable for given potential and Actions
////////////////////////////////////////////////////////////////////////////////
void PoiClosedOrbit::set_parameters(Potential *Phi, const Actions J) {
Jl = J(1);
Lz = fabs(J(2));
alt2=(fabs(Lz)+Jl)*(fabs(Lz)+Jl);
Phi->set_Lz(Lz);
if(Jl<=0.) {
cerr << "PoiClosedOrbit called for Jl <= 0. Not possible.\n";
return;
}
bool first=true,firstE=true, either_side=false, es_Jl=false, done=false;
int Nt=1024,np=0,norb=0,nE=0,nEmax = 50000,imax, NCheb=10;
double time[Nt], tbR[Nt], tbz[Nt], tbr[Nt], tbvr[Nt], tbpth[Nt], tbdrdth[Nt],
tbir[Nt],tbth[Nt]; // tables from orbit integration
// Could improve - starting radius should be guessed from Jz+Jphi
double Rstart0 = Phi->RfromLc(Lz), Rstart = Rstart0, dr=0.1*Rstart, Rstop,
E = Phi->eff(Rstart,0.), dE, tiny=1.e-9, small=1.e-5, odiff,odiffJ,
delt=0.002*Rstart*Rstart/Lz, dt,ot,pot, tJl, *psi, *psisq, *tbth2,
Escale = Phi->eff(2.*Rstart,0.)-E, // positive number
zmax;
PSPD clo;
Cheby rr2;
E += tiny*Escale;
dE = 0.08*Escale;
// For any given Jl, we do not know the corresponding closed orbit, and
// don't even know any point on it. Therefore we have to start by guessing
// an energy (E) and iterate to the correct value. Furthermore, for any
// given E, we don't actually know the closed orbit, so we have to guess a
// starting point, then integrate the orbit and use that to improve our
// guess
for(nE=0;!done && nE!=nEmax;nE++) { // iterate energy
for(norb=0;norb!=200 && !done;norb++) { // for each energy, iterate start R
while((pot=Phi->eff(Rstart,tiny))>=E) {// avoid unphysical starting points
if(first) Rstart += 0.5*(Rstart0-Rstart);
else Rstart = 0.01*clo[0] + 0.99*Rstart; // if use mean -> closed loop
}
clo[0] = Rstart; clo[1] = tiny; // clo = starting point
clo[2] = 0.; clo[3] = sqrt(2.*(E-pot));
do { // integrate orbit (with enough datapoints)
delt= (np==Nt)? delt*2 : (np<0.25*Nt &&np)? delt*.9*np/double(Nt):delt;
do_orbit(clo,delt,Phi,time,tbR,tbz,tbr,tbvr,tbpth,tbdrdth,np,Nt,zmax);
} while(np==Nt || np < Nt/4);
Rstop = tbR[np-2]-tbz[np-2]/(tbz[np-1]-tbz[np-2])*(tbR[np-1]-tbR[np-2]);
set_Rstart(Rstart,Rstop,odiff,dr,zmax,done,either_side,first);//pick new Rstart
norb++;
} // end iteration in Rstart
// clean up tables of values
RewriteTables(np, time,tbR,tbz,tbr,tbvr,tbpth,tbir, tbth, imax);
// find Jl, having set up chebyshev functions to do so.
psi = new double[imax];
psisq = new double[imax];
tbth2 = new double[imax];
for(int i=0; i!=imax; i++){
tbth2[i] = tbth[i]*tbth[i];
psi[i] = (tbth[i] >= thmax)? Pih : asin(tbth[i]/thmax);
psisq[i] = psi[i] * psi[i];
}
drdth2.chebyfit(psi,tbdrdth,imax-2,NCheb);
vr2.chebyfit (psi, tbvr, imax,NCheb);
pth2.chebyfit (psisq,tbpth,imax,NCheb);
thmaxforactint = thmax;
//tJl = 2.*qromb(&actint,0,thmax)/Pi; // Find Jl
tJl = 2.*qromb(this,&PoiClosedOrbit::actint,0,thmax)/Pi;
set_E(tJl,odiffJ,E,dE,done,es_Jl,firstE); // pick new E
if(!done && nE!=nEmax-1) { delete[] psi; delete[] psisq; delete[] tbth2; }
dr=0.1*Rstart;
first = true;
either_side = false;
} // end iterative loop
for(int i=0; i!=imax; i++) tbth2[i] = tbth[i]*tbth[i];
xa.chebyfit (tbth2, tbir, imax, NCheb); // x
rr2.chebyfit (tbth2, tbr, imax, NCheb);
double thmax2 = acos(sqrt(Lz*Lz/alt2));
int many=100000;
double tpsi,*thet;
vec2 *yzfull,yz,dyzdt;
thet = new double[many];
yzfull= new vec2[many];
yz[0] = 1.; yz[1] = 0.; tpsi = 0;
dyzdt = chebderivs(tpsi,yz);
int np2, nr=15;
double tol=2.e-10, h0=5.e-4,hnext=h0,tmp=0.;
for(np2=0;tmp<0.99*thmax && yz[0]*yz[1]<0.99*thmax2&& np2!=many;np2++) {
h0 = (hnext<0.002)? hnext : 0.002;
yzrkstep(yz,dyzdt,tol,tpsi,h0,hnext,1.e-8,2.e-3);
tmp = thmax*sin(tpsi);
thet[np2] = tmp;
yzfull[np2][0] = yz[0];
yzfull[np2][1] = yz[1];
dyzdt = chebderivs(tpsi,yz);
}
double rr[nr], yy[nr];
rr[0] = 0.;
yy[0] = 1.;
for(int i=1;i!=nr-1;i++) { // this nr is new and ~15
double tmpth = sqrt((i-1)/double(nr-2))*thmax;
rr[i] = rr2.unfit1(tmpth*tmpth); // possibly unfitn
yy[i] = yfn(tmpth,yzfull,0,thet,np2);
}
rr[nr-1] = 2*rr[nr-2];
yy[nr-1] = yy[nr-2];
int NCheb2 = 2*NCheb;
ya.chebyfit(rr,yy,nr,NCheb2);
//double outyz[nr];
//ya.unfitn(rr,outyz,nr);
//PJMplot2 graph(rr,yy,nr,rr,outyz,nr);
//graph.plot();
// extend zz to all theta<pi/2 and fit to theta*(apoly in theta**2)
double tmpth2[nr], zz[nr];
for(int i=0;i!=nr;i++) {
tmpth2[i] = (i+1.)/double(nr)*thmax*thmax;
tmp = sqrt(tmpth2[i]);
zz[i] = yfn(tmp,yzfull,1,thet,np2)/tmp;
}
za.chebyfit(tmpth2,zz,nr,NCheb); // note that this is in fact z/theta.
//za.unfitn(tmpth2,outyz,nr);
//graph.putvalues(tmpth2,zz,nr,tmpth2,outyz,nr);
//graph.findlimits();
//graph.plot();
double x1 = thmax*thmax, x2=Pih*Pih, y1x, dy1x, y1z, dy1z, delx = x2-x1;
xa.unfitderiv(x1,y1x,dy1x);
za.unfitderiv(x1,y1z,dy1z);
// define coefficients such that quadratic goes through final point and
// has correct gradient at that point. Then take same values of xa and za
// at th = pi/2
ax = -dy1x/delx;
bx = dy1x-2*ax*x1;
cx = y1x - x1*(ax*x1 + bx);
az = -dy1z/delx;
bz = dy1z-2*az*x1;
cz = y1z - x1*(az*x1 + bz);
delete[] psi;
delete[] psisq;
delete[] tbth2;
delete[] thet;
delete[] yzfull;
}
// various numbers needed for Derivatives()
double R,z,r,th,th2,ir,costh,sinth,pr,pth,xpp,ypp,zpp,dx,dy,dz,d2x,d2y,d2z,
rt,tht,prt,ptht;
double drtdr, drtdth, dthtdr, dthtdth;
double dthdtht, dthdrt, drdtht, drdrt;
PoiClosedOrbit::PoiClosedOrbit(const double* param) {
set_parameters(param);
}
void PoiClosedOrbit::set_parameters(const double* param) {
int ncx,ncy,ncz;
Jl = param[0]; Lz = param[1]; thmax = param[2]; omz = param[3];
ncx = int(param[4]);
double chx[ncx];
for(int i=0;i!=ncx;i++) chx[i] = param[5+i];
ncy = int(param[5+ncx]);
double chy[ncy];
for(int i=0;i!=ncy;i++) chy[i] = param[6+ncx+i];
ncz = int(param[6+ncx+ncy]);
double chz[ncz];
for(int i=0;i!=ncz;i++) chz[i] = param[7+ncx+ncy+i];
xa.setcoeffs(chx,ncx);
ya.setcoeffs(chy,ncy);
za.setcoeffs(chz,ncz);
double x1 = thmax*thmax, x2=Pih*Pih, y1x, dy1x, y1z, dy1z, delx = x2-x1;
xa.unfitderiv(x1,y1x,dy1x);
za.unfitderiv(x1,y1z,dy1z);
// define coeeficients such that quadratic goes through final point and
// has correct gradient at that point. Then take same values of xa and za
// at th = pi/2
ax = -dy1x/delx;
bx = dy1x-2*ax*x1;
cx = y1x - x1*(ax*x1 + bx);
az = -dy1z/delx;
bz = dy1z-2*az*x1;
cz = y1z - x1*(az*x1 + bz);
}
PoiClosedOrbit::PoiClosedOrbit(Actions J, Cheby ch1, Cheby ch2, Cheby ch3,
double tmx, double om) {
set_parameters(J,ch1,ch2,ch3,tmx,om);
}
PoiClosedOrbit::PoiClosedOrbit() {}
///////////////////////////////////////////////////////////////////////////////
PoiClosedOrbit::PoiClosedOrbit(Potential *Phi, const Actions J) {
set_parameters(Phi,J);
}
/*/////////////////////////////////////////////////////////////////////////////
* *
* The actual transforms *
* *
/////////////////////////////////////////////////////////////////////////////*/
PSPD PoiClosedOrbit::Forward (const PSPD &qp) const
{
//first convert from toy coords to real
// first guess, th = th^T
th = qp(1);
th2 = th*th;
// then use r^T = x(th)*r
if(fabs(th)<=thmax) xa.unfitderiv(th2,xpp,dx,d2x);
else {
xpp = (ax*th2+bx)*th2+cx;
dx = 2*ax*th2+bx;
d2x= 2*ax;
}
double ixpp = 1./xpp;
dx = 2*th*dx;
r = qp(0)*ixpp;
ya.unfitderiv(r,ypp,dy,d2y);
if(fabs(th)<=thmax) za.unfitderiv(th2,zpp,dz,d2z);
else {
zpp = (az*th2+bz)*th2+cz;
dz = 2*az*th2+bz;
d2z= 2*az;
}
dz = zpp + 2.*th2*dz;
zpp = zpp*th;
double tmptht = ypp*zpp;
int tmpint=0;
do {
tmpint++;
dthtdth = ypp*dz - zpp*dy*r*ixpp*dx; // note not holding usual constants
th += (qp(1)-tmptht)/dthtdth;
th2 = th*th;
// then use r^T = x(th)*r
if(fabs(th)<=thmax) xa.unfitderiv(th2,xpp,dx,d2x);
else {
xpp = (ax*th2+bx)*th2+cx;
dx = 2*ax*th2+bx;
d2x= 2*ax;
}
double ixpp = 1./xpp;
d2x = 2*dx+4*th2*d2x; // because given is d/dth2
dx = 2*th*dx;
r = qp(0)*ixpp;
ya.unfitderiv(r,ypp,dy,d2y);
if(fabs(th)<=thmax) za.unfitderiv(th2,zpp,dz,d2z);
else {
zpp = (az*th2+bz)*th2+cz;
dz = 2*az*th2+bz;
d2z= 2*az;
}
d2z = th*(6.*dz + 4*th2*d2z); // because given is d(z/th)/dth2
dz = zpp + 2.*th2*dz;
zpp = zpp*th;
tmptht = ypp*zpp;
}while(fabs(tmptht-qp(1))>0.00000001 && tmpint<100);
costh = cos(th); sinth = sin(th); ir = 1./r;
drtdr = xpp; drtdth = r*dx; dthtdr = dy*zpp; dthtdth = ypp*dz;
rt = qp(0); tht = qp(1); prt = qp(2); ptht = qp(3);
pr = drtdr*prt + dthtdr*ptht; pth = drtdth*prt + dthtdth*ptht;
double idet = 1./(dthtdth*drtdr-drtdth*dthtdr);
dthdtht = drtdr*idet; dthdrt = -dthtdr*idet; drdtht=-drtdth*idet;
drdrt = dthtdth*idet; // needed by Derivatives()
// last convert from rth to Rz
R = r*costh;
z = r*sinth;
double pR = costh*pr - sinth*ir*pth;
double pz = sinth*pr + costh*ir*pth;
PSPD QP(R,z,pR,pz);
return QP;
}
PSPD PoiClosedOrbit::Backward (const PSPD &QP) const
{
PSPD qp;
R=QP(0); z=QP(1); r=hypot(QP(0),QP(1)); th=atan2(QP(1),QP(0));
double th2=th*th;
ir=1./r; costh=QP(0)*ir; sinth=QP(1)*ir;
pr=QP(2)*costh+QP(3)*sinth; pth=-QP(2)*QP(1)+QP(3)*QP(0);
if(fabs(th)<=thmax) xa.unfitderiv(th2,xpp,dx,d2x);
else {
xpp = (ax*th2+bx)*th2+cx;
dx = 2*ax*th2+bx;
d2x= 2*ax;
}
ya.unfitderiv(r,ypp,dy,d2y);
if(fabs(th)<=thmax) za.unfitderiv(th2,zpp,dz,d2z);
else {
zpp = (az*th2+bz)*th2+cz;
dz = 2*az*th2+bz;
d2z= 2*az;
}
d2x = 2*dx+4*th2*d2x; // because given is d/dth2
dx = 2*th*dx;
d2z = th*(6.*dz + 4*th2*d2z); // given is z/th and d/dth2
dz = zpp + 2.*th2*dz;
zpp = zpp*th;
rt = r * xpp;
tht = ypp * zpp;
qp[0] = rt;
qp[1] = tht;
// unfortunately getting p(r,th)^T is harder. Need to know
// d(r,th)/d(r,th)^t, but can only find inverses directly.
drtdr = xpp; drtdth = r*dx; dthtdr = dy*zpp; dthtdth = ypp*dz;
double idet = 1./(dthtdth*drtdr-drtdth*dthtdr);
dthdtht = drtdr*idet; dthdrt = -dthtdr*idet; drdtht=-drtdth*idet;
drdrt = dthtdth*idet;
prt = pr*drdrt+pth*dthdrt;
ptht = pr*drdtht+pth*dthdtht;
qp[2] = prt;
qp[3] = ptht;
return qp;
}
////////////////////////////////////////////////////////////////////////////////
PSPT PoiClosedOrbit::Forward3D(const PSPT& w3) const
{
PSPT W3 = w3;
PSPD w2 = w3.Give_PSPD();
W3.Take_PSPD(Forward(w2));
W3[5] /= W3(0); // p_phi^T -> v_phi
return W3;
}
////////////////////////////////////////////////////////////////////////////////
PSPT PoiClosedOrbit::Backward3D(const PSPT& W3) const
{
PSPT w3 = W3;
PSPD W2 = W3.Give_PSPD();
w3.Take_PSPD(Backward(W2));
w3[5] *= W3(0); // correct because this is v_phi, not p_phi
return w3;
}
////////////////////////////////////////////////////////////////////////////////
void PoiClosedOrbit::Derivatives(double dQPdqp[4][4]) const {
double dpRdr = pth*sinth*ir*ir, dpRdth = -pr*sinth-pth*costh*ir,
dpRdpr = costh, dpRdpth = -sinth*ir,
dpzdr = -costh*ir*ir*pth, dpzdth = costh*pr+-sinth*ir*pth,
dpzdpr = sinth, dpzdpth = costh*ir;//, dQPdqp[4][4];
double d2rtdr2 = 0., d2rtdrdth = dx, d2rtdth2 = r*d2x,
d2thtdr2 = d2y*zpp, d2thtdrdth = dy*dz, d2thtdth2 = ypp*d2z;
double dprdrt = (d2rtdr2*drdrt + d2rtdrdth*dthdrt)*prt +
(d2thtdr2*drdrt + d2thtdrdth*dthdrt)*ptht,
dprdtht = (d2rtdr2*drdtht + d2rtdrdth*dthdtht)*prt +
(d2thtdr2*drdtht + d2thtdrdth*dthdtht)*ptht,
dprdprt = drtdr, dprdptht = dthtdr;
double dpthdrt = (d2rtdrdth*drdrt + d2rtdth2*dthdrt)*prt +
(d2thtdrdth*drdrt + d2thtdth2*dthdrt)*ptht,
dpthdtht = (d2rtdrdth*drdtht + d2rtdth2*dthdtht)*prt +
(d2thtdrdth*drdtht + d2thtdth2*dthdtht)*ptht,
dpthdprt = drtdth, dpthdptht = dthtdth;
dQPdqp[0][0] = costh*drdrt - z*dthdrt; //dR/dr*dr/drt + dR/dth*dth/drt
dQPdqp[0][1] = costh*drdtht - z*dthdtht; //dR/dr*dr/dtht + dR/dth*dth/dtht
dQPdqp[0][2] = 0.;
dQPdqp[0][3] = 0.;
dQPdqp[1][0] = sinth*drdrt + R*dthdrt; //dz/dr*dr/drt + dz/dth*dth/drt
dQPdqp[1][1] = sinth*drdtht + R*dthdtht; //dz/dr*dr/dtht + dz/dth*dth/dtht
dQPdqp[1][2] = 0.;
dQPdqp[1][3] = 0.;
dQPdqp[2][0] = dpRdr*drdrt + dpRdth*dthdrt + dpRdpr*dprdrt + dpRdpth*dpthdrt;
dQPdqp[2][1] = dpRdr*drdtht+ dpRdth*dthdtht+ dpRdpr*dprdtht+ dpRdpth*dpthdtht;
dQPdqp[2][2] = dpRdpr*dprdprt+ dpRdpth*dpthdprt;
dQPdqp[2][3] = dpRdpr*dprdptht+dpRdpth*dpthdptht;
dQPdqp[3][0] = dpzdr*drdrt + dpzdth*dthdrt + dpzdpr*dprdrt + dpzdpth*dpthdrt;
dQPdqp[3][1] = dpzdr*drdtht+ dpzdth*dthdtht+ dpzdpr*dprdtht+ dpzdpth*dpthdtht;
dQPdqp[3][2] = dpzdpr*dprdprt+ dpzdpth*dpthdprt;
dQPdqp[3][3] = dpzdpr*dprdptht+dpzdpth*dpthdptht;
}
| 32.826833 | 86 | 0.552134 | PaulMcMillan-Astro |
520e4a33f04febe48668f2cbfdc7fa5fe00aaa6a | 5,217 | cpp | C++ | Oem/dbxml/xqilla/src/functions/FunctionId.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Oem/dbxml/xqilla/src/functions/FunctionId.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Oem/dbxml/xqilla/src/functions/FunctionId.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | /*
* Copyright (c) 2001-2008
* DecisionSoft Limited. All rights reserved.
* Copyright (c) 2004-2008
* Oracle. 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.
*
* $Id$
*/
#include "../config/xqilla_config.h"
#include <xqilla/functions/FunctionId.hpp>
#include <xqilla/context/DynamicContext.hpp>
#include <xqilla/exceptions/FunctionException.hpp>
#include <xqilla/utils/XPath2Utils.hpp>
#include <xqilla/items/Node.hpp>
#include <xqilla/ast/StaticAnalysis.hpp>
#include <xqilla/items/DatatypeFactory.hpp>
const XMLCh FunctionId::name[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_d, XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
const unsigned int FunctionId::minArgs = 1;
const unsigned int FunctionId::maxArgs = 2;
/**
* fn:id($arg as xs:string*) as element()*
* fn:id($arg as xs:string*, $node as node()) as element()*
**/
FunctionId::FunctionId(const VectorOfASTNodes &args, XPath2MemoryManager* memMgr)
: XQFunction(name, minArgs, maxArgs, "string*, node()", args, memMgr)
{
}
ASTNode* FunctionId::staticResolution(StaticContext *context) {
if(_args.size()==2 && _args.back()->getType()==ASTNode::CONTEXT_ITEM)
_args.pop_back();
return resolveArguments(context);
}
ASTNode *FunctionId::staticTypingImpl(StaticContext *context)
{
_src.clear();
_src.getStaticType() = StaticType(StaticType::ELEMENT_TYPE, 0, StaticType::UNLIMITED);
if(_args.size()==1)
_src.contextItemUsed(true);
return calculateSRCForArguments(context);
}
Sequence FunctionId::createSequence(DynamicContext* context, int flags) const
{
Node::Ptr ctxNode;
if(getNumArgs() == 2)
{
Sequence arg=getParamNumber(2,context)->toSequence(context);
ctxNode=arg.first();
}
else
{
const Item::Ptr item = context->getContextItem();
if(item==NULLRCP)
XQThrow(FunctionException, X("FunctionId::createSequence"),X("Undefined context item in fn:id [err:XPDY0002]"));
if(!item->isNode())
XQThrow(FunctionException, X("FunctionId::createSequence"),X("The context item is not a node [err:XPTY0004]"));
ctxNode=item;
}
Node::Ptr root = ctxNode->root(context);
if(root->dmNodeKind() != Node::document_string) {
XQThrow(FunctionException,X("FunctionId::createSequence"), X("Current context doesn't belong to a document [err:FODC0001]"));
}
Sequence strings = getParamNumber(1, context)->toSequence(context);
if(strings.isEmpty())
return Sequence(context->getMemoryManager());
std::vector<const XMLCh*> values;
//get the list of id values we're looking for by iterating over each string in the sequence
for (Sequence::iterator stringIt = strings.begin(); stringIt != strings.end(); ++stringIt) {
const XMLCh *str = (*stringIt)->asString(context);
std::vector<const XMLCh*> idList = XPath2Utils::getVal(str, context->getMemoryManager());
//for each list obtained from a string check that each id is unique to the full list and if so add it
for (std::vector<const XMLCh*>::iterator listIt=idList.begin(); listIt!=idList.end(); ++listIt) {
if (!XPath2Utils::containsString(values, *listIt))
values.push_back(*listIt);
}
}
Sequence result(context->getMemoryManager());
std::vector<const XMLCh*> returnedVals;
std::vector<Result> resultStack;
resultStack.push_back(root->dmChildren(context, this));
Node::Ptr child = resultStack.back()->next(context);
while(child.notNull()) {
if(child->dmNodeKind() == Node::element_string) {
bool added = false;
if(child->dmIsId(context)->isTrue()) {
// child is of type xs:ID
const XMLCh* id = child->dmStringValue(context);
if(XPath2Utils::containsString(values, id) &&
!XPath2Utils::containsString(returnedVals, id)) {
returnedVals.push_back(id);
result.addItem(child);
added = true;
}
}
if(!added) {
Result attrs = child->dmAttributes(context, this);
Node::Ptr att;
while((att = (Node::Ptr)attrs->next(context)).notNull()) {
if(att->dmIsId(context)->isTrue()) {
// att is of type xs:ID
const XMLCh* id = att->dmStringValue(context);
if(XPath2Utils::containsString(values, id) &&
!XPath2Utils::containsString(returnedVals, id)) {
returnedVals.push_back(id);
result.addItem(child);
break;
}
}
}
}
}
resultStack.push_back(child->dmChildren(context, this));
while(!resultStack.empty() && (child = resultStack.back()->next(context)).isNull()) {
resultStack.pop_back();
}
}
return result;
}
| 34.322368 | 129 | 0.676634 | achilex |
52127d9558484f9d16631508c3f8ca167a12b651 | 11,685 | cpp | C++ | main.cpp | tsoding/kkona | 1957ce783d61490940a681abe1c904f3a7331690 | [
"MIT"
] | 5 | 2020-04-05T18:56:20.000Z | 2020-04-13T05:44:02.000Z | main.cpp | tsoding/kkona | 1957ce783d61490940a681abe1c904f3a7331690 | [
"MIT"
] | null | null | null | main.cpp | tsoding/kkona | 1957ce783d61490940a681abe1c904f3a7331690 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <SDL.h>
#include <png.h>
template <typename T>
struct Rect
{
T x, y, w, h;
};
using Rectf = Rect<float>;
SDL_Rect rectf_for_sdl(Rectf rect)
{
return {(int) floorf(rect.x),
(int) floorf(rect.y),
(int) floorf(rect.w),
(int) floorf(rect.h)};
}
template <typename T>
struct Vec2
{
T x, y;
};
using Vec2f = Vec2<float>;
template <typename T> Vec2<T> vec2(T x, T y) { return {x, y}; }
template <typename T> Vec2<T> constexpr operator+(Vec2<T> a, Vec2<T> b) { return {a.x + b.x, a.y + b.y}; }
template <typename T> Vec2<T> constexpr operator*(Vec2<T> a, Vec2<T> b) { return {a.x * b.x, a.y * b.y}; }
template <typename T> Vec2<T> constexpr operator*(Vec2<T> a, T b) { return {a.x * b, a.y * b}; }
template <typename T> Vec2<T> constexpr &operator+=(Vec2<T> &a, Vec2<T> b) { a = a + b; return a; }
void sec(int code)
{
if (code < 0) {
fprintf(stderr, "SDL pooped itself: %s\n", SDL_GetError());
abort();
}
}
template <typename T>
T *sec(T *ptr)
{
if (ptr == nullptr) {
fprintf(stderr, "SDL pooped itself: %s\n", SDL_GetError());
abort();
}
return ptr;
}
struct Sprite
{
SDL_Rect srcrect;
SDL_Texture *texture;
};
void render_sprite(SDL_Renderer *renderer,
Sprite texture,
Rectf destrect,
SDL_RendererFlip flip = SDL_FLIP_NONE)
{
SDL_Rect rect = rectf_for_sdl(destrect);
sec(SDL_RenderCopyEx(
renderer,
texture.texture,
&texture.srcrect,
&rect,
0.0,
nullptr,
flip));
}
SDL_Surface *load_png_file_as_surface(const char *image_filename)
{
png_image image;
memset(&image, 0, sizeof(image));
image.version = PNG_IMAGE_VERSION;
if (!png_image_begin_read_from_file(&image, image_filename)) {
fprintf(stderr, "Could not read file `%s`: %s\n", image_filename, image.message);
abort();
}
image.format = PNG_FORMAT_RGBA;
uint32_t *image_pixels = new uint32_t[image.width * image.height];
if (!png_image_finish_read(&image, nullptr, image_pixels, 0, nullptr)) {
fprintf(stderr, "libpng pooped itself: %s\n", image.message);
abort();
}
SDL_Surface* image_surface =
sec(SDL_CreateRGBSurfaceFrom(image_pixels,
(int) image.width,
(int) image.height,
32,
(int) image.width * 4,
0x000000FF,
0x0000FF00,
0x00FF0000,
0xFF000000));
return image_surface;
}
SDL_Texture *load_texture_from_png_file(SDL_Renderer *renderer,
const char *image_filename)
{
SDL_Surface *image_surface =
load_png_file_as_surface(image_filename);
SDL_Texture *image_texture =
sec(SDL_CreateTextureFromSurface(renderer,
image_surface));
SDL_FreeSurface(image_surface);
return image_texture;
}
Sprite load_png_file_as_sprite(SDL_Renderer *renderer, const char *image_filename)
{
Sprite sprite = {};
sprite.texture = load_texture_from_png_file(renderer, image_filename);
sec(SDL_QueryTexture(sprite.texture, NULL, NULL, &sprite.srcrect.w, &sprite.srcrect.h));
return sprite;
}
struct Sample_S16
{
int16_t* audio_buf;
Uint32 audio_len;
Uint32 audio_cur;
};
const size_t SAMPLE_MIXER_CAPACITY = 5;
struct Sample_Mixer
{
float volume;
Sample_S16 samples[SAMPLE_MIXER_CAPACITY];
void play_sample(Sample_S16 sample)
{
for (size_t i = 0; i < SAMPLE_MIXER_CAPACITY; ++i) {
if (samples[i].audio_cur >= samples[i].audio_len) {
samples[i] = sample;
samples[i].audio_cur = 0;
return;
}
}
}
};
const size_t SOMETHING_SOUND_FREQ = 48000;
const size_t SOMETHING_SOUND_FORMAT = 32784;
const size_t SOMETHING_SOUND_CHANNELS = 1;
const size_t SOMETHING_SOUND_SAMPLES = 4096;
Sample_S16 load_wav_as_sample_s16(const char *file_path)
{
Sample_S16 sample = {};
SDL_AudioSpec want = {};
if (SDL_LoadWAV(file_path, &want, (Uint8**) &sample.audio_buf, &sample.audio_len) == nullptr) {
fprintf(stderr, "SDL pooped itself: Failed to load %s: %s\n",
file_path, SDL_GetError());
abort();
}
assert(SDL_AUDIO_BITSIZE(want.format) == 16);
assert(SDL_AUDIO_ISLITTLEENDIAN(want.format));
assert(SDL_AUDIO_ISSIGNED(want.format));
assert(SDL_AUDIO_ISINT(want.format));
assert(want.freq == SOMETHING_SOUND_FREQ);
assert(want.channels == SOMETHING_SOUND_CHANNELS);
assert(want.samples == SOMETHING_SOUND_SAMPLES);
sample.audio_len /= 2;
return sample;
}
void sample_mixer_audio_callback(void *userdata, Uint8 *stream, int len)
{
Sample_Mixer *mixer = (Sample_Mixer *)userdata;
int16_t *output = (int16_t *)stream;
size_t output_len = (size_t) len / sizeof(*output);
memset(stream, 0, (size_t) len);
for (size_t i = 0; i < SAMPLE_MIXER_CAPACITY; ++i) {
for (size_t j = 0; j < output_len; ++j) {
int16_t x = 0;
if (mixer->samples[i].audio_cur < mixer->samples[i].audio_len) {
x = mixer->samples[i].audio_buf[mixer->samples[i].audio_cur];
mixer->samples[i].audio_cur += 1;
}
output[j] = (int16_t) std::clamp(
output[j] + x,
(int) std::numeric_limits<int16_t>::min(),
(int) std::numeric_limits<int16_t>::max());
}
}
for (size_t i = 0; i < output_len; ++i) {
output[i] = (int16_t) (output[i] * mixer->volume);
}
}
struct Rubber_Animat
{
float begin;
float end;
float duration;
float t;
Rectf transform_rect(Rectf texbox, Vec2f pos) const
{
const float offset = begin + (end - begin) * (t / duration);
const float w = texbox.w + offset * texbox.h;
const float h = texbox.h - offset * texbox.h;
return {pos.x - w * 0.5f, pos.y + (texbox.h * 0.5f) - h, w, h};
}
void update(float dt)
{
if (!finished()) t += dt;
}
bool finished() const
{
return t >= duration;
}
void reset()
{
t = 0.0f;
}
};
template <size_t N>
struct Compose_Rubber_Animat
{
Rubber_Animat rubber_animats[N];
size_t current;
Rectf transform_rect(Rectf texbox, Vec2f pos) const
{
return rubber_animats[std::min(current, N - 1)].transform_rect(texbox, pos);
}
void update(float dt)
{
if (finished()) return;
if (rubber_animats[current].finished()) {
current += 1;
}
rubber_animats[current].update(dt);
}
bool finished() const
{
return current >= N;
}
void reset()
{
current = 0;
for (size_t i = 0; i < N; ++i) {
rubber_animats[i].reset();
}
}
};
int main(void)
{
sec(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO));
Sample_S16 jump_sample = load_wav_as_sample_s16("./qubodup-cfork-ccby3-jump.wav");
Sample_Mixer mixer = {};
mixer.volume = 0.2f;
SDL_AudioSpec want = {};
want.freq = SOMETHING_SOUND_FREQ;
want.format = SOMETHING_SOUND_FORMAT;
want.channels = SOMETHING_SOUND_CHANNELS;
want.samples = SOMETHING_SOUND_SAMPLES;
want.callback = sample_mixer_audio_callback;
want.userdata = &mixer;
SDL_AudioSpec have = {};
SDL_AudioDeviceID dev = SDL_OpenAudioDevice(
NULL,
0,
&want,
&have,
SDL_AUDIO_ALLOW_FORMAT_CHANGE);
if (dev == 0) {
fprintf(stderr, "SDL pooped itself: Failed to open audio: %s\n", SDL_GetError());
abort();
}
if (have.format != want.format) {
fprintf(stderr, "[WARN] We didn't get expected audio format.\n");
abort();
}
SDL_PauseAudioDevice(dev, 0);
SDL_Window *window =
sec(SDL_CreateWindow(
"KKona",
0, 0, 800, 600,
SDL_WINDOW_RESIZABLE));
SDL_Renderer *renderer =
sec(SDL_CreateRenderer(
window, -1,
SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED));
auto kkona = load_png_file_as_sprite(renderer, "./KKona.png");
Rubber_Animat prepare_animat = {};
prepare_animat.begin = 0.0f;
prepare_animat.end = 0.2f;
prepare_animat.duration = 0.5f;
enum Jump_Animat_Phase
{
ATTACK = 0,
RECOVER,
N
};
Compose_Rubber_Animat<N> jump_animat = {};
jump_animat.rubber_animats[ATTACK].begin = 0.2f;
jump_animat.rubber_animats[ATTACK].end = -0.2f;
jump_animat.rubber_animats[ATTACK].duration = 0.1f;
jump_animat.rubber_animats[RECOVER].begin = -0.2f;
jump_animat.rubber_animats[RECOVER].end = 0.0f;
jump_animat.rubber_animats[RECOVER].duration = 0.2f;
// This is hackish
jump_animat.current = N - 1;
jump_animat.rubber_animats[N - 1].t = jump_animat.rubber_animats[N - 1].duration;
bool jump = true;
const auto TEXBOX_SIZE = 64.0f * 4.0f;
const Rectf texbox_local = {
- (TEXBOX_SIZE / 2), - (TEXBOX_SIZE / 2),
TEXBOX_SIZE, TEXBOX_SIZE
};
float FLOOR = 0.0f;
Vec2f gravity = vec2(0.0f, 3000.0f);
Vec2f position = vec2(0.0f, 0.0f);
Vec2f velocity = vec2(0.0f, 0.0f);
for(;;) {
int window_w = 0, window_h = 0;
SDL_GetWindowSize(window, &window_w, &window_h);
position.x = (float) window_w * 0.5f;
FLOOR = (float) window_h - texbox_local.h * 0.5f;
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: {
exit(0);
} break;
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_SPACE: {
if (!event.key.repeat) {
jump = false;
prepare_animat.reset();
}
} break;
}
} break;
case SDL_KEYUP: {
switch (event.key.keysym.sym) {
case SDLK_SPACE: {
if (!event.key.repeat) {
jump = true;
jump_animat.reset();
velocity.y = gravity.y * -0.5f;
mixer.play_sample(jump_sample);
}
} break;
}
} break;
}
}
sec(SDL_SetRenderDrawColor(renderer, 18, 8, 8, 255));
sec(SDL_RenderClear(renderer));
const float dt = 1.0f / 60.0f;
velocity += gravity * dt;
position += velocity * dt;
if (position.y >= FLOOR) {
velocity = vec2(0.0f, 0.0f);
position.y = FLOOR;
}
if (jump) {
render_sprite(renderer,
kkona,
jump_animat.transform_rect(texbox_local, position));
jump_animat.update(dt);
} else {
render_sprite(renderer,
kkona,
prepare_animat.transform_rect(texbox_local, position));
prepare_animat.update(dt);
}
SDL_RenderPresent(renderer);
}
}
| 26.986143 | 106 | 0.558922 | tsoding |
5215fd7b379e0b8a9eb62f77bcf9bc66af329346 | 3,167 | cpp | C++ | server/api/src/rsSpecificQuery.cpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | server/api/src/rsSpecificQuery.cpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | server/api/src/rsSpecificQuery.cpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* See specificQuery.h for a description of this API call.*/
#include "irods/specificQuery.h"
#include "irods/icatHighLevelRoutines.hpp"
#include "irods/miscUtil.h"
#include "irods/rcMisc.h"
#include "irods/irods_log.hpp"
#include "irods/miscServerFunct.hpp"
#include "irods/irods_configuration_keywords.hpp"
#include "irods/rsSpecificQuery.hpp"
int
rsSpecificQuery( rsComm_t *rsComm, specificQueryInp_t *specificQueryInp,
genQueryOut_t **genQueryOut ) {
rodsServerHost_t *rodsServerHost;
int status;
char *zoneHint = "";
/* zoneHint = getZoneHintForGenQuery (genQueryInp); (need something like this?) */
zoneHint = getValByKey( &specificQueryInp->condInput, ZONE_KW );
status = getAndConnRcatHost(rsComm, SECONDARY_RCAT, (const char*) zoneHint, &rodsServerHost);
if ( status < 0 ) {
return status;
}
if ( rodsServerHost->localFlag == LOCAL_HOST ) {
std::string svc_role;
irods::error ret = get_catalog_service_role(svc_role);
if(!ret.ok()) {
irods::log(PASS(ret));
return ret.code();
}
if( irods::KW_CFG_SERVICE_ROLE_PROVIDER == svc_role ) {
status = _rsSpecificQuery( rsComm, specificQueryInp, genQueryOut );
} else if( irods::KW_CFG_SERVICE_ROLE_CONSUMER == svc_role ) {
rodsLog( LOG_NOTICE,
"rsSpecificQuery error. RCAT is not configured on this host" );
return SYS_NO_RCAT_SERVER_ERR;
} else {
rodsLog(
LOG_ERROR,
"role not supported [%s]",
svc_role.c_str() );
status = SYS_SERVICE_ROLE_NOT_SUPPORTED;
}
}
else {
status = rcSpecificQuery( rodsServerHost->conn,
specificQueryInp, genQueryOut );
}
if ( status < 0 && status != CAT_NO_ROWS_FOUND ) {
rodsLog( LOG_NOTICE,
"rsSpecificQuery: rcSpecificQuery failed, status = %d", status );
}
return status;
}
int
_rsSpecificQuery( rsComm_t *rsComm, specificQueryInp_t *specificQueryInp,
genQueryOut_t **genQueryOut ) {
int status;
*genQueryOut = ( genQueryOut_t* )malloc( sizeof( genQueryOut_t ) );
memset( ( char * )*genQueryOut, 0, sizeof( genQueryOut_t ) );
status = chlSpecificQuery( *specificQueryInp, *genQueryOut );
if ( status == CAT_UNKNOWN_SPECIFIC_QUERY ) {
int i;
i = addRErrorMsg( &rsComm->rError, 0, "The SQL is not pre-defined.\n See 'iadmin h asq' (add specific query)" );
if ( i < 0 ) {
irods::log( i, "addErrorMsg failed" );
}
}
if ( status < 0 ) {
clearGenQueryOut( *genQueryOut );
free( *genQueryOut );
*genQueryOut = NULL;
if ( status != CAT_NO_ROWS_FOUND ) {
rodsLog( LOG_NOTICE,
"_rsSpecificQuery: specificQuery status = %d", status );
}
return status;
}
return status;
}
| 33.691489 | 121 | 0.607831 | stefan-wolfsheimer |
52166845003e90d0090f800b681e53cfb51b447c | 307 | cpp | C++ | AtCoder/ABC079/A/abc079_a.cpp | object-oriented-human/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | 1 | 2022-02-21T15:43:01.000Z | 2022-02-21T15:43:01.000Z | AtCoder/ABC079/A/abc079_a.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | AtCoder/ABC079/A/abc079_a.cpp | foooop/competitive | 9e761020e887d8980a39a64eeaeaa39af0ecd777 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define int long long
#define endl '\n'
#define fastio ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
signed main() {
string n; cin >> n;
if ((n[0] == n[1] && n[1] == n[2]) || (n[1] == n[2] && n[2] == n[3])) cout << "Yes";
else cout << "No";
} | 30.7 | 88 | 0.543974 | object-oriented-human |
52177474559eeebe0f9989317ba0a2177a0c0060 | 67 | cpp | C++ | common/renderer/component/Component.cpp | damonwy/vk_launcher | ac06969c3429c5b1a49245ee75a275afa22480c8 | [
"MIT"
] | null | null | null | common/renderer/component/Component.cpp | damonwy/vk_launcher | ac06969c3429c5b1a49245ee75a275afa22480c8 | [
"MIT"
] | 4 | 2020-12-29T00:16:39.000Z | 2021-01-18T02:04:33.000Z | common/renderer/component/Component.cpp | damonwy/vk_launcher | ac06969c3429c5b1a49245ee75a275afa22480c8 | [
"MIT"
] | null | null | null | //
// Created by Daosheng Mu on 8/9/20.
//
#include "Component.h"
| 11.166667 | 36 | 0.626866 | damonwy |
5217abbca1119f5eb093537d6bd996ad91786692 | 384 | cc | C++ | ch04/simplenet/lib/gradient.cc | research-note/deep-learning-from-scratch-using-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | 2 | 2021-08-15T12:38:41.000Z | 2021-08-15T12:38:51.000Z | ch04/simplenet/lib/gradient.cc | research-note/deep-learning-from-scratch-using-modern-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | null | null | null | ch04/simplenet/lib/gradient.cc | research-note/deep-learning-from-scratch-using-modern-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | null | null | null | /*
* Build gradient lib.
*
* Copyright Paran Lee
*
*/
#include <iostream>
#include "lib/gradient.hpp"
template <typename F, typename T>
T gradient(F f, T x) {
const auto h = 1e-4;
const auto hh = 2 * h;
std::transform(x.begin(), x.end(), x.begin(),
[f, h, hh](auto v) -> auto {
return ( f(v + h) - f(v - h) ) / hh;
});
return x;
}
| 16.695652 | 49 | 0.510417 | research-note |
5217acc06431d7d61d2c9174253962e91b57b67e | 92,486 | cc | C++ | Rover/build_isolated/cartographer/install/cartographer/mapping/proto/pose_graph.pb.cc | Rose-Hulman-Rover-Team/Rover-2019-2020 | d75a9086fa733f8a8b5240005bee058737ad82c7 | [
"MIT"
] | 1 | 2019-11-07T08:06:26.000Z | 2019-11-07T08:06:26.000Z | TrekBot_WS/build_isolated/cartographer/install/cartographer/mapping/proto/pose_graph.pb.cc | Rafcin/TrekBot | d3dc63e6c16a040b16170f143556ef358018b7da | [
"Unlicense"
] | null | null | null | TrekBot_WS/build_isolated/cartographer/install/cartographer/mapping/proto/pose_graph.pb.cc | Rafcin/TrekBot | d3dc63e6c16a040b16170f143556ef358018b7da | [
"Unlicense"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: cartographer/mapping/proto/pose_graph.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "cartographer/mapping/proto/pose_graph.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace cartographer {
namespace mapping {
namespace proto {
class SubmapIdDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<SubmapId>
_instance;
} _SubmapId_default_instance_;
class NodeIdDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<NodeId>
_instance;
} _NodeId_default_instance_;
class PoseGraph_ConstraintDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<PoseGraph_Constraint>
_instance;
} _PoseGraph_Constraint_default_instance_;
class PoseGraph_LandmarkPoseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<PoseGraph_LandmarkPose>
_instance;
} _PoseGraph_LandmarkPose_default_instance_;
class PoseGraphDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<PoseGraph>
_instance;
} _PoseGraph_default_instance_;
namespace protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[5];
const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[1];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubmapId, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubmapId, trajectory_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubmapId, submap_index_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NodeId, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NodeId, trajectory_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(NodeId, node_index_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, submap_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, node_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, relative_pose_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, translation_weight_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, rotation_weight_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_Constraint, tag_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_LandmarkPose, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_LandmarkPose, landmark_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph_LandmarkPose, global_pose_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph, constraint_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph, trajectory_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PoseGraph, landmark_poses_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(SubmapId)},
{ 7, -1, sizeof(NodeId)},
{ 14, -1, sizeof(PoseGraph_Constraint)},
{ 25, -1, sizeof(PoseGraph_LandmarkPose)},
{ 32, -1, sizeof(PoseGraph)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_SubmapId_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_NodeId_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_PoseGraph_Constraint_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_PoseGraph_LandmarkPose_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_PoseGraph_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"cartographer/mapping/proto/pose_graph.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, file_level_enum_descriptors, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5);
}
} // namespace
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
::cartographer::mapping::proto::protobuf_cartographer_2fmapping_2fproto_2ftrajectory_2eproto::InitDefaults();
::cartographer::transform::proto::protobuf_cartographer_2ftransform_2fproto_2ftransform_2eproto::InitDefaults();
_SubmapId_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_SubmapId_default_instance_);_NodeId_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_NodeId_default_instance_);_PoseGraph_Constraint_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_PoseGraph_Constraint_default_instance_);_PoseGraph_LandmarkPose_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_PoseGraph_LandmarkPose_default_instance_);_PoseGraph_default_instance_._instance.DefaultConstruct();
::google::protobuf::internal::OnShutdownDestroyMessage(
&_PoseGraph_default_instance_);_PoseGraph_Constraint_default_instance_._instance.get_mutable()->submap_id_ = const_cast< ::cartographer::mapping::proto::SubmapId*>(
::cartographer::mapping::proto::SubmapId::internal_default_instance());
_PoseGraph_Constraint_default_instance_._instance.get_mutable()->node_id_ = const_cast< ::cartographer::mapping::proto::NodeId*>(
::cartographer::mapping::proto::NodeId::internal_default_instance());
_PoseGraph_Constraint_default_instance_._instance.get_mutable()->relative_pose_ = const_cast< ::cartographer::transform::proto::Rigid3d*>(
::cartographer::transform::proto::Rigid3d::internal_default_instance());
_PoseGraph_LandmarkPose_default_instance_._instance.get_mutable()->global_pose_ = const_cast< ::cartographer::transform::proto::Rigid3d*>(
::cartographer::transform::proto::Rigid3d::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
namespace {
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n+cartographer/mapping/proto/pose_graph."
"proto\022\032cartographer.mapping.proto\032+carto"
"grapher/mapping/proto/trajectory.proto\032,"
"cartographer/transform/proto/transform.p"
"roto\"7\n\010SubmapId\022\025\n\rtrajectory_id\030\001 \001(\005\022"
"\024\n\014submap_index\030\002 \001(\005\"3\n\006NodeId\022\025\n\rtraje"
"ctory_id\030\001 \001(\005\022\022\n\nnode_index\030\002 \001(\005\"\230\005\n\tP"
"oseGraph\022D\n\nconstraint\030\002 \003(\01320.cartograp"
"her.mapping.proto.PoseGraph.Constraint\022:"
"\n\ntrajectory\030\004 \003(\0132&.cartographer.mappin"
"g.proto.Trajectory\022J\n\016landmark_poses\030\005 \003"
"(\01322.cartographer.mapping.proto.PoseGrap"
"h.LandmarkPose\032\333\002\n\nConstraint\0227\n\tsubmap_"
"id\030\001 \001(\0132$.cartographer.mapping.proto.Su"
"bmapId\0223\n\007node_id\030\002 \001(\0132\".cartographer.m"
"apping.proto.NodeId\022<\n\rrelative_pose\030\003 \001"
"(\0132%.cartographer.transform.proto.Rigid3"
"d\022\032\n\022translation_weight\030\006 \001(\001\022\027\n\017rotatio"
"n_weight\030\007 \001(\001\022A\n\003tag\030\005 \001(\01624.cartograph"
"er.mapping.proto.PoseGraph.Constraint.Ta"
"g\")\n\003Tag\022\020\n\014INTRA_SUBMAP\020\000\022\020\n\014INTER_SUBM"
"AP\020\001\032_\n\014LandmarkPose\022\023\n\013landmark_id\030\001 \001("
"\t\022:\n\013global_pose\030\002 \001(\0132%.cartographer.tr"
"ansform.proto.Rigid3db\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 949);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"cartographer/mapping/proto/pose_graph.proto", &protobuf_RegisterTypes);
::cartographer::mapping::proto::protobuf_cartographer_2fmapping_2fproto_2ftrajectory_2eproto::AddDescriptors();
::cartographer::transform::proto::protobuf_cartographer_2ftransform_2fproto_2ftransform_2eproto::AddDescriptors();
}
} // anonymous namespace
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto
const ::google::protobuf::EnumDescriptor* PoseGraph_Constraint_Tag_descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_enum_descriptors[0];
}
bool PoseGraph_Constraint_Tag_IsValid(int value) {
switch (value) {
case 0:
case 1:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const PoseGraph_Constraint_Tag PoseGraph_Constraint::INTRA_SUBMAP;
const PoseGraph_Constraint_Tag PoseGraph_Constraint::INTER_SUBMAP;
const PoseGraph_Constraint_Tag PoseGraph_Constraint::Tag_MIN;
const PoseGraph_Constraint_Tag PoseGraph_Constraint::Tag_MAX;
const int PoseGraph_Constraint::Tag_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SubmapId::kTrajectoryIdFieldNumber;
const int SubmapId::kSubmapIndexFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SubmapId::SubmapId()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.SubmapId)
}
SubmapId::SubmapId(const SubmapId& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&trajectory_id_, &from.trajectory_id_,
static_cast<size_t>(reinterpret_cast<char*>(&submap_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(submap_index_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.SubmapId)
}
void SubmapId::SharedCtor() {
::memset(&trajectory_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&submap_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(submap_index_));
_cached_size_ = 0;
}
SubmapId::~SubmapId() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.SubmapId)
SharedDtor();
}
void SubmapId::SharedDtor() {
}
void SubmapId::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SubmapId::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const SubmapId& SubmapId::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
return *internal_default_instance();
}
SubmapId* SubmapId::New(::google::protobuf::Arena* arena) const {
SubmapId* n = new SubmapId;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SubmapId::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.SubmapId)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&trajectory_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&submap_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(submap_index_));
_internal_metadata_.Clear();
}
bool SubmapId::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.SubmapId)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 trajectory_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &trajectory_id_)));
} else {
goto handle_unusual;
}
break;
}
// int32 submap_index = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &submap_index_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.SubmapId)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.SubmapId)
return false;
#undef DO_
}
void SubmapId::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.SubmapId)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->trajectory_id(), output);
}
// int32 submap_index = 2;
if (this->submap_index() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->submap_index(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.SubmapId)
}
::google::protobuf::uint8* SubmapId::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.SubmapId)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->trajectory_id(), target);
}
// int32 submap_index = 2;
if (this->submap_index() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->submap_index(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.SubmapId)
return target;
}
size_t SubmapId::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.SubmapId)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->trajectory_id());
}
// int32 submap_index = 2;
if (this->submap_index() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->submap_index());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SubmapId::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.SubmapId)
GOOGLE_DCHECK_NE(&from, this);
const SubmapId* source =
::google::protobuf::internal::DynamicCastToGenerated<const SubmapId>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.SubmapId)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.SubmapId)
MergeFrom(*source);
}
}
void SubmapId::MergeFrom(const SubmapId& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.SubmapId)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.trajectory_id() != 0) {
set_trajectory_id(from.trajectory_id());
}
if (from.submap_index() != 0) {
set_submap_index(from.submap_index());
}
}
void SubmapId::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.SubmapId)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SubmapId::CopyFrom(const SubmapId& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.SubmapId)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SubmapId::IsInitialized() const {
return true;
}
void SubmapId::Swap(SubmapId* other) {
if (other == this) return;
InternalSwap(other);
}
void SubmapId::InternalSwap(SubmapId* other) {
using std::swap;
swap(trajectory_id_, other->trajectory_id_);
swap(submap_index_, other->submap_index_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SubmapId::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// SubmapId
// int32 trajectory_id = 1;
void SubmapId::clear_trajectory_id() {
trajectory_id_ = 0;
}
::google::protobuf::int32 SubmapId::trajectory_id() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.SubmapId.trajectory_id)
return trajectory_id_;
}
void SubmapId::set_trajectory_id(::google::protobuf::int32 value) {
trajectory_id_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.SubmapId.trajectory_id)
}
// int32 submap_index = 2;
void SubmapId::clear_submap_index() {
submap_index_ = 0;
}
::google::protobuf::int32 SubmapId::submap_index() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.SubmapId.submap_index)
return submap_index_;
}
void SubmapId::set_submap_index(::google::protobuf::int32 value) {
submap_index_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.SubmapId.submap_index)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int NodeId::kTrajectoryIdFieldNumber;
const int NodeId::kNodeIndexFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
NodeId::NodeId()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.NodeId)
}
NodeId::NodeId(const NodeId& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&trajectory_id_, &from.trajectory_id_,
static_cast<size_t>(reinterpret_cast<char*>(&node_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(node_index_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.NodeId)
}
void NodeId::SharedCtor() {
::memset(&trajectory_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&node_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(node_index_));
_cached_size_ = 0;
}
NodeId::~NodeId() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.NodeId)
SharedDtor();
}
void NodeId::SharedDtor() {
}
void NodeId::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* NodeId::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const NodeId& NodeId::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
return *internal_default_instance();
}
NodeId* NodeId::New(::google::protobuf::Arena* arena) const {
NodeId* n = new NodeId;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void NodeId::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.NodeId)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&trajectory_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&node_index_) -
reinterpret_cast<char*>(&trajectory_id_)) + sizeof(node_index_));
_internal_metadata_.Clear();
}
bool NodeId::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.NodeId)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 trajectory_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &trajectory_id_)));
} else {
goto handle_unusual;
}
break;
}
// int32 node_index = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &node_index_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.NodeId)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.NodeId)
return false;
#undef DO_
}
void NodeId::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.NodeId)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->trajectory_id(), output);
}
// int32 node_index = 2;
if (this->node_index() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->node_index(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.NodeId)
}
::google::protobuf::uint8* NodeId::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.NodeId)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->trajectory_id(), target);
}
// int32 node_index = 2;
if (this->node_index() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->node_index(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.NodeId)
return target;
}
size_t NodeId::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.NodeId)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// int32 trajectory_id = 1;
if (this->trajectory_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->trajectory_id());
}
// int32 node_index = 2;
if (this->node_index() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->node_index());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void NodeId::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.NodeId)
GOOGLE_DCHECK_NE(&from, this);
const NodeId* source =
::google::protobuf::internal::DynamicCastToGenerated<const NodeId>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.NodeId)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.NodeId)
MergeFrom(*source);
}
}
void NodeId::MergeFrom(const NodeId& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.NodeId)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.trajectory_id() != 0) {
set_trajectory_id(from.trajectory_id());
}
if (from.node_index() != 0) {
set_node_index(from.node_index());
}
}
void NodeId::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.NodeId)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void NodeId::CopyFrom(const NodeId& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.NodeId)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool NodeId::IsInitialized() const {
return true;
}
void NodeId::Swap(NodeId* other) {
if (other == this) return;
InternalSwap(other);
}
void NodeId::InternalSwap(NodeId* other) {
using std::swap;
swap(trajectory_id_, other->trajectory_id_);
swap(node_index_, other->node_index_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata NodeId::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// NodeId
// int32 trajectory_id = 1;
void NodeId::clear_trajectory_id() {
trajectory_id_ = 0;
}
::google::protobuf::int32 NodeId::trajectory_id() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.NodeId.trajectory_id)
return trajectory_id_;
}
void NodeId::set_trajectory_id(::google::protobuf::int32 value) {
trajectory_id_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.NodeId.trajectory_id)
}
// int32 node_index = 2;
void NodeId::clear_node_index() {
node_index_ = 0;
}
::google::protobuf::int32 NodeId::node_index() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.NodeId.node_index)
return node_index_;
}
void NodeId::set_node_index(::google::protobuf::int32 value) {
node_index_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.NodeId.node_index)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int PoseGraph_Constraint::kSubmapIdFieldNumber;
const int PoseGraph_Constraint::kNodeIdFieldNumber;
const int PoseGraph_Constraint::kRelativePoseFieldNumber;
const int PoseGraph_Constraint::kTranslationWeightFieldNumber;
const int PoseGraph_Constraint::kRotationWeightFieldNumber;
const int PoseGraph_Constraint::kTagFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PoseGraph_Constraint::PoseGraph_Constraint()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.PoseGraph.Constraint)
}
PoseGraph_Constraint::PoseGraph_Constraint(const PoseGraph_Constraint& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_submap_id()) {
submap_id_ = new ::cartographer::mapping::proto::SubmapId(*from.submap_id_);
} else {
submap_id_ = NULL;
}
if (from.has_node_id()) {
node_id_ = new ::cartographer::mapping::proto::NodeId(*from.node_id_);
} else {
node_id_ = NULL;
}
if (from.has_relative_pose()) {
relative_pose_ = new ::cartographer::transform::proto::Rigid3d(*from.relative_pose_);
} else {
relative_pose_ = NULL;
}
::memcpy(&translation_weight_, &from.translation_weight_,
static_cast<size_t>(reinterpret_cast<char*>(&tag_) -
reinterpret_cast<char*>(&translation_weight_)) + sizeof(tag_));
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.PoseGraph.Constraint)
}
void PoseGraph_Constraint::SharedCtor() {
::memset(&submap_id_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&tag_) -
reinterpret_cast<char*>(&submap_id_)) + sizeof(tag_));
_cached_size_ = 0;
}
PoseGraph_Constraint::~PoseGraph_Constraint() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.PoseGraph.Constraint)
SharedDtor();
}
void PoseGraph_Constraint::SharedDtor() {
if (this != internal_default_instance()) delete submap_id_;
if (this != internal_default_instance()) delete node_id_;
if (this != internal_default_instance()) delete relative_pose_;
}
void PoseGraph_Constraint::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PoseGraph_Constraint::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const PoseGraph_Constraint& PoseGraph_Constraint::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
return *internal_default_instance();
}
PoseGraph_Constraint* PoseGraph_Constraint::New(::google::protobuf::Arena* arena) const {
PoseGraph_Constraint* n = new PoseGraph_Constraint;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void PoseGraph_Constraint::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.PoseGraph.Constraint)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
if (GetArenaNoVirtual() == NULL && submap_id_ != NULL) {
delete submap_id_;
}
submap_id_ = NULL;
if (GetArenaNoVirtual() == NULL && node_id_ != NULL) {
delete node_id_;
}
node_id_ = NULL;
if (GetArenaNoVirtual() == NULL && relative_pose_ != NULL) {
delete relative_pose_;
}
relative_pose_ = NULL;
::memset(&translation_weight_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&tag_) -
reinterpret_cast<char*>(&translation_weight_)) + sizeof(tag_));
_internal_metadata_.Clear();
}
bool PoseGraph_Constraint::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.PoseGraph.Constraint)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// .cartographer.mapping.proto.SubmapId submap_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_submap_id()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.NodeId node_id = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_node_id()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.transform.proto.Rigid3d relative_pose = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_relative_pose()));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.mapping.proto.PoseGraph.Constraint.Tag tag = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_tag(static_cast< ::cartographer::mapping::proto::PoseGraph_Constraint_Tag >(value));
} else {
goto handle_unusual;
}
break;
}
// double translation_weight = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &translation_weight_)));
} else {
goto handle_unusual;
}
break;
}
// double rotation_weight = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(57u /* 57 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &rotation_weight_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.PoseGraph.Constraint)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.PoseGraph.Constraint)
return false;
#undef DO_
}
void PoseGraph_Constraint::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.PoseGraph.Constraint)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->submap_id_, output);
}
// .cartographer.mapping.proto.NodeId node_id = 2;
if (this->has_node_id()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->node_id_, output);
}
// .cartographer.transform.proto.Rigid3d relative_pose = 3;
if (this->has_relative_pose()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->relative_pose_, output);
}
// .cartographer.mapping.proto.PoseGraph.Constraint.Tag tag = 5;
if (this->tag() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
5, this->tag(), output);
}
// double translation_weight = 6;
if (this->translation_weight() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->translation_weight(), output);
}
// double rotation_weight = 7;
if (this->rotation_weight() != 0) {
::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->rotation_weight(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.PoseGraph.Constraint)
}
::google::protobuf::uint8* PoseGraph_Constraint::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.PoseGraph.Constraint)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->submap_id_, deterministic, target);
}
// .cartographer.mapping.proto.NodeId node_id = 2;
if (this->has_node_id()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *this->node_id_, deterministic, target);
}
// .cartographer.transform.proto.Rigid3d relative_pose = 3;
if (this->has_relative_pose()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->relative_pose_, deterministic, target);
}
// .cartographer.mapping.proto.PoseGraph.Constraint.Tag tag = 5;
if (this->tag() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
5, this->tag(), target);
}
// double translation_weight = 6;
if (this->translation_weight() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->translation_weight(), target);
}
// double rotation_weight = 7;
if (this->rotation_weight() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->rotation_weight(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.PoseGraph.Constraint)
return target;
}
size_t PoseGraph_Constraint::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.PoseGraph.Constraint)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// .cartographer.mapping.proto.SubmapId submap_id = 1;
if (this->has_submap_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->submap_id_);
}
// .cartographer.mapping.proto.NodeId node_id = 2;
if (this->has_node_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->node_id_);
}
// .cartographer.transform.proto.Rigid3d relative_pose = 3;
if (this->has_relative_pose()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->relative_pose_);
}
// double translation_weight = 6;
if (this->translation_weight() != 0) {
total_size += 1 + 8;
}
// double rotation_weight = 7;
if (this->rotation_weight() != 0) {
total_size += 1 + 8;
}
// .cartographer.mapping.proto.PoseGraph.Constraint.Tag tag = 5;
if (this->tag() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->tag());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PoseGraph_Constraint::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.PoseGraph.Constraint)
GOOGLE_DCHECK_NE(&from, this);
const PoseGraph_Constraint* source =
::google::protobuf::internal::DynamicCastToGenerated<const PoseGraph_Constraint>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.PoseGraph.Constraint)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.PoseGraph.Constraint)
MergeFrom(*source);
}
}
void PoseGraph_Constraint::MergeFrom(const PoseGraph_Constraint& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.PoseGraph.Constraint)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_submap_id()) {
mutable_submap_id()->::cartographer::mapping::proto::SubmapId::MergeFrom(from.submap_id());
}
if (from.has_node_id()) {
mutable_node_id()->::cartographer::mapping::proto::NodeId::MergeFrom(from.node_id());
}
if (from.has_relative_pose()) {
mutable_relative_pose()->::cartographer::transform::proto::Rigid3d::MergeFrom(from.relative_pose());
}
if (from.translation_weight() != 0) {
set_translation_weight(from.translation_weight());
}
if (from.rotation_weight() != 0) {
set_rotation_weight(from.rotation_weight());
}
if (from.tag() != 0) {
set_tag(from.tag());
}
}
void PoseGraph_Constraint::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.PoseGraph.Constraint)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PoseGraph_Constraint::CopyFrom(const PoseGraph_Constraint& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.PoseGraph.Constraint)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PoseGraph_Constraint::IsInitialized() const {
return true;
}
void PoseGraph_Constraint::Swap(PoseGraph_Constraint* other) {
if (other == this) return;
InternalSwap(other);
}
void PoseGraph_Constraint::InternalSwap(PoseGraph_Constraint* other) {
using std::swap;
swap(submap_id_, other->submap_id_);
swap(node_id_, other->node_id_);
swap(relative_pose_, other->relative_pose_);
swap(translation_weight_, other->translation_weight_);
swap(rotation_weight_, other->rotation_weight_);
swap(tag_, other->tag_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata PoseGraph_Constraint::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// PoseGraph_Constraint
// .cartographer.mapping.proto.SubmapId submap_id = 1;
bool PoseGraph_Constraint::has_submap_id() const {
return this != internal_default_instance() && submap_id_ != NULL;
}
void PoseGraph_Constraint::clear_submap_id() {
if (GetArenaNoVirtual() == NULL && submap_id_ != NULL) delete submap_id_;
submap_id_ = NULL;
}
const ::cartographer::mapping::proto::SubmapId& PoseGraph_Constraint::submap_id() const {
const ::cartographer::mapping::proto::SubmapId* p = submap_id_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.submap_id)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::mapping::proto::SubmapId*>(
&::cartographer::mapping::proto::_SubmapId_default_instance_);
}
::cartographer::mapping::proto::SubmapId* PoseGraph_Constraint::mutable_submap_id() {
if (submap_id_ == NULL) {
submap_id_ = new ::cartographer::mapping::proto::SubmapId;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.Constraint.submap_id)
return submap_id_;
}
::cartographer::mapping::proto::SubmapId* PoseGraph_Constraint::release_submap_id() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraph.Constraint.submap_id)
::cartographer::mapping::proto::SubmapId* temp = submap_id_;
submap_id_ = NULL;
return temp;
}
void PoseGraph_Constraint::set_allocated_submap_id(::cartographer::mapping::proto::SubmapId* submap_id) {
delete submap_id_;
submap_id_ = submap_id;
if (submap_id) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraph.Constraint.submap_id)
}
// .cartographer.mapping.proto.NodeId node_id = 2;
bool PoseGraph_Constraint::has_node_id() const {
return this != internal_default_instance() && node_id_ != NULL;
}
void PoseGraph_Constraint::clear_node_id() {
if (GetArenaNoVirtual() == NULL && node_id_ != NULL) delete node_id_;
node_id_ = NULL;
}
const ::cartographer::mapping::proto::NodeId& PoseGraph_Constraint::node_id() const {
const ::cartographer::mapping::proto::NodeId* p = node_id_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.node_id)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::mapping::proto::NodeId*>(
&::cartographer::mapping::proto::_NodeId_default_instance_);
}
::cartographer::mapping::proto::NodeId* PoseGraph_Constraint::mutable_node_id() {
if (node_id_ == NULL) {
node_id_ = new ::cartographer::mapping::proto::NodeId;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.Constraint.node_id)
return node_id_;
}
::cartographer::mapping::proto::NodeId* PoseGraph_Constraint::release_node_id() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraph.Constraint.node_id)
::cartographer::mapping::proto::NodeId* temp = node_id_;
node_id_ = NULL;
return temp;
}
void PoseGraph_Constraint::set_allocated_node_id(::cartographer::mapping::proto::NodeId* node_id) {
delete node_id_;
node_id_ = node_id;
if (node_id) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraph.Constraint.node_id)
}
// .cartographer.transform.proto.Rigid3d relative_pose = 3;
bool PoseGraph_Constraint::has_relative_pose() const {
return this != internal_default_instance() && relative_pose_ != NULL;
}
void PoseGraph_Constraint::clear_relative_pose() {
if (GetArenaNoVirtual() == NULL && relative_pose_ != NULL) delete relative_pose_;
relative_pose_ = NULL;
}
const ::cartographer::transform::proto::Rigid3d& PoseGraph_Constraint::relative_pose() const {
const ::cartographer::transform::proto::Rigid3d* p = relative_pose_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.relative_pose)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::transform::proto::Rigid3d*>(
&::cartographer::transform::proto::_Rigid3d_default_instance_);
}
::cartographer::transform::proto::Rigid3d* PoseGraph_Constraint::mutable_relative_pose() {
if (relative_pose_ == NULL) {
relative_pose_ = new ::cartographer::transform::proto::Rigid3d;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.Constraint.relative_pose)
return relative_pose_;
}
::cartographer::transform::proto::Rigid3d* PoseGraph_Constraint::release_relative_pose() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraph.Constraint.relative_pose)
::cartographer::transform::proto::Rigid3d* temp = relative_pose_;
relative_pose_ = NULL;
return temp;
}
void PoseGraph_Constraint::set_allocated_relative_pose(::cartographer::transform::proto::Rigid3d* relative_pose) {
delete relative_pose_;
relative_pose_ = relative_pose;
if (relative_pose) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraph.Constraint.relative_pose)
}
// double translation_weight = 6;
void PoseGraph_Constraint::clear_translation_weight() {
translation_weight_ = 0;
}
double PoseGraph_Constraint::translation_weight() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.translation_weight)
return translation_weight_;
}
void PoseGraph_Constraint::set_translation_weight(double value) {
translation_weight_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraph.Constraint.translation_weight)
}
// double rotation_weight = 7;
void PoseGraph_Constraint::clear_rotation_weight() {
rotation_weight_ = 0;
}
double PoseGraph_Constraint::rotation_weight() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.rotation_weight)
return rotation_weight_;
}
void PoseGraph_Constraint::set_rotation_weight(double value) {
rotation_weight_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraph.Constraint.rotation_weight)
}
// .cartographer.mapping.proto.PoseGraph.Constraint.Tag tag = 5;
void PoseGraph_Constraint::clear_tag() {
tag_ = 0;
}
::cartographer::mapping::proto::PoseGraph_Constraint_Tag PoseGraph_Constraint::tag() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.Constraint.tag)
return static_cast< ::cartographer::mapping::proto::PoseGraph_Constraint_Tag >(tag_);
}
void PoseGraph_Constraint::set_tag(::cartographer::mapping::proto::PoseGraph_Constraint_Tag value) {
tag_ = value;
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraph.Constraint.tag)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int PoseGraph_LandmarkPose::kLandmarkIdFieldNumber;
const int PoseGraph_LandmarkPose::kGlobalPoseFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PoseGraph_LandmarkPose::PoseGraph_LandmarkPose()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.PoseGraph.LandmarkPose)
}
PoseGraph_LandmarkPose::PoseGraph_LandmarkPose(const PoseGraph_LandmarkPose& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
landmark_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.landmark_id().size() > 0) {
landmark_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.landmark_id_);
}
if (from.has_global_pose()) {
global_pose_ = new ::cartographer::transform::proto::Rigid3d(*from.global_pose_);
} else {
global_pose_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.PoseGraph.LandmarkPose)
}
void PoseGraph_LandmarkPose::SharedCtor() {
landmark_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
global_pose_ = NULL;
_cached_size_ = 0;
}
PoseGraph_LandmarkPose::~PoseGraph_LandmarkPose() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.PoseGraph.LandmarkPose)
SharedDtor();
}
void PoseGraph_LandmarkPose::SharedDtor() {
landmark_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete global_pose_;
}
void PoseGraph_LandmarkPose::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PoseGraph_LandmarkPose::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const PoseGraph_LandmarkPose& PoseGraph_LandmarkPose::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
return *internal_default_instance();
}
PoseGraph_LandmarkPose* PoseGraph_LandmarkPose::New(::google::protobuf::Arena* arena) const {
PoseGraph_LandmarkPose* n = new PoseGraph_LandmarkPose;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void PoseGraph_LandmarkPose::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
landmark_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (GetArenaNoVirtual() == NULL && global_pose_ != NULL) {
delete global_pose_;
}
global_pose_ = NULL;
_internal_metadata_.Clear();
}
bool PoseGraph_LandmarkPose::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string landmark_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_landmark_id()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->landmark_id().data(), static_cast<int>(this->landmark_id().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id"));
} else {
goto handle_unusual;
}
break;
}
// .cartographer.transform.proto.Rigid3d global_pose = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_global_pose()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.PoseGraph.LandmarkPose)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.PoseGraph.LandmarkPose)
return false;
#undef DO_
}
void PoseGraph_LandmarkPose::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string landmark_id = 1;
if (this->landmark_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->landmark_id().data(), static_cast<int>(this->landmark_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->landmark_id(), output);
}
// .cartographer.transform.proto.Rigid3d global_pose = 2;
if (this->has_global_pose()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->global_pose_, output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.PoseGraph.LandmarkPose)
}
::google::protobuf::uint8* PoseGraph_LandmarkPose::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// string landmark_id = 1;
if (this->landmark_id().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->landmark_id().data(), static_cast<int>(this->landmark_id().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->landmark_id(), target);
}
// .cartographer.transform.proto.Rigid3d global_pose = 2;
if (this->has_global_pose()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *this->global_pose_, deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.PoseGraph.LandmarkPose)
return target;
}
size_t PoseGraph_LandmarkPose::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// string landmark_id = 1;
if (this->landmark_id().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->landmark_id());
}
// .cartographer.transform.proto.Rigid3d global_pose = 2;
if (this->has_global_pose()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->global_pose_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PoseGraph_LandmarkPose::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
GOOGLE_DCHECK_NE(&from, this);
const PoseGraph_LandmarkPose* source =
::google::protobuf::internal::DynamicCastToGenerated<const PoseGraph_LandmarkPose>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.PoseGraph.LandmarkPose)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.PoseGraph.LandmarkPose)
MergeFrom(*source);
}
}
void PoseGraph_LandmarkPose::MergeFrom(const PoseGraph_LandmarkPose& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.landmark_id().size() > 0) {
landmark_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.landmark_id_);
}
if (from.has_global_pose()) {
mutable_global_pose()->::cartographer::transform::proto::Rigid3d::MergeFrom(from.global_pose());
}
}
void PoseGraph_LandmarkPose::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PoseGraph_LandmarkPose::CopyFrom(const PoseGraph_LandmarkPose& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.PoseGraph.LandmarkPose)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PoseGraph_LandmarkPose::IsInitialized() const {
return true;
}
void PoseGraph_LandmarkPose::Swap(PoseGraph_LandmarkPose* other) {
if (other == this) return;
InternalSwap(other);
}
void PoseGraph_LandmarkPose::InternalSwap(PoseGraph_LandmarkPose* other) {
using std::swap;
landmark_id_.Swap(&other->landmark_id_);
swap(global_pose_, other->global_pose_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata PoseGraph_LandmarkPose::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// PoseGraph_LandmarkPose
// string landmark_id = 1;
void PoseGraph_LandmarkPose::clear_landmark_id() {
landmark_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& PoseGraph_LandmarkPose::landmark_id() const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
return landmark_id_.GetNoArena();
}
void PoseGraph_LandmarkPose::set_landmark_id(const ::std::string& value) {
landmark_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
}
#if LANG_CXX11
void PoseGraph_LandmarkPose::set_landmark_id(::std::string&& value) {
landmark_id_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
}
#endif
void PoseGraph_LandmarkPose::set_landmark_id(const char* value) {
GOOGLE_DCHECK(value != NULL);
landmark_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
}
void PoseGraph_LandmarkPose::set_landmark_id(const char* value, size_t size) {
landmark_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
}
::std::string* PoseGraph_LandmarkPose::mutable_landmark_id() {
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
return landmark_id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* PoseGraph_LandmarkPose::release_landmark_id() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
return landmark_id_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void PoseGraph_LandmarkPose::set_allocated_landmark_id(::std::string* landmark_id) {
if (landmark_id != NULL) {
} else {
}
landmark_id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), landmark_id);
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraph.LandmarkPose.landmark_id)
}
// .cartographer.transform.proto.Rigid3d global_pose = 2;
bool PoseGraph_LandmarkPose::has_global_pose() const {
return this != internal_default_instance() && global_pose_ != NULL;
}
void PoseGraph_LandmarkPose::clear_global_pose() {
if (GetArenaNoVirtual() == NULL && global_pose_ != NULL) delete global_pose_;
global_pose_ = NULL;
}
const ::cartographer::transform::proto::Rigid3d& PoseGraph_LandmarkPose::global_pose() const {
const ::cartographer::transform::proto::Rigid3d* p = global_pose_;
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.LandmarkPose.global_pose)
return p != NULL ? *p : *reinterpret_cast<const ::cartographer::transform::proto::Rigid3d*>(
&::cartographer::transform::proto::_Rigid3d_default_instance_);
}
::cartographer::transform::proto::Rigid3d* PoseGraph_LandmarkPose::mutable_global_pose() {
if (global_pose_ == NULL) {
global_pose_ = new ::cartographer::transform::proto::Rigid3d;
}
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.LandmarkPose.global_pose)
return global_pose_;
}
::cartographer::transform::proto::Rigid3d* PoseGraph_LandmarkPose::release_global_pose() {
// @@protoc_insertion_point(field_release:cartographer.mapping.proto.PoseGraph.LandmarkPose.global_pose)
::cartographer::transform::proto::Rigid3d* temp = global_pose_;
global_pose_ = NULL;
return temp;
}
void PoseGraph_LandmarkPose::set_allocated_global_pose(::cartographer::transform::proto::Rigid3d* global_pose) {
delete global_pose_;
global_pose_ = global_pose;
if (global_pose) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:cartographer.mapping.proto.PoseGraph.LandmarkPose.global_pose)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int PoseGraph::kConstraintFieldNumber;
const int PoseGraph::kTrajectoryFieldNumber;
const int PoseGraph::kLandmarkPosesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
PoseGraph::PoseGraph()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:cartographer.mapping.proto.PoseGraph)
}
PoseGraph::PoseGraph(const PoseGraph& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
constraint_(from.constraint_),
trajectory_(from.trajectory_),
landmark_poses_(from.landmark_poses_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
// @@protoc_insertion_point(copy_constructor:cartographer.mapping.proto.PoseGraph)
}
void PoseGraph::SharedCtor() {
_cached_size_ = 0;
}
PoseGraph::~PoseGraph() {
// @@protoc_insertion_point(destructor:cartographer.mapping.proto.PoseGraph)
SharedDtor();
}
void PoseGraph::SharedDtor() {
}
void PoseGraph::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PoseGraph::descriptor() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const PoseGraph& PoseGraph::default_instance() {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::InitDefaults();
return *internal_default_instance();
}
PoseGraph* PoseGraph::New(::google::protobuf::Arena* arena) const {
PoseGraph* n = new PoseGraph;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void PoseGraph::Clear() {
// @@protoc_insertion_point(message_clear_start:cartographer.mapping.proto.PoseGraph)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
constraint_.Clear();
trajectory_.Clear();
landmark_poses_.Clear();
_internal_metadata_.Clear();
}
bool PoseGraph::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:cartographer.mapping.proto.PoseGraph)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .cartographer.mapping.proto.PoseGraph.Constraint constraint = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_constraint()));
} else {
goto handle_unusual;
}
break;
}
// repeated .cartographer.mapping.proto.Trajectory trajectory = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_trajectory()));
} else {
goto handle_unusual;
}
break;
}
// repeated .cartographer.mapping.proto.PoseGraph.LandmarkPose landmark_poses = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_landmark_poses()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:cartographer.mapping.proto.PoseGraph)
return true;
failure:
// @@protoc_insertion_point(parse_failure:cartographer.mapping.proto.PoseGraph)
return false;
#undef DO_
}
void PoseGraph::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:cartographer.mapping.proto.PoseGraph)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .cartographer.mapping.proto.PoseGraph.Constraint constraint = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->constraint_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->constraint(static_cast<int>(i)), output);
}
// repeated .cartographer.mapping.proto.Trajectory trajectory = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->trajectory_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, this->trajectory(static_cast<int>(i)), output);
}
// repeated .cartographer.mapping.proto.PoseGraph.LandmarkPose landmark_poses = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->landmark_poses_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, this->landmark_poses(static_cast<int>(i)), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:cartographer.mapping.proto.PoseGraph)
}
::google::protobuf::uint8* PoseGraph::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:cartographer.mapping.proto.PoseGraph)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// repeated .cartographer.mapping.proto.PoseGraph.Constraint constraint = 2;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->constraint_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, this->constraint(static_cast<int>(i)), deterministic, target);
}
// repeated .cartographer.mapping.proto.Trajectory trajectory = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->trajectory_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, this->trajectory(static_cast<int>(i)), deterministic, target);
}
// repeated .cartographer.mapping.proto.PoseGraph.LandmarkPose landmark_poses = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->landmark_poses_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
5, this->landmark_poses(static_cast<int>(i)), deterministic, target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:cartographer.mapping.proto.PoseGraph)
return target;
}
size_t PoseGraph::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:cartographer.mapping.proto.PoseGraph)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// repeated .cartographer.mapping.proto.PoseGraph.Constraint constraint = 2;
{
unsigned int count = static_cast<unsigned int>(this->constraint_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->constraint(static_cast<int>(i)));
}
}
// repeated .cartographer.mapping.proto.Trajectory trajectory = 4;
{
unsigned int count = static_cast<unsigned int>(this->trajectory_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->trajectory(static_cast<int>(i)));
}
}
// repeated .cartographer.mapping.proto.PoseGraph.LandmarkPose landmark_poses = 5;
{
unsigned int count = static_cast<unsigned int>(this->landmark_poses_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->landmark_poses(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PoseGraph::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:cartographer.mapping.proto.PoseGraph)
GOOGLE_DCHECK_NE(&from, this);
const PoseGraph* source =
::google::protobuf::internal::DynamicCastToGenerated<const PoseGraph>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:cartographer.mapping.proto.PoseGraph)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:cartographer.mapping.proto.PoseGraph)
MergeFrom(*source);
}
}
void PoseGraph::MergeFrom(const PoseGraph& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:cartographer.mapping.proto.PoseGraph)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
constraint_.MergeFrom(from.constraint_);
trajectory_.MergeFrom(from.trajectory_);
landmark_poses_.MergeFrom(from.landmark_poses_);
}
void PoseGraph::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:cartographer.mapping.proto.PoseGraph)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PoseGraph::CopyFrom(const PoseGraph& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:cartographer.mapping.proto.PoseGraph)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PoseGraph::IsInitialized() const {
return true;
}
void PoseGraph::Swap(PoseGraph* other) {
if (other == this) return;
InternalSwap(other);
}
void PoseGraph::InternalSwap(PoseGraph* other) {
using std::swap;
constraint_.InternalSwap(&other->constraint_);
trajectory_.InternalSwap(&other->trajectory_);
landmark_poses_.InternalSwap(&other->landmark_poses_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata PoseGraph::GetMetadata() const {
protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_cartographer_2fmapping_2fproto_2fpose_5fgraph_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// PoseGraph
// repeated .cartographer.mapping.proto.PoseGraph.Constraint constraint = 2;
int PoseGraph::constraint_size() const {
return constraint_.size();
}
void PoseGraph::clear_constraint() {
constraint_.Clear();
}
const ::cartographer::mapping::proto::PoseGraph_Constraint& PoseGraph::constraint(int index) const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.constraint)
return constraint_.Get(index);
}
::cartographer::mapping::proto::PoseGraph_Constraint* PoseGraph::mutable_constraint(int index) {
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.constraint)
return constraint_.Mutable(index);
}
::cartographer::mapping::proto::PoseGraph_Constraint* PoseGraph::add_constraint() {
// @@protoc_insertion_point(field_add:cartographer.mapping.proto.PoseGraph.constraint)
return constraint_.Add();
}
::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::PoseGraph_Constraint >*
PoseGraph::mutable_constraint() {
// @@protoc_insertion_point(field_mutable_list:cartographer.mapping.proto.PoseGraph.constraint)
return &constraint_;
}
const ::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::PoseGraph_Constraint >&
PoseGraph::constraint() const {
// @@protoc_insertion_point(field_list:cartographer.mapping.proto.PoseGraph.constraint)
return constraint_;
}
// repeated .cartographer.mapping.proto.Trajectory trajectory = 4;
int PoseGraph::trajectory_size() const {
return trajectory_.size();
}
void PoseGraph::clear_trajectory() {
trajectory_.Clear();
}
const ::cartographer::mapping::proto::Trajectory& PoseGraph::trajectory(int index) const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.trajectory)
return trajectory_.Get(index);
}
::cartographer::mapping::proto::Trajectory* PoseGraph::mutable_trajectory(int index) {
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.trajectory)
return trajectory_.Mutable(index);
}
::cartographer::mapping::proto::Trajectory* PoseGraph::add_trajectory() {
// @@protoc_insertion_point(field_add:cartographer.mapping.proto.PoseGraph.trajectory)
return trajectory_.Add();
}
::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::Trajectory >*
PoseGraph::mutable_trajectory() {
// @@protoc_insertion_point(field_mutable_list:cartographer.mapping.proto.PoseGraph.trajectory)
return &trajectory_;
}
const ::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::Trajectory >&
PoseGraph::trajectory() const {
// @@protoc_insertion_point(field_list:cartographer.mapping.proto.PoseGraph.trajectory)
return trajectory_;
}
// repeated .cartographer.mapping.proto.PoseGraph.LandmarkPose landmark_poses = 5;
int PoseGraph::landmark_poses_size() const {
return landmark_poses_.size();
}
void PoseGraph::clear_landmark_poses() {
landmark_poses_.Clear();
}
const ::cartographer::mapping::proto::PoseGraph_LandmarkPose& PoseGraph::landmark_poses(int index) const {
// @@protoc_insertion_point(field_get:cartographer.mapping.proto.PoseGraph.landmark_poses)
return landmark_poses_.Get(index);
}
::cartographer::mapping::proto::PoseGraph_LandmarkPose* PoseGraph::mutable_landmark_poses(int index) {
// @@protoc_insertion_point(field_mutable:cartographer.mapping.proto.PoseGraph.landmark_poses)
return landmark_poses_.Mutable(index);
}
::cartographer::mapping::proto::PoseGraph_LandmarkPose* PoseGraph::add_landmark_poses() {
// @@protoc_insertion_point(field_add:cartographer.mapping.proto.PoseGraph.landmark_poses)
return landmark_poses_.Add();
}
::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::PoseGraph_LandmarkPose >*
PoseGraph::mutable_landmark_poses() {
// @@protoc_insertion_point(field_mutable_list:cartographer.mapping.proto.PoseGraph.landmark_poses)
return &landmark_poses_;
}
const ::google::protobuf::RepeatedPtrField< ::cartographer::mapping::proto::PoseGraph_LandmarkPose >&
PoseGraph::landmark_poses() const {
// @@protoc_insertion_point(field_list:cartographer.mapping.proto.PoseGraph.landmark_poses)
return landmark_poses_;
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace proto
} // namespace mapping
} // namespace cartographer
// @@protoc_insertion_point(global_scope)
| 39.778925 | 170 | 0.735625 | Rose-Hulman-Rover-Team |
5218ced965d0b9d1c15bfad696ab2303f3afdf7c | 3,085 | hpp | C++ | include/mindsp/window.hpp | nsdrozario/guitar-amp | bd11d613e11893632d51807fb4b7b08a348d3528 | [
"MIT"
] | 1 | 2022-03-31T18:35:26.000Z | 2022-03-31T18:35:26.000Z | include/mindsp/window.hpp | nsdrozario/granite-amp | 2f797581f36f733048c7c9c98bdfff82d6fbe1b9 | [
"MIT"
] | 6 | 2021-07-06T23:21:30.000Z | 2021-08-15T03:26:27.000Z | include/mindsp/window.hpp | nsdrozario/granite-amp | 2f797581f36f733048c7c9c98bdfff82d6fbe1b9 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Nathaniel D'Rozario
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 <cmath>
namespace mindsp {
namespace window {
/**
*
* Hann window
* @param n window index
* @param N window size
*
*/
inline float hann(std::size_t n, std::size_t N) {
float sqrt_hann = std::sin(3.141592654f * n / (N-1));
return sqrt_hann * sqrt_hann;
}
/**
*
* Bartlett window (triangular window with L=N)
* @param n window index
* @param N window size
*
*/
inline float bartlett(std::size_t n, std::size_t N) {
return 1.0f - std::abs( (n-(N*0.5)) / (N * 0.5) );
}
/**
*
* Generalized cosine-sum window
* @param n window index
* @param N window size
* @param a Array of coefficients
* @param k Size of coefficient array
*
*/
inline float cosine_sum(std::size_t n, std::size_t N, float *a, std::size_t k) {
float out = 0.0f;
for (std::size_t i = 0; i < k; i++) {
float term = a[i] * std::cos(2.0f * i * 3.1415927f * n / N);
if (i % 2 == 1) {
out -= term;
} else {
out += term;
}
}
return out;
};
/**
*
* Blackman-Harris window
* @param n window index
* @param N window size
*
*/
inline float blackman_harris(std::size_t n, std::size_t N) {
float a[4] = {0.35875, 0.48829, 0.14128, 0.01168};
return cosine_sum(n, N, a, 4);
}
/**
*
* Hamming window
* @param n window index
* @param N window size
*
*/
inline float hamming(std::size_t n, std::size_t N) {
float a[2] = {0.54, 0.46};
return cosine_sum(n, N, a, 2);
}
}
} | 30.85 | 88 | 0.552026 | nsdrozario |
521c417b1daff8a28a7d0f6005b8e10ae6c179df | 547 | cpp | C++ | NWNXLib/API/Linux/API/SJournalEntry.cpp | acaos/nwnxee-unified | 0e4c318ede64028c1825319f39c012e168e0482c | [
"MIT"
] | 1 | 2019-06-04T04:30:24.000Z | 2019-06-04T04:30:24.000Z | NWNXLib/API/Linux/API/SJournalEntry.cpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | null | null | null | NWNXLib/API/Linux/API/SJournalEntry.cpp | presscad/nwnee | 0f36b281524e0b7e9796bcf30f924792bf9b8a38 | [
"MIT"
] | 1 | 2019-10-20T07:54:45.000Z | 2019-10-20T07:54:45.000Z | #include "SJournalEntry.hpp"
#include "API/Functions.hpp"
#include "Platform/ASLR.hpp"
namespace NWNXLib {
namespace API {
SJournalEntry::~SJournalEntry()
{
SJournalEntry__SJournalEntryDtor(this);
}
void SJournalEntry__SJournalEntryDtor(SJournalEntry* thisPtr)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(SJournalEntry*, int);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::SJournalEntry__SJournalEntryDtor);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
func(thisPtr, 2);
}
}
}
| 21.88 | 105 | 0.760512 | acaos |
521ec656a1d0999a32474e11f55f465aa8c60c07 | 3,131 | cpp | C++ | source/axPython.cpp | alxarsenault/axServer | cb5edf5a3d3010abe182e8c8b61bafbb8f3800f4 | [
"MIT"
] | 1 | 2015-10-18T07:48:20.000Z | 2015-10-18T07:48:20.000Z | source/axPython.cpp | alxarsenault/axServer | cb5edf5a3d3010abe182e8c8b61bafbb8f3800f4 | [
"MIT"
] | null | null | null | source/axPython.cpp | alxarsenault/axServer | cb5edf5a3d3010abe182e8c8b61bafbb8f3800f4 | [
"MIT"
] | null | null | null | //#include <Python.h>
//#include <iostream>
//#include <unistd.h>
//// https://docs.python.org/2/extending/embedding.html
//#include <string>
//#include <vector>
//#include <stdio.h>
#include "axPython.h"
axPython::axPython(int argc, char* argv[])
{
// std::cout << "axPython." << std::endl;
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PySys_SetArgv(argc, argv); // must call this to get sys.argv and relative imports
// /usr/lib/libpython2.7.dylib
// char pySearchPath[] = "/usr/bin/python2.7";
//char pySearchPath[] = "/usr/lib/libpython2.7.dylib";
// char pySearchPath[] = "/Library/Python/2.7/";///site-packages";
// Py_SetPythonHome(pySearchPath);
InsertCurrentAppDirectory();
// std::cerr << "PATH" << Py_GetPath() << std::endl;
}
axPython::~axPython()
{
Py_Finalize();
}
void axPython::InsertCurrentAppDirectory()
{
char* buffer = new char[1024];
getcwd(buffer, 1024);
std::string app_path(buffer);
delete buffer;
app_path += "/";
// std::cout << app_path << std::endl;
std::string insert_path("import sys \nsys.path.insert(1,'"+ app_path + "')\n ");
PyRun_SimpleString(insert_path.c_str());
}
void axPython::InsertFolder(const std::string& folder_path)
{
std::string insert_path("import sys \nsys.path.insert(1,'"+ folder_path + "')\n ");
PyRun_SimpleString(insert_path.c_str());
}
void axPython::LoadModule(const std::string& module_name)
{
PyObject* moduleString = PyString_FromString((char*)module_name.c_str());
_module = PyImport_Import(moduleString);
Py_DECREF(moduleString);
if(_module == nullptr)
{
std::cerr << "ERROR : " << std::endl;
PyErr_Print();
exit(1);
}
}
std::string axPython::CallFunction(const std::string& fct_name, const std::vector<std::string>& args)
{
PyObject* myFunction = PyObject_GetAttrString(_module, (char*)fct_name.c_str());
//PyObject* fctArg = PyObject_GetAttrString(_module, (char*)fct_name.c_str());
// PyObject* fct_args = NULL;
// if(args.size())
// {
// std::cout << "Add argument" << std::endl;
// fct_args = PyObject_GetAttrString(_module, (char*)args[0].c_str());
// }
// PyObject* tuple_args = PyTuple_Pack(1, fct_args);
PyObject* pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs, 0, PyString_FromString(args[0].c_str()));
PyObject* myResult = PyObject_CallObject(myFunction, pArgs);
PyObject* objectsRepresentation = PyObject_Repr(myResult);
const char* s = PyString_AsString(objectsRepresentation);
std::string answer(s);
answer = answer.substr(answer.find_first_of("'") + 1, answer.length());
answer = answer.substr(0, answer.find_last_of("'"));
return answer;
}
//
//private:
// PyObject* _module;
//};
//int main(int argc, char *argv[])
//{
// axPython python;
// python.LoadModule("ttt");
//
// std::vector<std::string> args;
// std::string answer = python.CallFunction("StringTest", args);
//
// std::cout << answer << std::endl;
//
// return 0;
//}
| 26.533898 | 101 | 0.634941 | alxarsenault |
52208f052772c1c11b1322c7e8e002e64b4f5d10 | 5,959 | cpp | C++ | utility/DebugLog.cpp | salsanci/YRShell | 7a6073651d2ddef0c258c9943a5f9fd88068a561 | [
"MIT"
] | 2 | 2017-09-09T15:18:44.000Z | 2020-02-02T17:08:40.000Z | utility/DebugLog.cpp | salsanci/YRShell | 7a6073651d2ddef0c258c9943a5f9fd88068a561 | [
"MIT"
] | 39 | 2017-10-19T00:44:17.000Z | 2019-01-19T19:20:24.000Z | utility/DebugLog.cpp | salsanci/YRShell | 7a6073651d2ddef0c258c9943a5f9fd88068a561 | [
"MIT"
] | null | null | null | #include "DebugLog.h"
void DebugLog::printHexLine( const char* P, int len) {
int i, j;
memset(c_buf, ' ', sizeof(c_buf)-1);
c_buf[ sizeof( c_buf) - 1] = '\0';
for( j = i = 0; i < 16; P++, i++ ) {
if( i >= len) {
print( " ");
} else {
c_buf[ j++] = *P > 0x20 && *P < 0x7E ? *P : '.';
outX(*P, 2);
print( " ");
}
if( i == 7) {
print( " ");
c_buf[ j++] = ' ';
c_buf[ j++] = ' ';
} else if( i == 3 || i == 11) {
print( " ");
c_buf[ j++] = ' ';
}
}
print( c_buf);
print( "\r\n");
}
void DebugLog::flush( ) {
for( uint16_t i = 1; i && valueAvailable(); i++ ) {
}
}
void DebugLog::out( const char c) {
if( m_dq.spaceAvailable( 24)) {
m_dq.put( c);
} else {
m_dq.reset();
out("\r\n\nLOG DATA DROPPED\r\n\n");
}
}
void DebugLog::out( const char* s) {
while( *s != '\0') {
out( *s++);
}
}
void DebugLog::out( uint32_t v, uint32_t n) {
YRShellInterpreter::unsignedToString( v, n, m_buf);
out( m_buf);
}
void DebugLog::outX( uint32_t v, uint32_t n) {
YRShellInterpreter::unsignedToStringX( v, n, m_buf);
out( m_buf);
}
void DebugLog::outPaddedStr( const char* p, uint32_t len) {
size_t sz = strlen( p);
if( sz > len) {
out( p + sz - len);
} else {
len -= sz;
while( len-- > 0) {
out( ' ');
}
out( p);
}
}
void DebugLog::printh( const char* file, uint32_t line) {
uint32_t t = (uint32_t) millis();
out( t);
out( ' ');
out( t - m_lastTime);
out( ' ');
m_lastTime = t;
outPaddedStr( file, 20);
out( ' ');
out( line, 4);
out( ' ');
}
void DebugLog::printu( uint32_t v) {
out( v);
out( ' ');
}
void DebugLog::printx( uint32_t v) {
outX( v);
out( ' ');
}
void DebugLog::printm( const char* m) {
prints( m);
out( "\r\n");
}
void DebugLog::prints( const char* m) {
out( '"');
out( m);
out( '"');
}
void DebugLog::print( const char* m) {
out( m);
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, const char* message) {
if( m_mask & mask) {
printh( file, line);
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, const char* m, const char* message) {
if( m_mask & mask) {
printh( file, line);
prints( m);
out( ' ');
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, const char* m, const char* m1, const char* message) {
if( m_mask & mask) {
printh( file, line);
prints( m);
out( ' ');
prints( m1);
out( ' ');
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, uint32_t v1, const char* m, const char* message) {
if( m_mask & mask) {
printh( file, line);
printu( v1);
prints( m);
out( ' ');
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, const char* m, const char* message) {
if( m_mask & mask) {
printh( file, line);
printu( v1);
printu( v2);
prints( m);
out( ' ');
printm( message);
}
}
void DebugLog::printLog( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, const char* m) {
if( m_mask & mask) {
printh( file, line);
printu( v1);
printu( v2);
outPaddedStr( m, 64);
out( "\r\n");
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, uint32_t v1, const char* message) {
if( m_mask & mask) {
printh( file, line);
printu(v1);
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, const char* message) {
if( m_mask & mask) {
printh( file, line);
printu(v1);
printu(v2);
printm( message);
}
}
void DebugLog::print( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, uint32_t v3, const char* message) {
if( m_mask & mask) {
printh( file, line);
printu(v1);
printu(v2);
printu(v3);
printm( message);
}
}
void DebugLog::printX( const char* file, uint32_t line, uint32_t mask, uint32_t v1, const char* m, const char* message) {
if( m_mask & mask) {
printh( file, line);
printx( v1);
print( m);
out( ' ');
printm( message);
}
}
void DebugLog::printX( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, const char* m, const char* message) {
if( m_mask & mask) {
printh( file, line);
printx( v1);
printx( v2);
print( m);
out( ' ');
printm( message);
}
}
void DebugLog::printX( const char* file, uint32_t line, uint32_t mask, uint32_t v1, const char* message) {
if( m_mask & mask) {
printh( file, line);
printx(v1);
printm( message);
}
}
void DebugLog::printX( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, const char* message) {
if( m_mask & mask) {
printh( file, line);
printx(v1);
printx(v2);
printm( message);
}
}
void DebugLog::printX( const char* file, uint32_t line, uint32_t mask, uint32_t v1, uint32_t v2, uint32_t v3, const char* message) {
if( m_mask & mask) {
printh( file, line);
printx(v1);
printx(v2);
printx(v3);
printm( message);
}
}
void DebugLog::printHex( const char* P, int len) {
for( ; len > 0; P += 16, len -= 16) {
printHexLine( P, len);
}
}
void DebugLog::printHex( String &s) {
printHex( s.c_str(), s.length());
}
| 26.021834 | 134 | 0.523074 | salsanci |
522168d31a350d40e16c883515a64b194aed437f | 3,136 | cpp | C++ | 044_Scattering (light)/Renders/Material.cpp | HansWord/HansMemory | ae74b8d4f5ebc749508ce43250a604e364950203 | [
"MIT"
] | null | null | null | 044_Scattering (light)/Renders/Material.cpp | HansWord/HansMemory | ae74b8d4f5ebc749508ce43250a604e364950203 | [
"MIT"
] | null | null | null | 044_Scattering (light)/Renders/Material.cpp | HansWord/HansMemory | ae74b8d4f5ebc749508ce43250a604e364950203 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Material.h"
Material::Material()
: shader(NULL)
, diffuseMap(NULL), specularMap(NULL), normalMap(NULL)
, bShaderDelete(false)
{
buffer = new Buffer();
}
Material::Material(wstring shaderFile)
: diffuseMap(NULL), specularMap(NULL), normalMap(NULL)
{
assert(shaderFile.length() > 0);
buffer = new Buffer();
bShaderDelete = true;
shader = new Shader(shaderFile);
}
Material::~Material()
{
if (bShaderDelete == true)
SAFE_DELETE(shader);
SAFE_DELETE(diffuseMap);
SAFE_DELETE(specularMap);
}
void Material::SetShader(string file)
{
SetShader(String::ToWString(file));
}
void Material::SetShader(wstring file)
{
if (bShaderDelete == true)
SAFE_DELETE(shader);
bShaderDelete = false;
if (file.length() > 0)
{
shader = new Shader(file);
bShaderDelete = true;
}
}
void Material::SetShader(Shader * shader)
{
if (bShaderDelete == true)
SAFE_DELETE(shader);
this->shader = shader;
bShaderDelete = false;
}
void Material::SetDiffuseMap(string file, D3DX11_IMAGE_LOAD_INFO * info)
{
SetDiffuseMap(String::ToWString(file), info);
}
void Material::SetDiffuseMap(wstring file, D3DX11_IMAGE_LOAD_INFO * info)
{
SAFE_DELETE(diffuseMap);
diffuseMap = new Texture(file, info);
}
void Material::SetSpecularMap(string file, D3DX11_IMAGE_LOAD_INFO * info)
{
SetSpecularMap(String::ToWString(file), info);
}
void Material::SetSpecularMap(wstring file, D3DX11_IMAGE_LOAD_INFO * info)
{
SAFE_DELETE(specularMap);
specularMap = new Texture(file, info);
}
void Material::SetNormalMap(string file, D3DX11_IMAGE_LOAD_INFO * info)
{
SetNormalMap(String::ToWString(file), info);
}
void Material::SetNormalMap(wstring file, D3DX11_IMAGE_LOAD_INFO * info)
{
SAFE_DELETE(normalMap);
normalMap = new Texture(file, info);
}
void Material::PSSetBuffer()
{
if (shader != NULL)
shader->Render();
UINT slot = 0;
if (diffuseMap != NULL)
{
diffuseMap->SetShaderResource(slot);
diffuseMap->SetShaderSampler(slot);
}
else
{
Texture::SetBlankShaderResource(slot);
Texture::SetBlankSamplerState(slot);
}
slot = 1;
if (specularMap != NULL)
{
specularMap->SetShaderResource(slot);
specularMap->SetShaderSampler(slot);
}
else
{
Texture::SetBlankShaderResource(slot);
Texture::SetBlankSamplerState(slot);
}
slot = 2;
if (normalMap != NULL)
{
normalMap->SetShaderResource(slot);
normalMap->SetShaderSampler(slot);
}
else
{
Texture::SetBlankShaderResource(slot);
Texture::SetBlankSamplerState(slot);
}
buffer->SetPSBuffer(1);
}
void Material::Clone(void ** clone)
{
Material* material = new Material();
material->name = this->name;
if(this->shader != NULL)
material->SetShader(this->shader->GetFile());
material->SetDiffuse(*this->GetDiffuse());
material->SetSpecular(*this->GetSpecular());
if (this->diffuseMap != NULL)
material->SetDiffuseMap(this->diffuseMap->GetFile());
if (this->specularMap != NULL)
material->SetSpecularMap(this->specularMap->GetFile());
if (this->normalMap != NULL)
material->SetNormalMap(this->normalMap->GetFile());
material->SetShininess(*this->GetShininess());
*clone = material;
}
| 18.778443 | 74 | 0.71588 | HansWord |
5221e166d95f0dba1d81287641d9b5c6783d3b87 | 13,581 | cc | C++ | src/vnsw/agent/ovs_tor_agent/ovsdb_client/vlan_port_binding_ovsdb.cc | madkiss/contrail-controller | 17f622dfe99f8ab4163436399e80f95dd564814c | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/ovs_tor_agent/ovsdb_client/vlan_port_binding_ovsdb.cc | madkiss/contrail-controller | 17f622dfe99f8ab4163436399e80f95dd564814c | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/ovs_tor_agent/ovsdb_client/vlan_port_binding_ovsdb.cc | madkiss/contrail-controller | 17f622dfe99f8ab4163436399e80f95dd564814c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
extern "C" {
#include <ovsdb_wrapper.h>
};
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovsdb_client.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <physical_switch_ovsdb.h>
#include <logical_switch_ovsdb.h>
#include <physical_port_ovsdb.h>
#include <vlan_port_binding_ovsdb.h>
#include <vm_interface_ksync.h>
#include <oper/vn.h>
#include <oper/interface_common.h>
#include <oper/physical_device.h>
#include <oper/physical_device_vn.h>
#include <ovsdb_types.h>
using OVSDB::OvsdbDBEntry;
using OVSDB::VlanPortBindingEntry;
using OVSDB::VlanPortBindingTable;
using OVSDB::PhysicalSwitchEntry;
using OVSDB::PhysicalPortEntry;
using OVSDB::LogicalSwitchEntry;
using OVSDB::OvsdbClient;
using OVSDB::OvsdbClientSession;
VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
const std::string &physical_device, const std::string &physical_port,
uint16_t vlan_tag, const std::string &logical_switch) :
OvsdbDBEntry(table_), logical_switch_name_(logical_switch),
physical_port_name_(physical_port), physical_device_name_(physical_device),
vlan_(vlan_tag) {
}
VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
const VlanLogicalInterface *entry) : OvsdbDBEntry(table_),
logical_switch_name_(), physical_port_name_(),
physical_device_name_(""), vlan_(entry->vlan()) {
RemotePhysicalInterface *phy_intf = dynamic_cast<RemotePhysicalInterface *>
(entry->physical_interface());
assert(phy_intf);
physical_port_name_ = phy_intf->display_name();
physical_device_name_ = phy_intf->physical_device()->name();
}
VlanPortBindingEntry::VlanPortBindingEntry(VlanPortBindingTable *table,
const VlanPortBindingEntry *key) : OvsdbDBEntry(table),
logical_switch_name_(key->logical_switch_name_),
physical_port_name_(key->physical_port_name_),
physical_device_name_(key->physical_device_name_), vlan_(key->vlan_) {
}
void VlanPortBindingEntry::PreAddChange() {
if (!logical_switch_name_.empty()) {
LogicalSwitchTable *l_table =
table_->client_idl()->logical_switch_table();
LogicalSwitchEntry ls_key(l_table, logical_switch_name_.c_str());
logical_switch_ = l_table->GetReference(&ls_key);
} else {
logical_switch_ = NULL;
}
}
void VlanPortBindingEntry::PostDelete() {
logical_switch_ = NULL;
}
void VlanPortBindingEntry::AddMsg(struct ovsdb_idl_txn *txn) {
PhysicalPortTable *p_table = table_->client_idl()->physical_port_table();
PhysicalPortEntry key(p_table, physical_device_name_, physical_port_name_);
physical_port_ = p_table->GetReference(&key);
PhysicalPortEntry *port =
static_cast<PhysicalPortEntry *>(physical_port_.get());
if (!logical_switch_name_.empty()) {
port->AddBinding(vlan_,
static_cast<LogicalSwitchEntry *>(logical_switch_.get()));
OVSDB_TRACE(Trace, "Adding port vlan binding port " +
physical_port_name_ + " vlan " + integerToString(vlan_) +
" to Logical Switch " + logical_switch_name_);
} else {
OVSDB_TRACE(Trace, "Deleting port vlan binding port " +
physical_port_name_ + " vlan " + integerToString(vlan_));
port->DeleteBinding(vlan_, NULL);
}
// Don't trigger update for stale entries
if (!stale()) {
port->TriggerUpdate();
}
}
void VlanPortBindingEntry::ChangeMsg(struct ovsdb_idl_txn *txn) {
PhysicalPortEntry *port =
static_cast<PhysicalPortEntry *>(physical_port_.get());
OVSDB_TRACE(Trace, "Deleting port vlan binding port " +
physical_port_name_ + " vlan " + integerToString(vlan_));
port->DeleteBinding(vlan_, NULL);
AddMsg(txn);
}
void VlanPortBindingEntry::DeleteMsg(struct ovsdb_idl_txn *txn) {
if (!physical_port_) {
return;
}
PhysicalPortEntry *port =
static_cast<PhysicalPortEntry *>(physical_port_.get());
OVSDB_TRACE(Trace, "Deleting port vlan binding port " +
physical_port_name_ + " vlan " + integerToString(vlan_));
port->DeleteBinding(vlan_,
static_cast<LogicalSwitchEntry *>(logical_switch_.get()));
port->TriggerUpdate();
}
bool VlanPortBindingEntry::Sync(DBEntry *db_entry) {
VlanLogicalInterface *entry =
static_cast<VlanLogicalInterface *>(db_entry);
std::string ls_name;
boost::uuids::uuid vmi_uuid;
bool change = false;
if (entry->vm_interface()) {
vmi_uuid = entry->vm_interface()->GetUuid();
}
if (entry->vm_interface() && entry->vm_interface()->vn()) {
ls_name = UuidToString(entry->vm_interface()->vn()->GetUuid());
}
if (vmi_uuid_ != vmi_uuid) {
vmi_uuid_ = vmi_uuid;
change = true;
}
if (ls_name != logical_switch_name_) {
logical_switch_name_ = ls_name;
change = true;
}
return change;
}
bool VlanPortBindingEntry::IsLess(const KSyncEntry &entry) const {
const VlanPortBindingEntry &vps_entry =
static_cast<const VlanPortBindingEntry&>(entry);
if (vlan_ != vps_entry.vlan_)
return vlan_ < vps_entry.vlan_;
if (physical_device_name_ != vps_entry.physical_device_name_)
return physical_device_name_ < vps_entry.physical_device_name_;
return physical_port_name_ < vps_entry.physical_port_name_;
}
KSyncEntry *VlanPortBindingEntry::UnresolvedReference() {
PhysicalSwitchTable *ps_table =
table_->client_idl()->physical_switch_table();
PhysicalSwitchEntry ps_key(ps_table, physical_device_name_.c_str());
PhysicalSwitchEntry *p_switch =
static_cast<PhysicalSwitchEntry *>(ps_table->GetReference(&ps_key));
if (!p_switch->IsResolved()) {
OVSDB_TRACE(Trace, "Physical Switch unavailable for Port Vlan Binding "+
physical_port_name_ + " vlan " + integerToString(vlan_) +
" to Logical Switch " + logical_switch_name_);
return p_switch;
}
PhysicalPortTable *p_table = table_->client_idl()->physical_port_table();
PhysicalPortEntry key(p_table, physical_device_name_, physical_port_name_);
PhysicalPortEntry *p_port =
static_cast<PhysicalPortEntry *>(p_table->GetReference(&key));
if (!p_port->IsResolved()) {
OVSDB_TRACE(Trace, "Physical Port unavailable for Port Vlan Binding " +
physical_port_name_ + " vlan " + integerToString(vlan_) +
" to Logical Switch " + logical_switch_name_);
return p_port;
}
// check for VMI only if entry is not stale marked.
if (!stale()) {
VMInterfaceKSyncObject *vm_intf_table =
table_->client_idl()->vm_interface_table();
VMInterfaceKSyncEntry vm_intf_key(vm_intf_table, vmi_uuid_);
VMInterfaceKSyncEntry *vm_intf = static_cast<VMInterfaceKSyncEntry *>(
vm_intf_table->GetReference(&vm_intf_key));
if (!vm_intf->IsResolved()) {
OVSDB_TRACE(Trace, "VM Interface unavailable for Port Vlan Binding " +
physical_port_name_ + " vlan " + integerToString(vlan_) +
" to Logical Switch " + logical_switch_name_);
return vm_intf;
} else if (logical_switch_name_.empty()) {
// update latest name after resolution.
logical_switch_name_ = vm_intf->vn_name();
}
}
if (!logical_switch_name_.empty()) {
// Check only if logical switch name is present.
LogicalSwitchTable *l_table =
table_->client_idl()->logical_switch_table();
LogicalSwitchEntry ls_key(l_table, logical_switch_name_.c_str());
LogicalSwitchEntry *ls_entry =
static_cast<LogicalSwitchEntry *>(l_table->GetReference(&ls_key));
if (!ls_entry->IsResolved()) {
OVSDB_TRACE(Trace, "Logical Switch unavailable for Port Vlan "
"Binding " + physical_port_name_ + " vlan " +
integerToString(vlan_) + " to Logical Switch " +
logical_switch_name_);
return ls_entry;
}
}
return NULL;
}
const std::string &VlanPortBindingEntry::logical_switch_name() const {
return logical_switch_name_;
}
const std::string &VlanPortBindingEntry::physical_port_name() const {
return physical_port_name_;
}
const std::string &VlanPortBindingEntry::physical_device_name() const {
return physical_device_name_;
}
uint16_t VlanPortBindingEntry::vlan() const {
return vlan_;
}
VlanPortBindingTable::VlanPortBindingTable(OvsdbClientIdl *idl) :
OvsdbDBObject(idl, true) {
}
VlanPortBindingTable::~VlanPortBindingTable() {
}
void VlanPortBindingTable::OvsdbNotify(OvsdbClientIdl::Op op,
struct ovsdb_idl_row *row) {
}
KSyncEntry *VlanPortBindingTable::Alloc(const KSyncEntry *key, uint32_t index) {
const VlanPortBindingEntry *k_entry =
static_cast<const VlanPortBindingEntry *>(key);
VlanPortBindingEntry *entry = new VlanPortBindingEntry(this, k_entry);
return entry;
}
KSyncEntry *VlanPortBindingTable::DBToKSyncEntry(const DBEntry* db_entry) {
const VlanLogicalInterface *entry =
static_cast<const VlanLogicalInterface *>(db_entry);
VlanPortBindingEntry *key = new VlanPortBindingEntry(this, entry);
return static_cast<KSyncEntry *>(key);
}
OvsdbDBEntry *VlanPortBindingTable::AllocOvsEntry(struct ovsdb_idl_row *row) {
return NULL;
}
KSyncDBObject::DBFilterResp VlanPortBindingTable::OvsdbDBEntryFilter(
const DBEntry *entry) {
const VlanLogicalInterface *l_port =
dynamic_cast<const VlanLogicalInterface *>(entry);
if (l_port == NULL) {
// Ignore entries other than VLanLogicalInterface.
return DBFilterIgnore;
}
// Logical interface without vm interface is incomplete entry
// for ovsdb, trigger delete.
if (l_port->vm_interface() == NULL) {
OVSDB_TRACE(Trace, "VM Interface Unavialable, Deleting Logical "
"Port " + l_port->name());
return DBFilterDelete;
}
// Since we need physical port name and device name as key, ignore entry
// if physical port or device is not yet present.
RemotePhysicalInterface *phy_intf = dynamic_cast<RemotePhysicalInterface *>
(l_port->physical_interface());
if (phy_intf == NULL) {
OVSDB_TRACE(Trace, "Ignoring Port Vlan Binding due to physical port "
"unavailablity Logical port = " + l_port->name());
return DBFilterIgnore; // TODO(Prabhjot) check if Delete is required.
}
if (phy_intf->physical_device() == NULL) {
OVSDB_TRACE(Trace, "Ignoring Port Vlan Binding due to device "
"unavailablity Logical port = " + l_port->name());
return DBFilterIgnore; // TODO(Prabhjot) check if Delete is required.
}
return DBFilterAccept;
}
/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
class VlanPortBindingSandeshTask : public Task {
public:
VlanPortBindingSandeshTask(std::string resp_ctx, const std::string &ip,
uint32_t port) :
Task((TaskScheduler::GetInstance()->GetTaskId("Agent::KSync")), 0),
resp_(new OvsdbVlanPortBindingResp()), resp_data_(resp_ctx),
ip_(ip), port_(port) {
}
virtual ~VlanPortBindingSandeshTask() {}
virtual bool Run() {
std::vector<OvsdbVlanPortBindingEntry> bindings;
OvsdbClient *ovsdb_client = Agent::GetInstance()->ovsdb_client();
OvsdbClientSession *session;
if (ip_.empty()) {
session = ovsdb_client->NextSession(NULL);
} else {
boost::system::error_code ec;
Ip4Address ip_addr = Ip4Address::from_string(ip_, ec);
session = ovsdb_client->FindSession(ip_addr, port_);
}
if (session != NULL && session->client_idl() != NULL) {
VlanPortBindingTable *table =
session->client_idl()->vlan_port_table();
VlanPortBindingEntry *entry =
static_cast<VlanPortBindingEntry *>(table->Next(NULL));
while (entry != NULL) {
OvsdbVlanPortBindingEntry oentry;
oentry.set_state(entry->StateString());
oentry.set_physical_port(entry->physical_port_name());
oentry.set_physical_device(entry->physical_device_name());
oentry.set_logical_switch(entry->logical_switch_name());
oentry.set_vlan(entry->vlan());
bindings.push_back(oentry);
entry = static_cast<VlanPortBindingEntry *>(table->Next(entry));
}
}
resp_->set_bindings(bindings);
SendResponse();
return true;
}
private:
void SendResponse() {
resp_->set_context(resp_data_);
resp_->set_more(false);
resp_->Response();
}
OvsdbVlanPortBindingResp *resp_;
std::string resp_data_;
std::string ip_;
uint32_t port_;
DISALLOW_COPY_AND_ASSIGN(VlanPortBindingSandeshTask);
};
void OvsdbVlanPortBindingReq::HandleRequest() const {
VlanPortBindingSandeshTask *task =
new VlanPortBindingSandeshTask(context(), get_session_remote_ip(),
get_session_remote_port());
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Enqueue(task);
}
| 37.106557 | 82 | 0.667698 | madkiss |
5222c1245620847883752cf0b2e098c5618357f9 | 1,175 | cpp | C++ | 0023-merge-k-sorted-lists.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | 106 | 2019-06-08T15:23:45.000Z | 2020-04-04T17:56:54.000Z | 0023-merge-k-sorted-lists.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | null | null | null | 0023-merge-k-sorted-lists.cpp | Jamesweng/leetcode | 1711a2a0e31d831e40137203c9abcba0bf56fcad | [
"Apache-2.0"
] | 3 | 2019-07-13T05:51:29.000Z | 2020-04-04T17:56:57.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool comp(const ListNode* a, const ListNode* b) {
return a->val > b->val;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode*> heaps;
for (int i = 0; i < lists.size(); ++i) {
ListNode* h = lists[i];
if (h == NULL) continue;
heaps.push_back(h);
push_heap(heaps.begin(), heaps.end(), comp);
}
ListNode* ans = NULL, *p = NULL;
while (heaps.size() > 0) {
pop_heap(heaps.begin(), heaps.end(), comp);
ListNode*& h = heaps.back();
if (ans == NULL) {
ans = h;
p = h;
} else {
p->next = h;
p = p->next;
}
h = h->next;
if (h != NULL) {
push_heap(heaps.begin(), heaps.end(), comp);
} else {
heaps.pop_back();
}
}
return ans;
}
};
| 25.543478 | 60 | 0.417021 | Jamesweng |
5222c5bcff8285f9c5fc191347f390ccaf6533e9 | 1,798 | cc | C++ | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_TimeStepMapperTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_TimeStepMapperTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_dal/dal_TimeStepMapperTest.cc | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE pcraster dal time_step_mapper
#include <boost/test/unit_test.hpp>
#include "dal_TimeStepMapper.h"
#include "dal_MathUtils.h"
BOOST_AUTO_TEST_CASE(test)
{
using namespace dal;
// Dataset A:
// 1 - 28
// 20060201 - 20060228 (days)
//
// Dataset B:
// 1 - 365
// 20060101 - 20061231 (days)
//
// Common dimension:
// 20060101 - 20061231 (days)
namespace bp = boost::posix_time;
namespace bg = boost::gregorian;
bp::ptime time;
time = bp::ptime(bg::date(2006, boost::gregorian::Feb, 1),
bp::time_duration(0, 0, 0, 0));
bp::time_duration duration(24, 0, 0, 0);
TimeStepMapper mapperA(1.0, time, duration);
BOOST_CHECK(mapperA.destination(1.0) == time);
BOOST_CHECK(mapperA.destination(2.0) == time + bg::days(1));
BOOST_CHECK(comparable(mapperA.source(time), 1.0));
BOOST_CHECK(comparable(mapperA.source(time + bg::days(1)), 2.0));
BOOST_CHECK(comparable(mapperA.source(time - bg::days(2)), -1.0));
time = bp::ptime(bg::date(2006, boost::gregorian::Jan, 1),
bp::time_duration(0, 0, 0, 0));
TimeStepMapper mapperB(1.0, time, duration);
BOOST_CHECK(comparable(mapperB.source(bp::ptime(
bg::date(2006, boost::gregorian::Dec, 31),
bp::time_duration(0, 0, 0, 0))), 365.0));
TimeStepMapper mapper(mapperA);
mapper |= mapperB;
BOOST_CHECK(comparable(mapper.source(bp::ptime(
bg::date(2006, boost::gregorian::Jan, 1),
bp::time_duration(0, 0, 0, 0))), 1.0));
BOOST_CHECK(comparable(mapper.source(bp::ptime(
bg::date(2006, boost::gregorian::Feb, 1),
bp::time_duration(0, 0, 0, 0))), 32.0));
BOOST_CHECK(comparable(mapper.source(bp::ptime(
bg::date(2006, boost::gregorian::Dec, 31),
bp::time_duration(0, 0, 0, 0))), 365.0));
}
| 30.474576 | 68 | 0.64238 | quanpands |
522328eb7705d95a3badd8068af28f86285f4bd8 | 5,360 | hpp | C++ | libiop/bcs/merkle_tree.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/bcs/merkle_tree.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/bcs/merkle_tree.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | /**@file
*****************************************************************************
Merkle tree interfaces.
Includes support for zero knowledge merkle trees, and set membership-proofs.
*****************************************************************************
* @author This file is part of libiop (see AUTHORS)
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBIOP_SNARK_COMMON_MERKLE_TREE_HPP_
#define LIBIOP_SNARK_COMMON_MERKLE_TREE_HPP_
#include <cstddef>
#include <numeric>
#include <vector>
#include <bits/stdc++.h>
#include "libiop/algebra/field_subset/field_subset.hpp"
#include "libiop/bcs/hashing/hashing.hpp"
namespace libiop {
/* Authentication paths for a set of positions */
template<typename hash_digest_type>
struct merkle_tree_set_membership_proof {
std::vector<hash_digest_type> auxiliary_hashes;
std::vector<zk_salt_type> randomness_hashes;
/* TODO: Write a test for this */
std::size_t size_in_bytes() const
{
return std::accumulate(this->auxiliary_hashes.begin(),
this->auxiliary_hashes.end(),
0,
[] (const std::size_t av, const hash_digest_type &h) {
return av + get_hash_size<hash_digest_type>(h); }) +
std::accumulate(this->randomness_hashes.begin(),
this->randomness_hashes.end(),
0,
[] (const std::size_t av, const zk_salt_type &h) {
return av + get_hash_size<zk_salt_type>(h); });
}
};
template<typename FieldT, typename hash_digest_type>
class merkle_tree {
protected:
bool constructed_;
std::vector<hash_digest_type> inner_nodes_;
std::size_t num_leaves_;
std::shared_ptr<leafhash<FieldT, hash_digest_type>> leaf_hasher_;
two_to_one_hash_function<hash_digest_type> node_hasher_;
std::size_t digest_len_bytes_;
bool make_zk_;
std::size_t num_zk_bytes_;
/* Each element will be hashed (individually) to produce a random hash digest. */
std::vector<zk_salt_type> zk_leaf_randomness_elements_;
void sample_leaf_randomness();
void compute_inner_nodes();
public:
/* Create a merkle tree with the given configuration.
If make_zk is true, 2 * security parameter random bytes will be appended to each leaf
before hashing, to prevent a low entropy leaf value from being inferred
from its hash. */
merkle_tree(const std::size_t num_leaves,
const std::shared_ptr<leafhash<FieldT, hash_digest_type>> &leaf_hasher,
const two_to_one_hash_function<hash_digest_type> &node_hasher,
const std::size_t digest_len_bytes,
const bool make_zk,
const std::size_t security_parameter);
/** This treats each leaf as a column.
* e.g. The ith leaf is the vector formed by leaf_contents[j][i] for all j */
void construct(const std::vector<std::shared_ptr<std::vector<FieldT>>> &leaf_contents);
// TODO: Remove this overload in favor of only using the former
void construct(const std::vector<std::vector<FieldT> > &leaf_contents);
/** Leaf contents is a table with `r` rows
* (`r` typically being the number of oracles)
* and (MT_num_leaves * coset_serialization_size) columns.
* Each MT leaf is the serialization of a table with `r` rows,
* and coset_serialization_size columns.
*
* This is done here rather than the BCS layer to avoid needing to copy the data,
* as this will take a significant amount of memory.
*/
void construct_with_leaves_serialized_by_cosets(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &leaf_contents,
size_t coset_serialization_size);
/** Takes in a set of query positions to input oracles to a domain of size:
* `num_leaves * coset_serialization_size`,
* and the associated evaluations for each query position.
*
* This function then serializes these evaluations into leaf entries.
* The rows of a leaf entry are the same as in the eva
*/
std::vector<std::vector<FieldT>> serialize_leaf_values_by_coset(
const std::vector<size_t> &query_positions,
const std::vector<std::vector<FieldT> > &query_responses,
const size_t coset_serialization_size) const;
hash_digest_type get_root() const;
merkle_tree_set_membership_proof<hash_digest_type> get_set_membership_proof(
const std::vector<std::size_t> &positions) const;
bool validate_set_membership_proof(
const hash_digest_type &root,
const std::vector<std::size_t> &positions,
const std::vector<std::vector<FieldT>> &leaf_contents,
const merkle_tree_set_membership_proof<hash_digest_type> &proof);
/* Returns number of two to one hashes */
size_t count_hashes_to_verify_set_membership_proof(
const std::vector<std::size_t> &positions) const;
std::size_t num_leaves() const;
std::size_t depth() const;
bool zk() const;
std::size_t num_total_bytes() const;
};
} // namespace libiop
#include "libiop/bcs/merkle_tree.tcc"
#endif // LIBIOP_SNARK_COMMON_MERKLE_TREE_HPP_
| 41.550388 | 91 | 0.649254 | alexander-zw |
5224e1fd85d9f81bf067d9db66b48c316fa4e594 | 1,608 | hpp | C++ | src/core/IList.hpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | 9 | 2019-05-14T01:07:08.000Z | 2020-11-12T01:46:11.000Z | src/core/IList.hpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | null | null | null | src/core/IList.hpp | clearlycloudy/concurrent | 243246f3244cfaf7ffcbfc042c69980d96f988e4 | [
"MIT"
] | null | null | null | #ifndef ILIST_HPP
#define ILIST_HPP
#include <utility>
#include <functional>
#include "IReclamation.hpp"
#include "IConcurrency.hpp"
#include "ISize.hpp"
template< class T, template< class, trait_reclamation > class ContainerType, trait_size list_size_, trait_concurrency list_concurrency_, trait_method list_method_, trait_reclamation reclam >
class IList final : public ContainerType<T, reclam> {
public:
//container and value traits
using container_type = ContainerType<T, reclam>;
using value_type = T;
using reference = T &;
using const_reference = T const &;
using size_type = typename container_type::_t_size;
//list traits
constexpr static trait_size list_size = list_size_;
constexpr static trait_concurrency list_concurrency = list_concurrency_;
constexpr static trait_method list_method = list_method_;
constexpr static trait_reclamation list_reclamation = reclam;
template< class... Args >
IList( Args... args ) : container_type( std::forward<Args>(args)... ) {}
~IList(){}
bool clear(){ return container_type::clear(); }
bool empty(){ return container_type::empty(); }
size_type size(){ return container_type::size(); }
bool add( const_reference item, size_t key ){ return container_type::add( item, key ); }
bool remove( value_type & item, size_t key ){ return container_type::remove( item, key ); }
bool contains( const_reference item, size_t key ){ return container_type::contains( item, key ); }
};
#endif
| 40.2 | 190 | 0.682836 | clearlycloudy |
522695134f9df5b1b3a00a5de9b09f76b7d66d1a | 1,536 | inl | C++ | Sources/SolarTears/Rendering/Vulkan/Scene/VulkanScene.inl | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | 4 | 2021-06-30T16:00:20.000Z | 2021-10-13T06:17:56.000Z | Sources/SolarTears/Rendering/Vulkan/Scene/VulkanScene.inl | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | Sources/SolarTears/Rendering/Vulkan/Scene/VulkanScene.inl | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | template<typename SubmeshCallback>
void RenderableScene::DrawStaticObjects(VkCommandBuffer commandBuffer, SubmeshCallback submeshCallback) const
{
for(uint32_t meshIndex = mStaticUniqueMeshSpan.Begin; meshIndex < mStaticUniqueMeshSpan.End; meshIndex++)
{
for(uint32_t submeshIndex = mSceneMeshes[meshIndex].FirstSubmeshIndex; submeshIndex < mSceneMeshes[meshIndex].AfterLastSubmeshIndex; submeshIndex++)
{
submeshCallback(commandBuffer, mSceneSubmeshes[submeshIndex].MaterialIndex);
vkCmdDrawIndexed(commandBuffer, mSceneSubmeshes[submeshIndex].IndexCount, mSceneMeshes[meshIndex].InstanceCount, mSceneSubmeshes[submeshIndex].FirstIndex, mSceneSubmeshes[submeshIndex].VertexOffset, 0);
}
}
}
template<typename MeshCallback, typename SubmeshCallback>
void RenderableScene::DrawNonStaticObjects(VkCommandBuffer commandBuffer, MeshCallback meshCallback, SubmeshCallback submeshCallback) const
{
for(uint32_t meshIndex = mNonStaticMeshSpan.Begin; meshIndex < mNonStaticMeshSpan.End; meshIndex++)
{
meshCallback(commandBuffer, mSceneMeshes[meshIndex].PerObjectDataIndex);
for(uint32_t submeshIndex = mSceneMeshes[meshIndex].FirstSubmeshIndex; submeshIndex < mSceneMeshes[meshIndex].AfterLastSubmeshIndex; submeshIndex++)
{
submeshCallback(commandBuffer, mSceneSubmeshes[submeshIndex].MaterialIndex);
vkCmdDrawIndexed(commandBuffer, mSceneSubmeshes[submeshIndex].IndexCount, mSceneMeshes[meshIndex].InstanceCount, mSceneSubmeshes[submeshIndex].FirstIndex, mSceneSubmeshes[submeshIndex].VertexOffset, 0);
}
}
} | 59.076923 | 205 | 0.836589 | Sixshaman |
522ca8d4e556f77c0c963852a12cafa29e87de29 | 7,372 | cpp | C++ | mazerunner/source/Way.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | mazerunner/source/Way.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | 3 | 2020-12-11T10:01:27.000Z | 2022-02-13T22:12:05.000Z | mazerunner/source/Way.cpp | 1pkg/dump | 0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b | [
"MIT"
] | null | null | null | #include "Way.h"
#include <stdlib.h>
#include <time.h>
int seed(int distance, int seed) {
if (seed == 0)
srand((int)time(NULL));
else
srand(seed);
return rand() % distance;
}
Way::Way(int width, int len) {
this->width = width;
this->len = len;
}
bool Way::gate_Checker(int wall, int position) {
if ((position != 0) && (position != this->len - 1) &&
(position != this->width - 1)) {
switch (wall) {
case 1:
if (this->len - position > 0)
return true;
else
return false;
break;
case 2:
if (this->len - position > 0)
return true;
else
return false;
break;
case 3:
if (this->width - position > 0)
return true;
else
return false;
break;
case 4:
if (this->width - position > 0)
return true;
else
return false;
break;
default:
return false;
}
} else
return false;
}
void Way::do_Gate() {
int wall, position;
int seeds = 0;
l1:
seeds = seed(666 * 666 * 666, seeds);
wall = seeds % 4 + 1;
position =
seed(this->len > this->width ? this->len - 1 : this->width - 1, seeds) +
1;
if (gate_Checker(wall, position)) {
switch (wall) {
case 1:
this->add_node(0, position);
this->add_node(1, position);
break;
case 2:
this->add_node(this->width - 1, position);
this->add_node(this->width - 2, position);
break;
case 3:
this->add_node(position, this->len - 1);
this->add_node(position, this->len - 2);
break;
case 4:
this->add_node(position, 0);
this->add_node(position, 1);
break;
}
}
else
goto l1;
}
void Way::regen_it() {
node *enter;
if (this->head->n < 15) {
while (this->head->n > 2) {
enter = this->head->next;
delete this->head;
this->head = enter;
}
} else {
for (int i = 0; i < 12; i++) {
enter = this->head->next;
delete this->head;
this->head = enter;
}
}
}
bool Way::fin() {
if (this->head->m_lval == 0 || this->head->m_lval == this->len - 1 ||
this->head->m_wval == 0 || this->head->m_wval == this->width - 1) {
node *enter = this->head;
do
this->head = this->head->next;
while (this->head->n != 1);
if (enter->n < this->len * this->width) {
this->head = enter;
this->regen_it();
return true;
}
else if ((this->head->m_lval == enter->m_lval) ||
(this->head->m_wval == enter->m_wval)) {
this->head = enter;
this->regen_it();
return true;
}
else if (((enter->m_lval == 0 || enter->m_lval == this->len - 1) &&
(this->head->m_wval == 0 ||
this->head->m_wval == this->width - 1)) ||
((this->head->m_lval == 0 ||
this->head->m_lval == this->len - 1) &&
(enter->m_wval == 0 || enter->m_wval == this->width - 1))) {
if (abs(((enter->m_wval * this->len) + enter->m_lval) -
((this->head->m_wval * this->len) + this->head->m_lval)) <
(this->len) * (int)(this->width / 6)) {
this->head = enter;
this->regen_it();
return true;
}
else {
this->head = enter;
return false;
}
}
else {
this->head = enter;
return false;
}
}
else
return true;
}
bool Way::check_Way(int route, int size) {
switch (route) {
case 1:
if (this->head->m_wval - size >= 0 &&
(this->head->next->m_wval >= this->head->m_wval))
return true;
else
return false;
break;
case 2:
if (this->head->m_wval + size <= this->width - 1 &&
(this->head->next->m_wval <= this->head->m_wval))
return true;
else
return false;
break;
case 3:
if (this->head->m_lval + size <= this->len - 1 &&
(this->head->next->m_lval <= this->head->m_lval))
return true;
else
return false;
break;
case 4:
if (this->head->m_lval - size >= 0 &&
(this->head->next->m_lval >= this->head->m_lval))
return true;
else
return false;
break;
default:
return false;
}
}
void Way::do_step(int route, int size) {
int len, width;
for (int i = 1; i <= size; i++) {
width = this->head->m_wval;
len = this->head->m_lval;
switch (route) {
case 1:
this->add_node(--width, len);
break;
case 2:
this->add_node(++width, len);
break;
case 3:
this->add_node(width, ++len);
break;
case 4:
this->add_node(width, --len);
break;
}
}
}
void Way::do_Way() {
int seeds = 0;
while (this->fin()) {
if (this->head->n % 50 == 0 &&
(this->head->n > this->width * this->len * 3))
seeds = 0;
seeds = seed(666 * 666 * 666, seeds);
if (this->check_Way(seeds % 4 + 1, seeds % 3 + 2))
this->do_step(seeds % 4 + 1, seeds % 3 + 2);
}
}
void Way::position(int &start_width, int &start_len, int &end_width,
int &end_len) {
node *enter = this->head;
end_width = this->head->m_wval;
end_len = this->head->m_lval;
while (this->head->n != 1)
this->head = this->head->next;
start_width = this->head->m_wval;
start_len = this->head->m_lval;
this->head = enter;
}
void Way::coppy_lab(bool **lab) {
node *enter = this->head;
while (this->head != NULL) {
lab[this->head->m_wval][this->head->m_lval] = 1;
this->head = this->head->next;
}
this->head = enter;
}
void Way::main(bool **lab, int &start_width, int &start_len, int &end_width,
int &end_len) {
this->do_Gate();
this->do_Way();
this->coppy_lab(lab);
this->position(start_width, start_len, end_width, end_len);
}
bool Way::check_sWay(int route, int size) {
switch (route) {
case 1:
if (this->head->m_wval - size > 0 &&
(this->head->next->m_wval >= this->head->m_wval))
return true;
else
return false;
break;
case 2:
if (this->head->m_wval + size < this->width - 1 &&
(this->head->next->m_wval <= this->head->m_wval))
return true;
else
return false;
break;
case 3:
if (this->head->m_lval + size < this->len - 1 &&
(this->head->next->m_lval <= this->head->m_lval))
return true;
else
return false;
break;
case 4:
if (this->head->m_lval - size > 0 &&
(this->head->next->m_lval >= this->head->m_lval))
return true;
else
return false;
break;
default:
return false;
}
}
void Way::do_sWay() {
node *enter = head;
int lim = seed(this->head->n - 1, 0);
while (this->head->n > lim) {
enter = this->head->next;
delete this->head;
this->head = enter;
}
int seeds = 0;
for (int i = 0; i < this->width * this->len; i++) {
seeds = seed(666 * 666 * 666, seeds);
if (this->check_sWay(seeds % 4 + 1, seeds % 6 + 2))
this->do_step(seeds % 4 + 1, seeds % 6 + 2);
}
} | 21.492711 | 79 | 0.495252 | 1pkg |
522dad0a3044d987186eda0ccec9ff2467291d47 | 681 | cpp | C++ | test/zisa/unit_test/flux/hllc.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | test/zisa/unit_test/flux/hllc.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | test/zisa/unit_test/flux/hllc.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | 1 | 2021-08-24T11:52:51.000Z | 2021-08-24T11:52:51.000Z | // SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#include <zisa/testing/testing_framework.hpp>
#include <zisa/flux/hllc.hpp>
#include <zisa/model/euler.hpp>
#include <zisa/model/ideal_gas_eos.hpp>
TEST_CASE("HLLC; consistency") {
using eos_t = zisa::IdealGasEOS;
using gravity_t = zisa::ConstantGravityRadial;
using euler_t = zisa::Euler;
auto eos = eos_t{1.6, 1.0};
auto euler = euler_t{};
auto u = zisa::euler_var_t{1.0, -0.2, 0.3, 0.8, 12.0};
auto p = eos.pressure(u);
auto [nf, _] = zisa::HLLCBatten<eos_t>::flux(euler, eos, u, eos, u);
auto pf = euler.flux(u, p);
REQUIRE(zisa::almost_equal(nf, pf, 1e-12));
}
| 25.222222 | 70 | 0.676946 | 1uc |
52346b8c383fcf4cfb0397a308d50fd394c8ccdf | 3,122 | cpp | C++ | test/voiceControlInterfaceTest.cpp | rubenacevedo3/cpp-RoboDogVoiceController | 9583447574531c18a6346f49de460b52bc97bed4 | [
"MIT"
] | null | null | null | test/voiceControlInterfaceTest.cpp | rubenacevedo3/cpp-RoboDogVoiceController | 9583447574531c18a6346f49de460b52bc97bed4 | [
"MIT"
] | null | null | null | test/voiceControlInterfaceTest.cpp | rubenacevedo3/cpp-RoboDogVoiceController | 9583447574531c18a6346f49de460b52bc97bed4 | [
"MIT"
] | null | null | null | /**
*@author Ruben Acevedo
*@file voiceControlInterfaceTest.cpp
*@brief This is the ".cpp" file for testing the voiceControlInterface Class
*@copyright [2017] Ruben Acevedo
*
* This file tests the voiceControlInterface Class using google test
*
*/
/**
* MIT License
*
* Copyright 2017 Ruben Acevedo
*
* 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. © 2017 GitHub, Inc.
*/
#include <voiceControlInterface.hpp>
#include <gtest/gtest.h>
//! test the class constructor sets on bool false
/**
* This tests to make sure that when the class is created
* the on bool is set to false. This also test the
* isOn() bool function as a result.
*/
TEST(voiceControlInterfaceTest, constructorTest) {
voiceControlInterface vci;
EXPECT_FALSE(vci.isOn());
}
//! test the turn on function
/**
* This tests to make sure the function turns the on bool
* to true and it outputs to the user the correct phrase
*/
TEST(voiceControlInterfaceTest, turnOnTest) {
voiceControlInterface vci;
EXPECT_EQ("RoboDog Voice Control Interface is on", vci.turnOn());
EXPECT_TRUE(vci.isOn());
EXPECT_EQ("", vci.turnOn());
}
//! test the turn off function
/**
* This tests to make sure the function turns the on bool
* to false and it outputs to the user the correct phrase
*/
TEST(voiceControlInterfaceTest, turnOffTest) {
voiceControlInterface vci;
vci.turnOn();
EXPECT_EQ("RoboDog Voice Control Interface is off", vci.turnOff());
EXPECT_FALSE(vci.isOn());
EXPECT_EQ("", vci.turnOff());
}
//! test the listen function
/**
* This tests to make sure that the listen function only works
* when the interface is turned on.
*/
TEST(voiceControlInterfaceTest, listenTest) {
voiceControlInterface vci;
EXPECT_FALSE(vci.listen(true));
vci.turnOn();
EXPECT_TRUE(vci.listen(true));
}
//! test the train function
/**
* This tests to make sure that the train function only works
* when the interface is turned on.
*/
TEST(voiceControlInterfaceTest, trainModeTest) {
voiceControlInterface vci;
EXPECT_FALSE(vci.trainMode(true));
vci.turnOn();
EXPECT_TRUE(vci.trainMode(true));
}
| 32.863158 | 80 | 0.741832 | rubenacevedo3 |
523acc952caa31c8f2b044cd738427da6e0c6ee1 | 16,885 | cpp | C++ | TheEngineSample/RoomRayModel.cpp | natalieagus/Original-Binaural-Reverb | 15cb56203c432d7768f6674b8e80ea3902c2ff11 | [
"Zlib"
] | null | null | null | TheEngineSample/RoomRayModel.cpp | natalieagus/Original-Binaural-Reverb | 15cb56203c432d7768f6674b8e80ea3902c2ff11 | [
"Zlib"
] | null | null | null | TheEngineSample/RoomRayModel.cpp | natalieagus/Original-Binaural-Reverb | 15cb56203c432d7768f6674b8e80ea3902c2ff11 | [
"Zlib"
] | 1 | 2018-12-16T15:03:53.000Z | 2018-12-16T15:03:53.000Z | //
// RoomRayModel.c
// TheEngineSample
//
// Created by Hans on 6/11/15.
// Copyright © 2015 A Tasty Pixel. All rights reserved.
//
#include "RoomRayModel.h"
#include "assert.h"
#include "string.h"
#include "math.h"
#include "FDN.h"
RoomRayModel::RoomRayModel(){
numCorners = 0;
}
//Visibility check when setting a bounce point on the wall
void RoomRayModel::setBouncePoints(Vector3D* bouncePoints, Vector3D wallOrientation, Vector3D wallStart, float wallLength, size_t numPoints, float* outputGains, float* inputGains, Vector3D* BP){
// average space between each pair of points
float pointSpacing = wallLength / numPoints;
Vector3D prevStart = wallStart;
// set the points at even but randomly jittered locations
for (size_t i = 0; i < numPoints; i++) {
float randFlt = (float)rand() / (float)RAND_MAX;
bouncePoints[i] = getBP(pointSpacing, wallStart, i, wallOrientation, randFlt);
if(i>0){
Vector3D start = prevStart;
Vector3D difference = (bouncePoints[i] - bouncePoints[i-1]).scalarMul(0.5f);
Vector3D end = bouncePoints[i-1] + difference;
//check how many points in that line:
// int count = 0;
// for (int k =0; k<numWallPoints ; k++){
// float d1 = BP[k].distance(start);
// float d2 = BP[k].distance(end);
// float d3 = start.distance(end);
// if ((d1+d2)-d3 < 0.0000001f){
// count++;
// // printf("Point : %f %f in S %f %f E %f %f\n", BP[k].x, bouncePoints[k].y, start.x, start.y, end.x, end.y);
// }
// }
// // printf("Count : %d \n", count);
// if (count > 0) {
//// outputGains[i-1] = sqrtf( xAlignedIntegration(listenerLoc, start, end, true) * ROOMCEILING) * sqrtf(float(count));
//// inputGains[i-1] = sqrtf(xAlignedIntegration(soundSourceLoc, start, end, false) * ROOMCEILING) * sqrtf(float(count));
//
// outputGains[i-1] = sqrtf( xAlignedIntegration(listenerLoc, start, end, true) * ROOMCEILING) * float(count);
// inputGains[i-1] = sqrtf(xAlignedIntegration(soundSourceLoc, start, end, false) * ROOMCEILING)* float(count);
//
// }
//
outputGains[i-1] = sqrtf( xAlignedIntegration(listenerLoc, start, end, true) * ROOMCEILING)*sqrtf(1.f/M_PI);
inputGains[i-1] = sqrtf(xAlignedIntegration(soundSourceLoc, start, end, false) * ROOMCEILING);
prevStart = Vector3D(end.x, end.y);
}
}
//do the last gain
Vector3D end = wallStart + wallOrientation.scalarMul(wallLength);
outputGains[numPoints-1] = sqrtf(xAlignedIntegration(listenerLoc, prevStart, end, true))*sqrtf(1.f/M_PI);
inputGains[numPoints-1] = sqrtf(xAlignedIntegration(soundSourceLoc, prevStart, end, false));
printf("\nDone setting ARE");
}
Vector3D RoomRayModel::getBP(float pointSpacing, Vector3D wallStart, size_t i, Vector3D wallOrientation, float randFlt){
float distance = (((float)i+randFlt) * pointSpacing);
Vector3D bp = wallStart + wallOrientation.scalarMul(distance);
return bp;
}
void RoomRayModel::gridBP(Vector3D* floorBouncePoints, size_t floorTaps){
float xSpacing = wallLengths[0] / floorTaps;
float ySpacing = wallLengths[1] / floorTaps;
gridArea = xSpacing * ySpacing;
for (size_t i = 0; i < floorTaps; i++){ //y
for (size_t j = 0; j < floorTaps; j++) { //x
float randFltX = (float)rand() / (float)RAND_MAX;
float randFltY = (float)rand() / (float)RAND_MAX;
//printf("index %lu : ", i*floorTaps+j);
floorBouncePoints[i*floorTaps + j] = Vector3D(((float)j + randFltX) * xSpacing, ((float)i + randFltY) * ySpacing);
//printf(" --- PT x %f y %f \n", floorBouncePoints[i*floorTaps + j].x, floorBouncePoints[i*floorTaps + j].y);
}
}
}
void RoomRayModel::setFloorBouncePointsGain(Vector3D* bouncePoints, float* inputGain, float* outputGain, size_t floorTaps){
for (size_t i = 0; i < floorTaps; i++){
// printf("GridArea is : %f \n", gridArea);
inputGain[i] = gridArea * pythagorasGain(soundSourceLoc, &bouncePoints[i], HEIGHT);
outputGain[i] = gridArea * pythagorasGain(listenerLoc, &bouncePoints[i], HEIGHT);
// printf("Floor input Gain : %f floor output Gain : %f \n", inputGain[i], outputGain[i]);
if (inputGain[i] > maxFloorGain){
inputGain[i] = maxFloorGain;
}
if (outputGain[i] > maxFloorGain){
outputGain[i] = maxFloorGain;
}
}
}
float RoomRayModel::pythagorasGain(Vector3D loc, Vector3D* bouncePoint, float height){
float zVal = ((float)rand()/float(RAND_MAX) * height);
float distance = sqrtf( powf(loc.distance(*bouncePoint), 2.f) + powf(zVal, 2.f));
bouncePoint->z = zVal;
// printf("z : %f", zVal);
return 1.0f/distance;
}
float RoomRayModel::calcMaxGain(float x, float y){
float a = y * logf(x + sqrtf(powf(x, 2.f)+powf(y, 2.f)));
float b = x * (-1.f + logf(y + sqrtf(powf(x, 2.f)+powf(y, 2.f))));
return a+b;
}
float RoomRayModel::getMaxGain(float xLower, float xUpper, float yLower, float yUpper){
float a = calcMaxGain(yUpper, xUpper);
float b = calcMaxGain(yUpper, xLower);
float c = calcMaxGain(yLower, xUpper);
float d = calcMaxGain(yLower, xLower);
return ((a-b) - (c-d));
}
void RoomRayModel::setLocation(float* rayLengths, size_t numTaps, Vector3D listenerLocation, Vector3D soundSourceLocation, Vector3D* bouncePoints, float* outputGains, float* inputGains, size_t floorTaps, Vector3D* BP){
srand (1);
size_t j = numTaps - floorTaps;
floorTapsPerDimension = (size_t) sqrtf(floorTaps);
// this->numWallPoints = numTaps - floorTaps;
// numTaps -= floorTaps;
//
//
// assert(numCorners > 0); // the geometry must be initialised before now
// soundSourceLoc = soundSourceLocation;
// listenerLoc = listenerLocation;
//
// // set the number of taps on each wall proportional to the
// // length of the wall
// size_t numTapsOnWall[RRM_MAX_CORNERS];
// size_t totalTaps = 0;
// for (size_t i = 0; i < RRM_MAX_CORNERS; i++) {
// numTapsOnWall[i] = (size_t)floor(wallLengths[i]/totalWallLength * (float)numTaps);
// totalTaps += numTapsOnWall[i];
// }
//
// // if the number of taps now assigned isn't enough, add one tap to
// // each wall until we have the desired number
// size_t i = 0;
// while (totalTaps < numTaps) {
// numTapsOnWall[i]++;
// i++;
// totalTaps++;
// if (i == RRM_MAX_CORNERS) i = 0;
// }
//
// // set bounce points for each wall
// size_t j = 0;
// for (size_t i = 0; i < numCorners; i++) {
// //must be corner i-1 or shift the corner values firston
// setBouncePoints(&bouncePoints[j], wallOrientations[i], corners[i], wallLengths[i], numTapsOnWall[i],&outputGains[j],&inputGains[j],BP);
// j += numTapsOnWall[i];
// }
////
// for (int i =0; i < numTaps; i++){
// printf("%f, ",bouncePoints[i].x);
// }
// printf("\n\n");
// for (int i =0; i < numTaps; i++){
// printf("%f, ",bouncePoints[i].y);
// }
// set bounce points for the floor
gridBP(&bouncePoints[j], floorTapsPerDimension);
setFloorBouncePointsGain(&bouncePoints[j], &inputGains[j], &outputGains[j], floorTaps);
numTaps += floorTaps;
// // normalize the total input gain to 1.0f
// float totalSquaredInputGain = 0.0f;
// for (size_t i = 0; i < numTaps; i++) {
// inputGains[i] = fabsf(inputGains[i]*ROOMCEILING); //multiply by the room ceiling
// totalSquaredInputGain += inputGains[i]*inputGains[i];
// }
//
// float inGainNormalize = 1.0f / sqrt(totalSquaredInputGain);
// for (size_t i = 0; i < numTaps; i++) {
// inputGains[i] *= inGainNormalize;
// // printf("inputGains[%lu] : %f \n", i, inputGains[i]);
// }
//
// //normalize the total out gain to 1.0f
// float totalSquaredOutputGain = 0.0f;
// for (size_t i = 0; i< numTaps; i++){
// outputGains[i] = fabsf(outputGains[i]);
// // printf("Output gain: %f \n", outputGains[i]);
// totalSquaredOutputGain += outputGains[i]*outputGains[i];
// }
//
// float outputGainNormalize = 1.0f / sqrtf(totalSquaredOutputGain);
// for (size_t i = 0; i< numTaps; i++){
// outputGains[i] *= outputGainNormalize;
// // printf("OutputGain[%lu] : %f \n", i, outputGains[i]);
// }
//
}
void RoomRayModel::setRoomGeometry(Vector3D* corners, size_t numCorners){
assert(numCorners >= 3);
this->numCorners = numCorners;
// save the locations of the corners
memcpy(this->corners,corners,sizeof(Vector3D)*numCorners);
// get normalized vectors to represent the orientation of each wall
// and get length of each wall
assert(numCorners < RRM_MAX_CORNERS);
totalWallLength = 0.0f;
for (size_t i = 1; i < numCorners; i++) {
// get orientation vector
wallOrientations[i] = corners[i] - corners[i-1];
// get wall length
wallLengths[i] = wallOrientations[i].length();
totalWallLength += wallLengths[i];
// normalize the orientation vector
wallOrientations[i].normalize();
}
// get the values that wrap around from the end of the for loop above
wallOrientations[0] = corners[0] - corners[numCorners-1];
wallLengths[0] = wallOrientations[0].length();
totalWallLength += wallLengths[0];
wallOrientations[0].normalize();
assert(totalWallLength > 0.0f);
//change the corner indexes to match the wallOrientation indexes for setLocation method
Vector3D lastCorner = this->corners[numCorners-1];
Vector3D prevCorner = this->corners[0];
Vector3D currCorner;
for (size_t i = 1; i<numCorners; i++){
currCorner = this->corners[i];
this->corners[i] = prevCorner;
prevCorner = currCorner;
}
this->corners[0] = lastCorner;
}
//Simpler integration method with angle
float RoomRayModel::integrationSimple(Vector3D loc, float x, bool listLoc){
//With angle, for input gain, not listloc
if (!listLoc){
float a = -1.0f*loc.x + x;
float b = sqrtf(powf(loc.x, 2.f) + pow(loc.y, 2.f) - 2.f * loc.x * x + pow(x, 2.f));
return (a / (loc.y * b));
}
//Without angle, for output gain
else{
float a = (loc.x - x) / loc.y;
return (- atan(a) / loc.y);
}
}
Vector3D RoomRayModel::align(Vector3D point, Vector3D wallvector){
//normalize wall vector
wallvector.normalize();
float x = wallvector.x * point.x + wallvector.y * point.y;
float y = -1.0f*wallvector.y * point.x + wallvector.x * point.y;
return Vector3D(x,y);
}
//this returns the gain, can be used for both input and output
float RoomRayModel::xAlignedIntegration(Vector3D loc, Vector3D ptStart, Vector3D ptEnd, bool listLoc){
Vector3D wallVector = ptEnd - ptStart;
Vector3D alignedStart = align(ptStart, wallVector);
Vector3D alignedEnd = align(ptEnd, wallVector);
Vector3D alignedLoc = align(loc, wallVector);
alignedEnd = alignedEnd - alignedStart;
alignedLoc = alignedLoc - alignedStart;
float endVal = integrationSimple(alignedLoc, alignedEnd.x, listLoc);
float startVal = integrationSimple(alignedLoc, 0.0f, listLoc);
// printf("endval %f startval %f \n", endVal, startVal);
return fabs(endVal - startVal);
}
//
void RoomRayModel::setRayTracingPoints(Vector3D* bouncePoints, Vector3D ssLoc, float rheight, float rwidth, int numpoints, float* outputGains, float* inputGains, Vector3D listloc){
listenerLoc = listloc;
soundSourceLoc = ssLoc;
float yBot = 0.0f-ssLoc.y;
float yTop = rheight - ssLoc.y;
float xLeft = 0.0f - ssLoc.x;
float xRight = rwidth - ssLoc.x;
float w = ssLoc.x;
float h = ssLoc.y;
for (int i = 0; i < numpoints/2; i++){
float angle = (360.f / float(numpoints)) * float(i);
// printf("Angle : %f \n", angle);
float m = 1.0f/tan(angle * M_PI / 180.f);
//y = mx + 0
Vector3D pointArray[4] = {Vector3D(yBot/m, yBot),
Vector3D(yTop/m, yTop),
Vector3D(xLeft, m*xLeft),
Vector3D(xRight, m*xRight)};
for (int j = 0; j< 4; j++){
float xO = pointArray[j].x + ssLoc.x;
if (xO > rwidth or xO < 0.0f){
pointArray[j].mark = false;
continue;
}
float yO = pointArray[j].y + ssLoc.y;
if (yO > rheight or yO < 0.0f){
pointArray[j].mark = false;
continue;
}
if (pointArray[j].mark == true){
//check for x value
if (pointArray[j].x >= 0){
bouncePoints[i].x = pointArray[j].x + w;
bouncePoints[i].y = pointArray[j].y + h;
}
else{
bouncePoints[i+numpoints/2].x = pointArray[j].x + w;
bouncePoints[i+numpoints/2].y = pointArray[j].y + h;
}
}
}
}
Vector3D prevStart = bouncePoints[0];
// printf("List loc %f %f ssloc %f %f \n", listenerLoc.x, listenerLoc.y, soundSourceLoc.x, soundSourceLoc.y);
// set the points at even but randomly jittered locations
for (size_t i = 1; i < numpoints; i++) {
Vector3D start = prevStart;
Vector3D difference = (bouncePoints[i] - bouncePoints[i-1]).scalarMul(0.5f);
Vector3D end = bouncePoints[i-1] + difference;
// printf("Start : %f %f , difference : %f %f \n", start.x, start.y, difference.x, difference.y);
outputGains[i-1] = sqrtf( xAlignedIntegration(listloc, start, end, true))*sqrtf(1.f/M_PI);
inputGains[i-1] = sqrtf(xAlignedIntegration(ssLoc, start, end, false));
// printf("i : %d OutputGains : %f \n", i,outputGains[i-1]);
// printf("i : %d InputGains : %f \n", i,inputGains[i-1]);
prevStart = Vector3D(end.x, end.y);
}
//do the last gain
Vector3D end = bouncePoints[numpoints-1];
outputGains[numpoints-1] = sqrtf(xAlignedIntegration(listloc, prevStart, end, true)) *sqrtf(1.f/M_PI);
inputGains[numpoints-1] = sqrtf(xAlignedIntegration(ssLoc, prevStart, end, false));
printf("OutputGains : %f \n", outputGains[numpoints-1]);
printf("InputGains : %f \n", inputGains[numpoints-1]);
// printf("S loc x : %f , y : %f \n", ssLoc.x, ssLoc.y);
// for (int i = 0; i<numpoints;i++){
// printf("%f,", bouncePoints[i].x);
// }
// printf("\n\n");
// for (int i = 0; i<numpoints;i++){
// printf("%f,", bouncePoints[i].y);
// }
}
//void RoomRayModel::setRayTracingPoints(Vector3D* bouncePoints, Vector3D ssLoc, float rheight, float rwidth, int numpoints,Vector3D listloc){
//
// listenerLoc = listloc;
// soundSourceLoc = ssLoc;
// float yBot = 0.0f-ssLoc.y;
// float yTop = rheight - ssLoc.y;
// float xLeft = 0.0f - ssLoc.x;
// float xRight = rwidth - ssLoc.x;
//
// float w = ssLoc.x;
// float h = ssLoc.y;
//
// for (int i = 0; i < numpoints/2; i++){
// float angle = (360.f / float(numpoints)) * float(i);
// // printf("Angle : %f \n", angle);
// float m = 1.0f/tan(angle * M_PI / 180.f);
// //y = mx + 0
// Vector3D pointArray[4] = {Vector3D(yBot/m, yBot),
// Vector3D(yTop/m, yTop),
// Vector3D(xLeft, m*xLeft),
// Vector3D(xRight, m*xRight)};
//
// for (int j = 0; j< 4; j++){
// float xO = pointArray[j].x + ssLoc.x;
// if (xO > rwidth or xO < 0.0f){
// pointArray[j].mark = false;
// continue;
// }
// float yO = pointArray[j].y + ssLoc.y;
// if (yO > rheight or yO < 0.0f){
// pointArray[j].mark = false;
// continue;
// }
// if (pointArray[j].mark == true){
// //check for x value
// if (pointArray[j].x >= 0){
// bouncePoints[i].x = pointArray[j].x + w;
// bouncePoints[i].y = pointArray[j].y + h;
// }
// else{
// bouncePoints[i+numpoints/2].x = pointArray[j].x + w;
// bouncePoints[i+numpoints/2].y = pointArray[j].y + h;
// }
// }
// }
// }
//
//
//}
| 37.774049 | 218 | 0.579094 | natalieagus |
523d124075a4a5ecbaa4b0fd7003d0058aa6e3cf | 12,371 | cpp | C++ | src/ObjEdit/(old)/OE_TexEd.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 71 | 2015-12-15T19:32:27.000Z | 2022-02-25T04:46:01.000Z | src/ObjEdit/(old)/OE_TexEd.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 19 | 2016-07-09T19:08:15.000Z | 2021-07-29T10:30:20.000Z | src/ObjEdit/(old)/OE_TexEd.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 42 | 2015-12-14T19:13:02.000Z | 2022-03-01T15:15:03.000Z | /*
* Copyright (c) 2004, Laminar Research.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "OE_TexEd.h"
#include "XPLMGraphics.h"
#include "XPWidgets.h"
#include "XPWidgetUtils.h"
#include "XPStandardWidgets.h"
#include "OE_Notify.h"
#include "OE_Msgs.h"
#include "OE_Globals.h"
#include "OE_TexMgr.h"
const float kHandleRad = 3.0; // Handles are about 6 pixels around
const int kMargin = 5; // 5 pixel margin when zoomed out, so we can see handles, etc.
const int kZoomFactor = 16; // Max zoom out is 16x smaller. Makes 64x64 texture size at Max
// Data stored on the actual tex editor widget
const long kHScrollBarID = 1000;
const long kVScrollBarID = 1001;
const long kZoomID = 1002;
const long kCurHandle = 1003;
const long kHandleSlopX = 1004;
const long kHandleSlopY = 1005;
inline float InterpF(float mi, float ma, float v) { return mi + v * (ma - mi); }
inline float GetInterpF(float mi, float ma, float v) { if (ma == mi) return 0.0; return (v - mi) / (ma - mi); }
// second array is s1, s2, t1, t2
int kHandleWriteFlags[9][4] = {
// s1 s2 t1 t2
{ 1, 0, 0, 1 }, // Top left
{ 0, 1, 0, 1 }, // Top right
{ 0, 1, 1, 0 }, // Bot right
{ 1, 0, 1, 0 }, // Bot left
{ 0, 0, 0, 1 }, // Top
{ 0, 1, 0, 0 }, // Right
{ 0, 0, 1, 0 }, // Bottom
{ 1, 0, 0, 0 }, // Left
{ 1, 1, 1, 1 } }; // Center
static void OE_TexEdNotify(int cat, int msg, void * param, void * ref);
static int OE_TexEdFunc( XPWidgetMessage inMessage,
XPWidgetID inWidget,
long inParam1,
long inParam2);
static void ResyncScrollBars(XPWidgetID);
XPWidgetID OE_CreateTexEd(
int x1, int y1, int x2, int y2)
{
XPWidgetID texEd = XPCreateWidget(x1, y2, x2, y1, 1, "Texture Edit", 1, NULL, xpWidgetClass_MainWindow);
XPSetWidgetProperty(texEd, xpProperty_MainWindowHasCloseBoxes, 0);
XPWidgetID vScrollbar = XPCreateWidget(x2-16, y2-18, x2,y1+16, 1, "", 0, texEd, xpWidgetClass_ScrollBar);
XPSetWidgetProperty(vScrollbar, xpProperty_ScrollBarSliderPosition, 0);
XPSetWidgetProperty(vScrollbar, xpProperty_ScrollBarMin, 0);
XPSetWidgetProperty(vScrollbar, xpProperty_ScrollBarMax, 100);
XPWidgetID hScrollbar = XPCreateWidget(x1, y1+16, x2-16,y1, 1, "", 0, texEd, xpWidgetClass_ScrollBar);
XPSetWidgetProperty(hScrollbar, xpProperty_ScrollBarSliderPosition, 0);
XPSetWidgetProperty(hScrollbar, xpProperty_ScrollBarMin, 0);
XPSetWidgetProperty(hScrollbar, xpProperty_ScrollBarMax, 100);
XPWidgetID pane = XPCreateCustomWidget(x1, y2-18, x2-16, y1+16, 1, "", 0, texEd, OE_TexEdFunc);
XPSetWidgetProperty(pane, kHScrollBarID, (long) hScrollbar);
XPSetWidgetProperty(pane, kVScrollBarID, (long) vScrollbar);
XPSetWidgetProperty(pane, xpProperty_Clip, 1);
XPSetWidgetProperty(pane, kZoomID, kZoomFactor);
XPSetWidgetProperty(pane, kCurHandle, -1);
OE_Register(OE_TexEdNotify, pane);
return texEd;
}
void OE_TexEdNotify(int cat, int msg, void * param, void * ref)
{
if ((cat == catagory_Texture && msg == msg_TexLoaded) ||
(cat == catagory_Object && msg == msg_ObjectLoaded))
{
ResyncScrollBars((XPWidgetID) ref);
}
}
void ResyncScrollBars(XPWidgetID me)
{
if (!gObjects.empty())
{
string tex = gObjects[gLevelOfDetail].texture;
if (!tex.empty())
{
int twidth, theight;
if (FindTexture(tex, false, &twidth, &theight))
{
int zoom = XPGetWidgetProperty(me, kZoomID, NULL);
twidth *= zoom;
twidth /= kZoomFactor;
theight *= zoom;
theight /= kZoomFactor;
int t, l, r, b;
XPGetWidgetGeometry(me, &l, &t, &r, &b);
int hScrollDis = twidth - (r - l);
if (hScrollDis < 0) hScrollDis = 0;
int vScrollDis = theight - (t - b);
if (vScrollDis < 0) vScrollDis = 0;
XPSetWidgetProperty((XPWidgetID) XPGetWidgetProperty(me, kHScrollBarID, NULL),
xpProperty_ScrollBarMax, hScrollDis);
XPSetWidgetProperty((XPWidgetID) XPGetWidgetProperty(me, kVScrollBarID, NULL),
xpProperty_ScrollBarMax, vScrollDis);
}
}
}
}
int OE_TexEdFunc( XPWidgetMessage inMessage,
XPWidgetID inWidget,
long inParam1,
long inParam2)
{
if (XPUSelectIfNeeded(inMessage, inWidget, inParam1, inParam2, true)) return 1;
int left, top, right, bottom; // The dimensions of our total pane
int cleft, ctop, cright, cbottom; // The dimensions in which we actually show the texture
int tleft, ttop, tright, tbottom; // The dimensions of the texture in screen coordinates, after zooming, etc.
int hScroll, vScroll; // How far into the texture are we scrolled?
int zoom; // Zoom level
int twidth = 32, theight = 32; // Texture raw dimensions
GLenum texID = 0; // The texture's OGL ID.
float handles[9][2]; // 8 handles in window coords: TL, TR, BR, BL, then T, R, B, L, Center
/*
* Before we do much of anything, we have a ton of geometry data to calculate...
* stuff we'll need both in drawing and mouse tracking.
*
*/
/* Calculate the locations of the window and its parts */
hScroll = XPGetWidgetProperty((XPWidgetID) XPGetWidgetProperty(inWidget, kHScrollBarID, NULL), xpProperty_ScrollBarSliderPosition, NULL);
vScroll = XPGetWidgetProperty((XPWidgetID) XPGetWidgetProperty(inWidget, kVScrollBarID, NULL), xpProperty_ScrollBarSliderPosition, NULL);
XPGetWidgetGeometry(inWidget, &left, &top, &right, &bottom);
cleft = left + kMargin;
cright = right - kMargin;
cbottom = bottom + kMargin;
ctop = top - kMargin;
/* Calculate the texture's location */
if (!gObjects.empty())
{
string tex = gObjects[gLevelOfDetail].texture;
if (!tex.empty())
texID = FindTexture(tex, false, &twidth, &theight);
}
tleft = cleft - hScroll;
tright = tleft + twidth;
ttop = ctop + vScroll;
tbottom = ttop - theight;
zoom = XPGetWidgetProperty(inWidget, kZoomID, NULL);
twidth *= zoom; twidth /= kZoomFactor;
theight *= zoom; theight /= kZoomFactor;
/* Calculate control handle positions */
if (gCurTexture != -1)
{
handles[0][0] = InterpF(tleft, tright, gTextures[gCurTexture].s1);
handles[1][0] = InterpF(tleft, tright, gTextures[gCurTexture].s2);
handles[2][0] = InterpF(tleft, tright, gTextures[gCurTexture].s2);
handles[3][0] = InterpF(tleft, tright, gTextures[gCurTexture].s1);
handles[0][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t2);
handles[1][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t2);
handles[2][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t1);
handles[3][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t1);
handles[4][0] = InterpF(tleft, tright, InterpF(gTextures[gCurTexture].s1, gTextures[gCurTexture].s2, 0.5));
handles[5][0] = InterpF(tleft, tright, gTextures[gCurTexture].s2);
handles[6][0] = InterpF(tleft, tright, InterpF(gTextures[gCurTexture].s1, gTextures[gCurTexture].s2, 0.5));
handles[7][0] = InterpF(tleft, tright, gTextures[gCurTexture].s1);
handles[4][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t2);
handles[5][1] = InterpF(tbottom, ttop, InterpF(gTextures[gCurTexture].t1, gTextures[gCurTexture].t2, 0.5));
handles[6][1] = InterpF(tbottom, ttop, gTextures[gCurTexture].t1);
handles[7][1] = InterpF(tbottom, ttop, InterpF(gTextures[gCurTexture].t1, gTextures[gCurTexture].t2, 0.5));
handles[8][0] = InterpF(tleft, tright, InterpF(gTextures[gCurTexture].s1, gTextures[gCurTexture].s2, 0.5));
handles[8][1] = InterpF(tbottom, ttop, InterpF(gTextures[gCurTexture].t1, gTextures[gCurTexture].t2, 0.5));
}
switch(inMessage) {
case xpMsg_Destroy:
OE_Unregister(OE_TexEdNotify, inWidget);
return 1;
case xpMsg_Draw:
{
// First fill in the whole pane with black...better to see things against black.
XPLMSetGraphicsState(0, 0, 0, 0, 0, 0, 0);
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(left, top);
glVertex2i(right, top);
glVertex2i(right, bottom);
glVertex2i(left, bottom);
glEnd();
// Now draw the texture if we have one.
if (texID)
{
XPLMBindTexture2d(texID, 0);
XPLMSetGraphicsState(0, 1, 0, 1, 1, 0, 0);
} else
XPLMSetGraphicsState(0, 0, 0, 0, 0, 0, 0);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex2i(tleft, ttop);
glTexCoord2f(1.0, 1.0); glVertex2i(tright, ttop);
glTexCoord2f(1.0, 0.0); glVertex2i(tright, tbottom);
glTexCoord2f(0.0, 0.0); glVertex2i(tleft, tbottom);
glEnd();
if (gCurTexture != -1)
{
// Draw the outline of the texture
XPLMSetGraphicsState(0, 0, 0, 0, 0, 0, 0);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
for (int n = 0; n < 4; ++n)
glVertex2fv(handles[n]);
glEnd();
// Draw all 8 control handles
glColor3f(0.5, 1.0, 1.0);
glBegin(GL_QUADS);
for (int n = 0; n < 9; ++n)
{
glVertex2f(handles[n][0] - kHandleRad, handles[n][1] + kHandleRad);
glVertex2f(handles[n][0] + kHandleRad, handles[n][1] + kHandleRad);
glVertex2f(handles[n][0] + kHandleRad, handles[n][1] - kHandleRad);
glVertex2f(handles[n][0] - kHandleRad, handles[n][1] - kHandleRad);
}
glEnd();
}
}
return 1;
case xpMsg_MouseDown:
case xpMsg_MouseDrag:
case xpMsg_MouseUp:
{
if (inMessage == xpMsg_MouseDown)
{
XPSetWidgetProperty(inWidget, kCurHandle, -1);
for (int n = 0; n < 9; ++n)
{
if (((handles[n][0] - kHandleRad) < MOUSE_X(inParam1)) &&
((handles[n][0] + kHandleRad) > MOUSE_X(inParam1)) &&
((handles[n][1] - kHandleRad) < MOUSE_Y(inParam1)) &&
((handles[n][1] + kHandleRad) > MOUSE_Y(inParam1)))
{
XPSetWidgetProperty(inWidget, kCurHandle, n);
XPSetWidgetProperty(inWidget, kHandleSlopX, handles[n][0] - MOUSE_X(inParam1));
XPSetWidgetProperty(inWidget, kHandleSlopY, handles[n][1] - MOUSE_Y(inParam1));
}
}
}
int curHandle = XPGetWidgetProperty(inWidget, kCurHandle, NULL);
if (curHandle != -1)
{
int new_handle_x = MOUSE_X(inParam1) + XPGetWidgetProperty(inWidget, kHandleSlopX, NULL);
int new_handle_y = MOUSE_Y(inParam1) + XPGetWidgetProperty(inWidget, kHandleSlopY, NULL);
float s_loc = GetInterpF(tleft, tright, new_handle_x);
float t_loc = GetInterpF(tbottom, ttop, new_handle_y);
if (curHandle == 8)
{
float s_dif = s_loc - InterpF(gTextures[gCurTexture].s1, gTextures[gCurTexture].s2, 0.5);
float t_dif = t_loc - InterpF(gTextures[gCurTexture].t1, gTextures[gCurTexture].t2, 0.5);
gTextures[gCurTexture].s1 += s_dif;
gTextures[gCurTexture].s2 += s_dif;
gTextures[gCurTexture].t1 += t_dif;
gTextures[gCurTexture].t2 += t_dif;
} else {
if (kHandleWriteFlags[curHandle][0]) gTextures[gCurTexture].s1 = s_loc;
if (kHandleWriteFlags[curHandle][1]) gTextures[gCurTexture].s2 = s_loc;
if (kHandleWriteFlags[curHandle][2]) gTextures[gCurTexture].t1 = t_loc;
if (kHandleWriteFlags[curHandle][3]) gTextures[gCurTexture].t2 = t_loc;
}
OE_Notify(catagory_Texture, msg_TexSelectionEdited, NULL);
}
if (inMessage == xpMsg_MouseUp)
XPSetWidgetProperty(inWidget, kCurHandle, -1);
}
return 1;
default:
return 0;
}
}
| 37.038922 | 138 | 0.671005 | rromanchuk |
5241ada4c0cefc0831d002c7c10868d1131954a4 | 11,139 | cpp | C++ | Data-Structures/week4_binary_search_trees/5_rope/rope.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | Data-Structures/week4_binary_search_trees/5_rope/rope.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | Data-Structures/week4_binary_search_trees/5_rope/rope.cpp | ChristineHu1207/Coursera-Data-Structures-and-Algorithms-Specialization | 27f543ca0778d00ffd624ffcd18bf555660e0168 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
const bool DEBUG = false;
struct Vertex {
// key field stores an index pointing to a character via the initial string.
int key;
// Include size to be able to compute order statistics of the key values.
int size;
Vertex *left;
Vertex *right;
Vertex *parent;
Vertex(int key) : key(key), size(1), left(nullptr), right(nullptr), parent(nullptr) {}
};
void update(Vertex *v) {
if (v == nullptr)
return;
v->size =
1 + (v->left != nullptr ? v->left->size : 0) + (v->right != nullptr ? v->right->size : 0);
if (v->left != nullptr) {
v->left->parent = v;
}
if (v->right != nullptr) {
v->right->parent = v;
}
}
void small_rotation(Vertex *v) {
Vertex *parent = v->parent;
if (parent == nullptr) {
return;
}
Vertex *grandparent = v->parent->parent;
if (parent->left == v) {
Vertex *m = v->right;
v->right = parent;
parent->left = m;
} else {
Vertex *m = v->left;
v->left = parent;
parent->right = m;
}
update(parent);
update(v);
v->parent = grandparent;
if (grandparent != nullptr) {
if (grandparent->left == parent) {
grandparent->left = v;
} else {
grandparent->right = v;
}
}
}
void big_rotation(Vertex *v) {
if (v->parent->left == v && v->parent->parent->left == v->parent) {
// Zig-zig
small_rotation(v->parent);
small_rotation(v);
} else if (v->parent->right == v && v->parent->parent->right == v->parent) {
// Zig-zig
small_rotation(v->parent);
small_rotation(v);
} else {
// Zig-zag
small_rotation(v);
small_rotation(v);
}
}
// Makes splay of the given vertex and makes
// it the new root.
void splay(Vertex *&root, Vertex *v) {
if (v == nullptr)
return;
while (v->parent != nullptr) {
if (v->parent->parent == nullptr) {
small_rotation(v);
break;
}
big_rotation(v);
}
root = v;
}
// Searches the tree for the node in position k (1-based) ~ k-th order statistic
// Assume k in [1, size]
Vertex *find(Vertex *&root, int k) {
if (k == 0) {
return nullptr;
}
int s{0};
if (root->left != nullptr) {
s = root->left->size;
}
if (k == s + 1) {
return root;
} else if (k < s + 1 and root->left != nullptr) {
return find(root->left, k);
} else if (root->right != nullptr) {
return find(root->right, k - s - 1);
} else {
return nullptr;
}
}
void split(Vertex *root, int pos, Vertex *&left, Vertex *&right) {
right = find(root, pos);
splay(root, right);
if (right == nullptr) {
left = root;
return;
}
left = right->left;
right->left = nullptr;
if (left != nullptr) {
left->parent = nullptr;
}
update(left);
update(right);
}
// Searches for the given key in the tree with the given root
// and calls splay for the deepest visited node after that.
// If found, returns a pointer to the node with the given key.
// Otherwise, returns a pointer to the node with the smallest
// bigger key (next value in the order).
// If the key is bigger than all keys in the tree,
// returns nullptr.
Vertex *old_find(Vertex *&root, int key) {
Vertex *v = root;
Vertex *last = root;
Vertex *next = nullptr;
while (v != nullptr) {
if (v->key >= key && (next == nullptr || v->key < next->key)) {
next = v;
}
last = v;
if (v->key == key) {
break;
}
if (v->key < key) {
v = v->right;
} else {
v = v->left;
}
}
splay(root, last);
return next;
}
// Version of split using the old_find function, used for rope initalization.
void old_split(Vertex *root, size_t key, Vertex *&left, Vertex *&right) {
right = old_find(root, key);
splay(root, right);
if (right == nullptr) {
left = root;
return;
}
left = right->left;
right->left = nullptr;
if (left != nullptr) {
left->parent = nullptr;
}
update(left);
update(right);
}
Vertex *merge(Vertex *left, Vertex *right) {
if (left == nullptr)
return right;
if (right == nullptr)
return left;
Vertex *min_right = right;
while (min_right->left != nullptr) {
min_right = min_right->left;
}
splay(right, min_right);
right->left = left;
update(right);
return right;
}
class Rope {
std::string s, s_slow;
Vertex *root = nullptr;
void insert(int idx) {
Vertex *left = nullptr;
Vertex *right = nullptr;
Vertex *new_vertex = nullptr;
old_split(root, idx, left, right);
if (right == nullptr || right->key != idx) {
new_vertex = new Vertex(idx);
}
root = merge(merge(left, new_vertex), right);
}
void traverse(Vertex *node, std::stringstream &ss) {
// In order search of the spaly tree
if (node == nullptr) {
return;
}
traverse(node->left, ss);
// output original character
ss << s[node->key];
traverse(node->right, ss);
}
public:
Rope(const std::string &s) : s(s), s_slow(s) {
for (size_t idx = 0; idx < s.size(); ++idx) {
insert(idx);
}
}
void process_slow(int i, int j, int k) {
// t is the substring of s without the characters between i-th through j-th
std::string t = s_slow.substr(0, i) + s_slow.substr(j + 1);
s_slow = t.substr(0, k) + s_slow.substr(i, j - i + 1) + t.substr(k);
}
void process(int i, int j, int k) {
if (DEBUG) {
std::cout << std::endl
<< "Processing: i=" << i << " j=" << j << " k=" << k << std::endl;
}
Vertex *left = nullptr;
Vertex *middle = nullptr;
Vertex *right = nullptr;
if (DEBUG) {
std::cout << " Initial state (root): ";
std::cout << result(root) << std::endl;
}
split(root, j + 2, middle, right);
if (DEBUG) {
std::cout << " After 1st call to split: " << std::endl;
std::cout << " middle: ";
std::cout << result(middle) << std::endl;
std::cout << " right: ";
std::cout << result(right) << std::endl;
}
split(middle, i + 1, left, middle);
if (DEBUG) {
std::cout << " After 2nd call to split: " << std::endl;
std::cout << " left: ";
std::cout << result(left) << std::endl;
std::cout << " middle: ";
std::cout << result(middle) << std::endl;
std::cout << " right: ";
std::cout << result(right) << std::endl;
}
root = merge(left, right);
if (DEBUG) {
std::cout << " Merged left & right: ";
std::cout << result(root) << std::endl;
}
if (root != nullptr) {
split(root, k + 1, left, right);
} else {
root = middle;
}
if (DEBUG) {
std::cout << " After 3rd call to split (insert step):" << std::endl;
std::cout << " left: ";
std::cout << result(left) << std::endl;
std::cout << " right: ";
std::cout << result(right) << std::endl;
}
root = merge(merge(left, middle), right);
if (DEBUG) {
std::cout << "State after process (root): ";
std::cout << result(root) << std::endl;
}
}
std::string result() {
std::stringstream ss;
std::string result;
traverse(root, ss);
ss >> result;
return result;
}
std::string result(Vertex *node) {
std::stringstream ss;
std::string result;
if (node != nullptr) {
traverse(node, ss);
ss >> result;
}
return result;
}
std::string result_slow() { return s_slow; }
void test_find() {
std::cout << result(root) << std::endl;
while (true) {
size_t k;
std::cin >> k;
auto v = find(root, k);
std::cout << s[v->key] << ", size=" << v->size << std::endl;
}
}
};
void stress_test() {
while (true) {
std::string alphabet{"abcdefghijklmnopqrstuvwxyz"};
std::string s;
std::cout << "generate string" << std::endl;
// generate test string of size from 1 up to 300 000
int ssize = (rand() % 30) + 1;
for (int i = 0; i < ssize; ++i) {
s += alphabet[rand() % alphabet.size()];
}
std::cout << "size: " << ssize << std::endl;
std::cout << "string: " << s << std::endl;
std::cout << "create rope" << std::endl;
Rope rope(s);
std::cout << "generate queries" << std::endl;
// generate queries
int q = (rand() % 5) + 1;
for (int q_i = 0; q_i < q; ++q_i) {
int a = rand() % ssize;
int b = rand() % ssize;
int i = std::min(a, b);
int j = std::max(a, b);
int k_limit = ssize - (j - i + 1);
int k{0};
if (k_limit > 0) {
k = rand() % (ssize - (j - i + 1));
}
std::cout << i << " " << j << " " << k << std::endl;
std::cout << "s_prev" << std::endl;
auto s_prev = rope.result();
std::cout << "process" << std::endl;
rope.process(i, j, k);
std::cout << "process_slow" << std::endl;
rope.process_slow(i, j, k);
std::cout << "result" << std::endl;
auto result = rope.result();
std::cout << "result_slow" << std::endl;
auto result_slow = rope.result_slow();
if (result == result_slow) {
std::cout << "OK!" << std::endl;
} else {
std::cout << "FAIL!" << std::endl;
std::cout << "s=" << s << std::endl;
std::cout << "i=" << i << " j=" << j << " k=" << k << std::endl;
std::cout << "s_prev=" << s_prev << std::endl;
std::cout << "result=" << result << std::endl;
std::cout << "result_slow=" << result_slow << std::endl;
break;
}
}
}
}
int main() {
// stress_test();
std::string s;
std::cin >> s;
Rope rope(s);
if (DEBUG) {
while (true) {
int i, j, k;
std::cin >> i >> j >> k;
rope.process(i, j, k);
}
} else {
int nops;
std::cin >> nops;
for (int op = 0; op < nops; ++op) {
int i, j, k;
std::cin >> i >> j >> k;
rope.process(i, j, k);
}
}
std::cout << rope.result() << std::endl;
} | 26.776442 | 98 | 0.474998 | ChristineHu1207 |
52440254b28103248dafb8f5f404d1aa859146d6 | 1,161 | cpp | C++ | tests/piecetypetest.cpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 6 | 2019-01-23T03:13:36.000Z | 2020-09-06T09:54:48.000Z | tests/piecetypetest.cpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 33 | 2015-12-28T08:48:01.000Z | 2019-09-25T11:39:53.000Z | tests/piecetypetest.cpp | bsamseth/Goldfish | c99cb9f2b14bbd04e0c2a9ae32b78e074ff6199b | [
"MIT"
] | 6 | 2018-08-06T14:05:11.000Z | 2022-02-15T01:30:49.000Z | #include "piecetype.hpp"
#include "gtest/gtest.h"
using namespace goldfish;
TEST(piecetypetest, test_values)
{
for (auto piecetype : PieceTypes::values)
{
EXPECT_EQ(piecetype, PieceTypes::values[piecetype]);
}
}
TEST(piecetypetest, test_is_validPromotion)
{
EXPECT_TRUE(PieceTypes::is_valid_promotion(PieceType::KNIGHT));
EXPECT_TRUE(PieceTypes::is_valid_promotion(PieceType::BISHOP));
EXPECT_TRUE(PieceTypes::is_valid_promotion(PieceType::ROOK));
EXPECT_TRUE(PieceTypes::is_valid_promotion(PieceType::QUEEN));
EXPECT_FALSE(PieceTypes::is_valid_promotion(PieceType::PAWN));
EXPECT_FALSE(PieceTypes::is_valid_promotion(PieceType::KING));
EXPECT_FALSE(PieceTypes::is_valid_promotion(PieceType::NO_PIECE_TYPE));
}
TEST(piecetypetest, test_is_sliding)
{
EXPECT_TRUE(PieceTypes::is_sliding(PieceType::BISHOP));
EXPECT_TRUE(PieceTypes::is_sliding(PieceType::ROOK));
EXPECT_TRUE(PieceTypes::is_sliding(PieceType::QUEEN));
EXPECT_FALSE(PieceTypes::is_sliding(PieceType::PAWN));
EXPECT_FALSE(PieceTypes::is_sliding(PieceType::KNIGHT));
EXPECT_FALSE(PieceTypes::is_sliding(PieceType::KING));
}
| 33.171429 | 75 | 0.763135 | bsamseth |
524449190bc2a46790c6c8d6dcc26c611565ef8a | 2,315 | cp | C++ | MacOS/Sources/Application/Address_Book/CAddressFieldMultiLine.cp | mbert/mulberry-main | 6b7951a3ca56e01a7be67aa12e55bfeafc63950d | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Address_Book/CAddressFieldMultiLine.cp | mtalexander/mulberry-main | fa6d96ca6ef4401308bddb56518651b4fd866def | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Address_Book/CAddressFieldMultiLine.cp | mtalexander/mulberry-main | fa6d96ca6ef4401308bddb56518651b4fd866def | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007-2011 Cyrus Daboo. 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.
*/
// Source for CAddressFieldMultiLine class
#include "CAddressFieldMultiLine.h"
#include "CStaticText.h"
#include "CTextDisplay.h"
#include <LPopupButton.h>
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CAddressFieldMultiLine::CAddressFieldMultiLine()
{
}
// Constructor from stream
CAddressFieldMultiLine::CAddressFieldMultiLine(LStream *inStream)
: CAddressFieldBase(inStream)
{
}
// Default destructor
CAddressFieldMultiLine::~CAddressFieldMultiLine()
{
}
// O T H E R M E T H O D S ____________________________________________________________________________
// Get details of sub-panes
void CAddressFieldMultiLine::FinishCreateSelf(void)
{
// Do inherited
CAddressFieldBase::FinishCreateSelf();
// Get controls
mData = (CTextDisplay*) mDataMove;
mDataMove = (LView*) FindPaneByID(paneid_AddressFieldBaseMove);
// Link controls to this window
UReanimator::LinkListenerToBroadcasters(this, this, RidL_CAddressFieldMultiLineBtns);
}
void CAddressFieldMultiLine::SetDetails(const cdstring& title, int type, const cdstring& data)
{
// Cache this to check for changes later
mOriginalType = type;
mOriginalData = data;
mTitle->SetText(title);
if (mUsesType)
mType->SetValue(type + 1);
mData->SetText(data);
}
bool CAddressFieldMultiLine::GetDetails(int& newtype, cdstring& newdata)
{
bool changed = false;
if (mUsesType)
{
newtype = mType->GetValue() - 1;
if (newtype != mOriginalType)
changed = true;
}
mData->GetText(newdata);
if (newdata != mOriginalData)
changed = true;
return changed;
}
| 25.722222 | 104 | 0.710583 | mbert |
52460eeb9adc725637203e933192aa1e2ff4fe28 | 527 | cpp | C++ | Curso/AULA 43,44 e 45 - ARQUIVOS/exemplo/src/main.cpp | vandodiniz/CursoC-- | ba979bae23292a59941437dee478f51e7e357abb | [
"MIT"
] | 1 | 2022-03-07T21:40:38.000Z | 2022-03-07T21:40:38.000Z | Curso/AULA 43,44 e 45 - ARQUIVOS/exemplo/src/main.cpp | vandodiniz/CursoC-- | ba979bae23292a59941437dee478f51e7e357abb | [
"MIT"
] | null | null | null | Curso/AULA 43,44 e 45 - ARQUIVOS/exemplo/src/main.cpp | vandodiniz/CursoC-- | ba979bae23292a59941437dee478f51e7e357abb | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main() {
char seps[]=",";
int camisa, pool;
string linha;
char *nome, *func;
int maiorPool = 0;
string maiorNome;
fstream arquivo;
arquivo.open("clash.txt",ios::in);
if(arquivo.is_open()){
while(!arquivo.eof()){
getline(arquivo,linha);
camisa = atoi(strktok(&linha[0],seps));
}
arquivo.close();
}
else
cout << "Erro ao abrir arquivo";
} | 17 | 51 | 0.552182 | vandodiniz |
524762c3f33652de9620a276dcfd14dc99f2c40e | 3,971 | cc | C++ | lite/backends/nnadapter/nnadapter/src/operation/gather.cc | Danielmic/Paddle-Lite | 8bf08425035cfae077754ac72629292fac7bb996 | [
"Apache-2.0"
] | 808 | 2018-04-17T17:43:12.000Z | 2019-08-18T07:39:13.000Z | lite/backends/nnadapter/nnadapter/src/operation/gather.cc | Danielmic/Paddle-Lite | 8bf08425035cfae077754ac72629292fac7bb996 | [
"Apache-2.0"
] | 728 | 2018-04-18T08:15:25.000Z | 2019-08-16T07:14:43.000Z | lite/backends/nnadapter/nnadapter/src/operation/gather.cc | Danielmic/Paddle-Lite | 8bf08425035cfae077754ac72629292fac7bb996 | [
"Apache-2.0"
] | 364 | 2018-04-18T17:05:02.000Z | 2019-08-18T03:25:38.000Z | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "operation/gather.h"
#include "core/types.h"
#include "operation/math/gather.h"
#include "utility/debug.h"
#include "utility/hints.h"
#include "utility/logging.h"
#include "utility/micros.h"
#include "utility/modeling.h"
#include "utility/utility.h"
namespace nnadapter {
namespace operation {
NNADAPTER_EXPORT bool ValidateGather(const core::Operation* operation) {
return false;
}
NNADAPTER_EXPORT int PrepareGather(core::Operation* operation) {
GATHER_OPERATION_EXTRACT_INPUTS_OUTPUTS
// Infer the shape and type of output operands
CopyOperandTypeExceptQuantParams(&output_operand->type, input_operand->type);
output_operand->type.lifetime = NNADAPTER_TEMPORARY_VARIABLE;
auto& in_dims = input_operand->type.dimensions;
auto& ids_dims = indices_operand->type.dimensions;
auto& out_dims = output_operand->type.dimensions;
int32_t in_count = in_dims.count;
int32_t ids_count = ids_dims.count;
out_dims.count = in_count + ids_count - 1;
auto infer_output_shape = [&](const int32_t* in_dims_data,
const int32_t* ids_dims_data,
int32_t* out_dims_data) {
memcpy(out_dims_data, in_dims_data, sizeof(int32_t) * axis);
memcpy(out_dims_data + axis, ids_dims_data, sizeof(int32_t) * ids_count);
memcpy(out_dims_data + axis + ids_count,
in_dims_data + axis + 1,
sizeof(int32_t) * (in_count - axis));
};
infer_output_shape(in_dims.data, ids_dims.data, out_dims.data);
for (uint32_t i = 0; i < in_dims.dynamic_count; i++) {
infer_output_shape(in_dims.dynamic_data[i],
ids_dims.dynamic_data[i],
out_dims.dynamic_data[i]);
}
if (IsTemporaryShapeOperand(input_operand) &&
IsConstantOperand(indices_operand)) {
auto indices = reinterpret_cast<int32_t*>(indices_operand->buffer);
auto indices_count =
indices_operand->length / static_cast<uint32_t>(sizeof(int32_t));
output_operand->type.lifetime = NNADAPTER_TEMPORARY_SHAPE;
auto& temporary_shape = *(GetTemporaryShape(input_operand));
NNADAPTER_CHECK(temporary_shape.data);
NNADAPTER_CHECK(temporary_shape.data[0]);
NNAdapterOperandDimensionType dimension_type;
dimension_type.count = output_operand->type.dimensions.data[0];
dimension_type.dynamic_count = input_operand->type.dimensions.dynamic_count;
math::gather<int32_t>(
temporary_shape.data,
std::vector<int32_t>({static_cast<int32_t>(temporary_shape.count)}),
indices,
std::vector<int32_t>({static_cast<int32_t>(indices_count)}),
axis,
dimension_type.data);
for (uint32_t i = 0; i < dimension_type.dynamic_count; i++) {
math::gather<int32_t>(
temporary_shape.dynamic_data[i],
std::vector<int32_t>({static_cast<int32_t>(temporary_shape.count)}),
indices,
std::vector<int32_t>({static_cast<int32_t>(indices_count)}),
axis,
dimension_type.dynamic_data[i]);
}
SetTemporaryShape(output_operand, dimension_type);
}
NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand);
return NNADAPTER_NO_ERROR;
}
NNADAPTER_EXPORT int ExecuteGather(core::Operation* operation) {
return NNADAPTER_FEATURE_NOT_SUPPORTED;
}
} // namespace operation
} // namespace nnadapter
| 38.553398 | 80 | 0.712163 | Danielmic |
5247804ebba4a87ff0167d502f6f65835e7d783b | 3,470 | cpp | C++ | test/unit_test/patterns/factory/unit_test_copy_factory.cpp | bvanessen/DiHydrogen | 62e52e22184556a028750bb73d8aed92cedb8884 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2020-01-06T17:26:58.000Z | 2021-12-11T01:17:43.000Z | test/unit_test/patterns/factory/unit_test_copy_factory.cpp | bvanessen/DiHydrogen | 62e52e22184556a028750bb73d8aed92cedb8884 | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2020-02-26T06:07:42.000Z | 2022-02-15T22:51:36.000Z | test/unit_test/patterns/factory/unit_test_copy_factory.cpp | bvanessen/DiHydrogen | 62e52e22184556a028750bb73d8aed92cedb8884 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2020-01-06T18:08:42.000Z | 2021-07-26T14:53:07.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright 2019-2020 Lawrence Livermore National Security, LLC and other
// DiHydrogen Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: Apache-2.0
////////////////////////////////////////////////////////////////////////////////
#include <catch2/catch.hpp>
#include <h2/patterns/factory/CopyFactory.hpp>
#include <memory>
#include <typeinfo>
namespace h2
{
template <typename T>
std::unique_ptr<T> ToUnique(T* ptr)
{
return std::unique_ptr<T>(ptr);
}
} // namespace h2
namespace
{
struct WidgetBase
{
virtual int Data() const noexcept = 0;
virtual ~WidgetBase() = default;
};
struct Widget : WidgetBase
{
Widget(int d) : data_(d) {}
Widget* Copy() const { return new Widget(*this); }
int Data() const noexcept override { return data_; }
int data_;
};
struct Gizmo : WidgetBase
{
Gizmo(int d) : data_(d) {}
std::unique_ptr<Gizmo> Clone() const
{
return h2::ToUnique(new Gizmo(*this));
}
int Data() const noexcept override { return data_; }
int data_;
};
std::unique_ptr<WidgetBase> CopyGizmo(WidgetBase const& obj)
{
auto const& gizmo = dynamic_cast<Gizmo const&>(obj);
return gizmo.Clone();
}
std::unique_ptr<WidgetBase> CopyWidget(WidgetBase const& obj)
{
auto const& widget = dynamic_cast<Widget const&>(obj);
return h2::ToUnique(widget.Copy());
}
} // namespace
TEST_CASE("testing the copy factory class", "[factory][utilities]")
{
using WidgetFactory = h2::factory::CopyFactory<WidgetBase>;
WidgetFactory factory;
SECTION("Register new classes")
{
CHECK(factory.register_builder(typeid(Gizmo), CopyGizmo));
CHECK(factory.register_builder(typeid(Widget), CopyWidget));
CHECK(factory.size() == 2UL);
SECTION("Re-registering a type fails.")
{
CHECK_FALSE(factory.register_builder(typeid(Widget), CopyWidget));
CHECK(factory.size() == 2UL);
}
SECTION("Copy objects by concrete type")
{
Widget w(17);
auto w2 = factory.copy_object(w);
auto const& w2_ref = *w2;
CHECK(w2->Data() == w.Data());
CHECK(typeid(w2_ref) == typeid(w));
Gizmo g(13);
auto g2 = factory.copy_object(g);
auto const& g2_ref = *g2;
CHECK(g2->Data() == g.Data());
CHECK(typeid(g2_ref) == typeid(g));
}
SECTION("Copy objects through base type")
{
auto g = std::unique_ptr<WidgetBase>(new Gizmo(37));
auto w = std::unique_ptr<WidgetBase>(new Widget(73));
auto w2 = factory.copy_object(*w);
auto g2 = factory.copy_object(*g);
CHECK(w2->Data() == w->Data());
CHECK(g2->Data() == g->Data());
}
SECTION("Get list of supported types")
{
auto names = factory.registered_types();
CHECK(names.size() == factory.size());
}
SECTION("Unregister types.")
{
CHECK(factory.unregister(typeid(Widget)));
CHECK(factory.size() == 1UL);
CHECK(factory.unregister(typeid(Gizmo)));
CHECK(factory.size() == 0UL);
}
}
SECTION("Cannot copy unregistered widgets")
{
Gizmo g(13);
CHECK_THROWS(factory.copy_object(g));
}
}
| 25.703704 | 80 | 0.563112 | bvanessen |
5250d23eb93b67242ce7adcb1c49443d482be03b | 1,177 | cpp | C++ | thdatwrapper.cpp | BearKidsTeam/thplayer | 54db11c02ad5fb7b6534b93e5c2ef03ecb91bc03 | [
"BSD-2-Clause"
] | 13 | 2019-01-02T13:52:09.000Z | 2022-01-30T10:17:01.000Z | thdatwrapper.cpp | BearKidsTeam/thplayer | 54db11c02ad5fb7b6534b93e5c2ef03ecb91bc03 | [
"BSD-2-Clause"
] | null | null | null | thdatwrapper.cpp | BearKidsTeam/thplayer | 54db11c02ad5fb7b6534b93e5c2ef03ecb91bc03 | [
"BSD-2-Clause"
] | 1 | 2018-11-20T04:41:53.000Z | 2018-11-20T04:41:53.000Z | #include "thdatwrapper.hpp"
#include <cstdlib>
#include <cstring>
thDatWrapper::thDatWrapper(const char *datpath,unsigned ver)
{
thtk_error_t *e=NULL;
datf=thtk_io_open_file(datpath,"rb",&e);
thtk_error_free(&e);
dat=thdat_open(ver,datf,&e);
if(!dat)
//just try the latest supported version instead
{
thtk_error_free(&e);
dat=thdat_open(17,datf,&e);
}
thtk_error_free(&e);
}
ssize_t thDatWrapper::getFileSize(const char *path)
{
thtk_error_t *e=NULL;
int en=thdat_entry_by_name(dat,path,&e);
thtk_error_free(&e);
if(!~en)return -1;
return thdat_entry_get_size(dat,en,&e);
}
int thDatWrapper::getFile(const char *path,char *dest)
{
thtk_error_t *e=NULL;
int en=thdat_entry_by_name(dat,path,&e);
thtk_error_free(&e);
if(!~en)return -1;
ssize_t sz=thdat_entry_get_size(dat,en,&e);
thtk_error_free(&e);
void *m=malloc(sz);
thtk_io_t* mf=thtk_io_open_memory(m,sz,&e);
thtk_error_free(&e);
ssize_t r=thdat_entry_read_data(dat,en,mf,&e);
if(!~r)return -1;
thtk_error_free(&e);
memcpy(dest,m,sz);
thtk_io_close(mf);
return 0;
}
thDatWrapper::~thDatWrapper()
{
thtk_error_t *e=NULL;
thdat_close(dat,&e);
thtk_error_free(&e);
thtk_io_close(datf);
}
| 22.634615 | 60 | 0.724724 | BearKidsTeam |
5252205036d63502d017a67a262dc6c3d6547898 | 2,795 | cpp | C++ | interfaces/kits/js/napi/src/delivery_callback.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/js/napi/src/delivery_callback.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | null | null | null | interfaces/kits/js/napi/src/delivery_callback.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:07:15.000Z | 2021-09-13T12:07:15.000Z | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* 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 "delivery_callback.h"
#include "napi_util.h"
namespace OHOS {
namespace Telephony {
DeliveryCallback::DeliveryCallback(bool hasCallback, napi_env env, napi_ref thisVarRef, napi_ref callbackRef)
: hasCallback_(hasCallback), env_(env), thisVarRef_(thisVarRef), callbackRef_(callbackRef)
{}
DeliveryCallback::~DeliveryCallback()
{
env_ = nullptr;
thisVarRef_ = nullptr;
callbackRef_ = nullptr;
}
void DeliveryCallback::OnSmsDeliveryResult(const std::u16string pdu)
{
if (hasCallback_) {
napi_handle_scope scope = nullptr;
napi_open_handle_scope(env_, &scope);
napi_value callbackFunc = nullptr;
napi_get_reference_value(env_, callbackRef_, &callbackFunc);
napi_value callbackValues[2] = {0};
if (!pdu.empty()) {
std::string pdu8 = NapiUtil::ToUtf8(pdu);
callbackValues[0] = NapiUtil::CreateUndefined(env_);
napi_create_object(env_, &callbackValues[1]);
size_t dataSize = pdu8.size();
uint32_t forDataSize = (uint32_t)dataSize;
napi_value arrayValue = nullptr;
napi_create_array(env_, &arrayValue);
for (uint32_t i = 0; i < forDataSize; ++i) {
napi_value element = nullptr;
int32_t intValue = pdu8[i];
napi_create_int32(env_, intValue, &element);
napi_set_element(env_, arrayValue, i, element);
}
std::string pduStr = "pdu";
napi_set_named_property(env_, callbackValues[1], pduStr.c_str(), arrayValue);
} else {
callbackValues[0] = NapiUtil::CreateErrorMessage(env_, "pdu empty");
callbackValues[1] = NapiUtil::CreateUndefined(env_);
}
napi_value callbackResult = nullptr;
napi_value thisVar = nullptr;
napi_get_reference_value(env_, thisVarRef_, &thisVar);
napi_call_function(env_, thisVar, callbackFunc, 2, callbackValues, &callbackResult);
napi_delete_reference(env_, thisVarRef_);
napi_delete_reference(env_, callbackRef_);
napi_close_handle_scope(env_, scope);
}
}
} // namespace Telephony
} // namespace OHOS | 39.928571 | 109 | 0.670483 | openharmony-gitee-mirror |
5254cdae99f9f4622692fafe17a3e8510c53c9c4 | 697 | cpp | C++ | src/codegen/ILtoMIPS/inita.cpp | EthanSK/C-to-MIPS-Compiler | a736901053ec1a2ad009bf33f588b4ce5293317c | [
"MIT"
] | 6 | 2019-05-21T09:42:10.000Z | 2021-03-22T04:34:20.000Z | src/codegen/ILtoMIPS/inita.cpp | EthanSK/C-to-MIPS-Compiler | a736901053ec1a2ad009bf33f588b4ce5293317c | [
"MIT"
] | null | null | null | src/codegen/ILtoMIPS/inita.cpp | EthanSK/C-to-MIPS-Compiler | a736901053ec1a2ad009bf33f588b4ce5293317c | [
"MIT"
] | 1 | 2019-06-25T22:35:24.000Z | 2019-06-25T22:35:24.000Z | #include "il2mips.hpp"
void IL2MIPS::inita(Instr instr, MIPSContext &context)
{
if (context.isGlobalScope())
{
context.removeGlobalInits(instr.dest);
for (size_t i = 0; i < instr.extraData.size(); ++i)
{
context.addRawInstr(Instr(".word", instr.extraData[i]));
}
context.addRawInstr(Instr(".align", "2"));
}
else
{
context.addInstr(Instr("move", "$t0", instr.dest));
for (size_t i = 0; i < instr.extraData.size(); ++i)
{
context.addRawInstr(Instr("li", "$t1", instr.extraData[i]));
context.addRawInstr(Instr("sw", "$t1", std::to_string(4 * i) + "($t0)"));
}
}
} | 30.304348 | 85 | 0.535151 | EthanSK |
5256b84311004fb31aa20ed865492a6feb544db4 | 10,414 | cpp | C++ | common/AdvancedOptionsDialog.cpp | Jasig/ImageQuiz | 6a303dcfa01801aa5cccb7835f1b257d461bb33e | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2016-12-19T15:53:52.000Z | 2021-03-24T00:21:47.000Z | common/AdvancedOptionsDialog.cpp | Jasig/ImageQuiz | 6a303dcfa01801aa5cccb7835f1b257d461bb33e | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2017-02-04T06:18:14.000Z | 2019-07-02T17:21:05.000Z | common/AdvancedOptionsDialog.cpp | Jasig/ImageQuiz | 6a303dcfa01801aa5cccb7835f1b257d461bb33e | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2015-11-19T17:31:33.000Z | 2017-01-27T18:35:00.000Z | #include "AdvancedOptionsDialog.h"
#include "StudyDialog.h"
#include "QuizDialog.h"
#include "sysscale.h"
#include <QDebug>
#include <sstream>
AdvancedOptionsDialog * AdvancedOptionsDialog::s_instance = nullptr;
AdvancedOptionsDialog::AdvancedOptionsDialog(QWidget * parent)
: QDialog( parent )
{
width = ppp(400);
height = ppp(460);
setGeometry(QRect(0, 0, width, height));
setMinimumSize(width, height);
setMaximumSize(width, height);
setWindowTitle("Advanced Options");
spellingGroupBox = new QGroupBox("Spelling", this);
spellingGroupBox->setGeometry(QRect(ppp(10), ppp(10), width - ppp(20), ppp(125)));
group1Line1Label = new QLabel("This setting sets the sensitivity of the spelling in both", spellingGroupBox);
group1Line1Label->setGeometry(QRect(ppp(10), ppp(30), width - ppp(40), ppp(20)));
group1Line1Label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
group1Line2Label = new QLabel("quiz and test modes. The higher the setting, the better", spellingGroupBox);
group1Line2Label->setGeometry(QRect(ppp(10), ppp(50), width - ppp(40), ppp(20)));
group1Line2Label->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
group1Line3Label = new QLabel("the spelling must be. Eg. 100% is perfect spelling.", spellingGroupBox);
group1Line3Label->setGeometry(QRect(ppp(10), ppp(70), width - ppp(40), ppp(20)));
group1Line3Label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
group1Line4Label = new QLabel("Spelling sensitivity : ", spellingGroupBox);
group1Line4Label->setGeometry(QRect((width - ppp(40)) / 2 - ppp(65), ppp(90), ppp(200), ppp(20)));
group1Line4Label->setAlignment(Qt::AlignVCenter);
sensitivityComboBox = new QComboBox(spellingGroupBox);
sensitivityComboBox->setGeometry(QRect((width - ppp(40)) / 2 + ppp(75), ppp(90), ppp(60 + 20), ppp(20)));
sensitivityComboBox->addItem("100%");
sensitivityComboBox->addItem("90%");
sensitivityComboBox->addItem("80%");
sensitivityComboBox->addItem("70%");
numberOfImagesGroupBox = new QGroupBox("Number of Images", this);
numberOfImagesGroupBox->setGeometry(QRect(ppp(10), ppp(140), width - ppp(20), ppp(80)));
group2Line1Label = new QLabel("Please select the total number of images in", numberOfImagesGroupBox);
group2Line1Label->setGeometry(QRect(ppp(10), ppp(30), width - ppp(40), ppp(20)));
group2Line1Label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
group2Line2Label = new QLabel("the quiz and test sessions.", numberOfImagesGroupBox);
group2Line2Label->setGeometry(QRect((width - ppp(40)) / 2 - ppp(90), ppp(50), ppp(200), ppp(20)));
numberOfImagesComboBox = new QComboBox(numberOfImagesGroupBox);
numberOfImagesComboBox->addItem("Show All");
for (int i = 15; i <= 45; i += 5)
{
std::stringstream s;
s << i;
numberOfImagesComboBox->addItem(s.str().c_str());
}
numberOfImagesComboBox->setGeometry(QRect((width - ppp(40)) / 2 + ppp(85), ppp(50), ppp(70 + 20), ppp(20)));
fixationSpeedGroupBox = new QGroupBox("Fixation Speed", this);
fixationSpeedGroupBox->setGeometry(QRect(ppp(10), ppp(225), width - ppp(20), ppp(95)));
label1 = new QLabel(fixationSpeedGroupBox);
label1->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label1->setText("Fixation Display time: (0.5 - 3 seconds)");
label1->setGeometry(QRect(0, ppp(30), width - ppp(20), ppp(20)));
label2 = new QLabel(fixationSpeedGroupBox);
label2->setText("Less");
label2->setGeometry(QRect(ppp(15), ppp(47), ppp(50), ppp(20)));
label3 = new QLabel(fixationSpeedGroupBox);
label3->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
label3->setText("0.5 seconds");
label3->setGeometry(QRect(0, ppp(60), width - ppp(20), ppp(20)));
label4 = new QLabel(fixationSpeedGroupBox);
label4->setText("More");
label4->setGeometry(QRect(ppp(330), ppp(47), ppp(50), ppp(20)));
fixationIntervalSlider = new QSlider( fixationSpeedGroupBox );
fixationIntervalSlider->setOrientation( Qt::Horizontal );
fixationIntervalSlider->setMinimum(5);
fixationIntervalSlider->setMaximum(30);
fixationIntervalSlider->setValue(5);
fixationIntervalSlider->setGeometry(QRect(ppp(45), ppp(47), ppp(280), ppp(20)));
QObject::connect(fixationIntervalSlider, SIGNAL(valueChanged(int)), this, SLOT(setFixationInterval(int)));
progressGroupBox = new QGroupBox( "Progress", this );
progressGroupBox->setGeometry(QRect(ppp(10), ppp(325), width - ppp(20), ppp(80)));
afterQuizCheckBox = new QCheckBox( "Show progress after quiz.", progressGroupBox );
afterTestCheckBox = new QCheckBox( "Show progress after test.", progressGroupBox );
afterQuizCheckBox->setGeometry(QRect(width / 2 - ppp(80), ppp(30), ppp(200), ppp(20)));
afterTestCheckBox->setGeometry(QRect(width / 2 - ppp(80), ppp(50), ppp(200), ppp(20)));
applyButton = new QPushButton( "Apply", this );
applyButton->setDefault(true);
applyButton->setAutoDefault(true);
applyButton->setGeometry(QRect(ppp(10), ppp(415), width / 2 - ppp(15), ppp(25)));
QObject::connect(applyButton, SIGNAL(clicked()), this, SLOT(applyClicked()));
cancelButton = new QPushButton( "Cancel", this);
cancelButton->setGeometry(QRect(width / 2 + ppp(5), ppp(415), width / 2 - ppp(15), ppp(25)));
QObject::connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));
spellingSensitivityIndex = 0; // Option 0 = 100% sensitivity
numberOfImagesIndex = 0; // Option 0 = show all images
fixationInterval = 5; // fixation invertal is 5*100 msec
viewProgressAfterQuizChecked = false; // Flag to view progress report after the Quiz
viewProgressAfterTestChecked = false; // Flag to view progress report after the Test
}
// Read the user file to find out the advanced
// options that were set during the last session for the user
// fname: user filename
void AdvancedOptionsDialog::updateVariables(QString fname)
{
QFile inFile;
inFile.setFileName(fname + ".csv");
qDebug() << "opening settings file " << fname;
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::warning( this, "No Advanced Settings",
tr("<b>Session is configured using default advanced settings.</b>"));
return;
}
QTextStream in;
in.setDevice(&inFile);
// Read the first line of the user file
// If the header of the first line is 'AdvancedOptions', a previous sessions was saved
// otherwise do nothing, constructor would set the variables to default values.
QString line = in.readLine();
QStringList options = line.split(",");
bool ok;
if (options[0] == "AdvancedOptions")
{
spellingSensitivityIndex = options[1].toInt(&ok, 10);
numberOfImagesIndex = options[2].toInt(&ok, 10 );
fixationInterval = options[3].toInt(&ok, 10);
viewProgressAfterQuizChecked = options[4].toInt(&ok, 10);
QuizDialog::instance()->setQuizProgressReport( viewProgressAfterQuizChecked );
viewProgressAfterTestChecked = options[5].toInt(&ok, 10);
QuizDialog::instance()->setTestProgressReport( viewProgressAfterTestChecked );
}
setOptions(); // Set advanced option variables in the Quiz and Study dialog
resetOptions(); // Set the advanced options dialog to show current state
inFile.close();
}
// Set advanced option variables in the Quiz and Study dialog
void AdvancedOptionsDialog::setOptions()
{
QuizDialog::instance()->setSpellingSensitivity(spellingSensitivityIndex);
QuizDialog::instance()->setNumberOfImages(numberOfImagesIndex);
StudyDialog::instance()->setFixationInterval(fixationInterval * 100);
QuizDialog::instance()->setFixationInterval(fixationInterval * 100);
QuizDialog::instance()->setQuizProgressReport(viewProgressAfterQuizChecked);
QuizDialog::instance()->setTestProgressReport(viewProgressAfterTestChecked);
}
void AdvancedOptionsDialog::applyClicked()
{
spellingSensitivityIndex = sensitivityComboBox->currentIndex();
numberOfImagesIndex = numberOfImagesComboBox->currentIndex();
fixationInterval = fixationIntervalSlider->value();
viewProgressAfterQuizChecked = afterQuizCheckBox->isChecked();
viewProgressAfterTestChecked = afterTestCheckBox->isChecked();
setOptions();
hide();
}
// Set the advanced options dialog to show current state
void AdvancedOptionsDialog::resetOptions()
{
sensitivityComboBox->setCurrentIndex(spellingSensitivityIndex);
numberOfImagesComboBox->setCurrentIndex(numberOfImagesIndex);
fixationIntervalSlider->setValue(fixationInterval);
setFixationInterval(fixationInterval);
afterQuizCheckBox->setChecked(viewProgressAfterQuizChecked);
afterTestCheckBox->setChecked(viewProgressAfterTestChecked);
}
void AdvancedOptionsDialog::cancelClicked()
{
resetOptions();
hide();
}
// Same as clicking cancel
void AdvancedOptionsDialog::closeEvent(QCloseEvent *)
{
cancelClicked();
}
// If the user presses the ESCAPE key in a dialog, QDialog::reject() will be called
// Overriding reject() to do nothing
void AdvancedOptionsDialog::reject()
{
}
// Updates the slider label to show the current fixation interval
void AdvancedOptionsDialog::setFixationInterval(int value)
{
std::stringstream s;
s << value / 10 << "." << value % 10 << " seconds";
label3->setText(s.str().c_str());
}
// Return a '|'-delimited concatentated string of the state variables to store to file
QString AdvancedOptionsDialog::getSettings()
{
QString settings="AdvancedOptions,";
settings.append(QString::number(spellingSensitivityIndex));
settings.append(",");
settings.append(QString::number(numberOfImagesIndex));
settings.append(",");
settings.append(QString::number(fixationInterval));
settings.append(",");
settings.append(QString::number(viewProgressAfterQuizChecked));
settings.append(",");
settings.append(QString::number(viewProgressAfterTestChecked));
settings.append("\n");
return settings;
}
AdvancedOptionsDialog * AdvancedOptionsDialog::instance(QWidget * parent)
{
if (!s_instance)
s_instance = new AdvancedOptionsDialog(parent);
return s_instance;
}
AdvancedOptionsDialog::~AdvancedOptionsDialog()
{
}
| 40.839216 | 113 | 0.706837 | Jasig |
525923e263bd39e69b8727989bd0ef89d63c4051 | 1,406 | cpp | C++ | docker/water/epanet/tags/ooten/ooten/ONENException.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | 3 | 2021-01-06T03:01:18.000Z | 2022-03-21T03:02:55.000Z | docker/water/epanet/tags/ooten/ooten/ONENException.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | docker/water/epanet/tags/ooten/ooten/ONENException.cpp | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | /*
*******************************************************************
OOTEN: Object Oriented Toolkit for Epanet
ONENEXCEPTION.CPP - Implementation of OOTEN ONENException class
VERSION: 1.00beta
DATE: 13 June 2003
AUTHOR: JE van Zyl
Rand Afrikaans University
Johannesburg
South Africa
jevz@ing.rau.ac.za
*******************************************************************
*/
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ONENException.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
ONENException::ONENException(void) : ONException() {}
ONENException::ONENException(int errcode, string origin) : ONException("", origin)
{
errcode=errcode;
char message[1024];
int error;
error=ENgeterror(errcode, message, 1023);
if (error!=0)
setMessage("Error could not be retrieved from Epanet. Error code = " + errcode);
else
{
string messg(message);
setMessage(messg);
}
}
ONENException::ONENException(const ONENException &o)
{
setOrigin(o.origin());
setMessage(o.message());
}
ONENException::~ONENException(void){}
string ONENException::report(void) const
{
string messg = "Epanet exception thrown at " + origin() + " : " + message();
return messg;
}
| 23.433333 | 88 | 0.519915 | liujiamingustc |
525d5397bf474c0141afa0878aae1c74542f64ef | 517 | cpp | C++ | Cpp/Codes/Practice/LeetCode/69 Sqrt.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | null | null | null | Cpp/Codes/Practice/LeetCode/69 Sqrt.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | null | null | null | Cpp/Codes/Practice/LeetCode/69 Sqrt.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | 1 | 2019-04-01T10:30:03.000Z | 2019-04-01T10:30:03.000Z | #include <gtest/gtest.h>
using namespace std;
int mySqrt(int x)
{
if (x==0)
return 0;
int result = 0;
int l = 1;
int r = x;
while (r >= l)
{
int m = l + (r-l)/2;
if (m == x/m)
{
result = m;
break;
}
else if (m < x/m)
{
result = m;
l = m+1;
}
else
{
r = m-1;
}
}
return result;
}
TEST(LeetCode, tMySqrt)
{
ASSERT_EQ(mySqrt(0),0);
ASSERT_EQ(mySqrt(1),1);
ASSERT_EQ(mySqrt(2),1);
ASSERT_EQ(mySqrt(3),1);
ASSERT_EQ(mySqrt(4),2);
ASSERT_EQ(mySqrt(12312312),3508);
} | 12.309524 | 34 | 0.541586 | QuincyWork |
525e271d3e86d5c7d50b97cb4620fcc9fd9b2c7f | 5,012 | cc | C++ | cageAnalysis/SMA_Preprocess/preprocess.cc | richardjgowers/zeoplusplus | 99d004b863f5fa6b069ad348fb86e932c6624c1f | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-03-07T09:39:00.000Z | 2021-02-08T14:19:45.000Z | cageAnalysis/SMA_Preprocess/preprocess.cc | richardjgowers/zeoplusplus | 99d004b863f5fa6b069ad348fb86e932c6624c1f | [
"BSD-3-Clause-LBNL"
] | 1 | 2020-09-17T11:21:43.000Z | 2020-09-17T11:21:43.000Z | cageAnalysis/SMA_Preprocess/preprocess.cc | richardjgowers/zeoplusplus | 99d004b863f5fa6b069ad348fb86e932c6624c1f | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-11-09T01:56:28.000Z | 2022-03-11T03:04:01.000Z | /*
* preprocess.cc
*
* Created on: Mar 3, 2016
* Author: ismael.gomez
*/
#include "preprocess.hh"
/////////////////
MoleculeInfo *PerformMCA (Complex *Chemical, int ExecMode)
{
///// ERROR CHECK
/// If Chemical is null, stop
if (Chemical == NULL) {
return NULL;
}
///// CREATE MOLECULE_INFO OBJECT
/// Empty object
// Add pruned chemical to it
MoleculeInfo *Molecule = new MoleculeInfo();
///// COMPUTE CHEMICAL INFORMATION
/// Prune chemical (previously read from file)
// Insert into molecule
if (ExecMode%NO_PRUNE == 0)
{
//cout << "Not pruned" << endl;
Complex *ChemCopy = Chemical->ComplexCopy();
Molecule->SetChemical(ChemCopy);
}
else
{
//cout << "Pruned" << endl;
Complex *PrunedChemical = Chemical->PruneComplex();
if (PrunedChemical == NULL)
{
delete Molecule;
return NULL;
}
Molecule->SetChemical(PrunedChemical);
}
///// COMPUTE VORONOI GRAPH
/// Use molecule's chemical (after processing)
// Insert into molecule info
Complex *MolVoronoi = ComputeVoronoi( Molecule->GetChemical() );
Molecule->SetVoronoiGraph(MolVoronoi);
Complex *VoroCH = MolVoronoi->ComplexCopy();
Molecule->SetVoroConvexHull(VoroCH);
///// MOLECULE'S CHARACTERISTIC
///
//
/// Test (exploratory mode)
bool Test = false;
if (ExecMode%EXPLORATORY == 0)
{
Test = CenterShadowTest(Molecule);
return Molecule;
}
//
//Test = CenterShadowTest(Molecule);
///// COMPUTE INTERNAL CELLS
/// Stop processing if internal cells computing failed
//
/*if( !MoleculeInternalCells(Molecule) )
{
delete Molecule;
return NULL;
}*/
///// COMPUTE SHADOW CHARACTERISTIC FOR BEST VORONOI NODE
/// Only if previous test failed
/*if (ExecMode%EXPLORATORY == 0 && !Test)
{
Test = MaxIntSphereShadowTest(Molecule);
if (!Test)
{
return Molecule;
}
}*/
CenterShadowTest(Molecule);
int SRC = ProcessShadow(Molecule);
// If no points were reclassified as internal, finish
if (SRC == 0)
{
//delete Molecule;
//return NULL;
return Molecule;
}
Complex *VoroCluster = ClusterizeComplex(Molecule->GetVoronoiGraph(), Molecule->GetChemical(), ATOMIC_CLUSTER_THRESHOLD);
delete Molecule->GetVoronoiGraph();
Molecule->SetVoronoiGraph(VoroCluster);
///// COMPUTE MOLECULE WINDOWS
/// Call function and check if it succesfully computed
//
bool CWFlag = true;
if ( ExecMode%WINDOW_COMP == 0)
{
//CWFlag = ComputeWindows( Molecule, ID_WC_ALL);
//CWFlag = ComputeWindows( Molecule, UW_ALPHA_OPT);
CWFlag = ComputeWindowsPER( Molecule);
//if (!CWFlag) cout << "Warning: Windows were not successfully computed" << endl;
Molecule->SetWinCorrect(CWFlag);
}
///// RETURN MOLECULE_INFO OBJECT
/// Containing:
// - Chemical info (pruned)
// - Voronoi tessellation
// - Window list and window number
return Molecule;
}
MoleculeInfo *MolecularCageAnalysis(char *Filename, int ExecMode)
{
// TODO: Parse filename
///// READ CHEMICAL INFORMATION FROM FILE
/// Read it from file (.mol).
// Store it in Complex object.
Complex *Chemical = new Complex();
if (!ReadMolFile(Chemical, Filename))
{
//cout << "Error reading file" << endl;
delete Chemical;
return NULL;
}
// TODO check extension of the file and load in depends
/*if (!ReadXYZFile(Chemical, Filename))
{
cout << "Error reading file" << endl;
return NULL;
}*/
///// PERFORM MOLECULAR CAGE ANALYSIS
/// Retrieve molecular relevant information in a MoleculeInfo object.
// Allocation performed at a lower layer.
MoleculeInfo *Molecule = PerformMCA(Chemical, ExecMode);
delete Chemical;
return Molecule;
}
void MultipleMolecularCageAnalysis ( char *Filename,
vector <MoleculeInfo *> *MMCA_Vector,
int ExecMode)
{
// TODO: Check that the extension is appropriate
///// LOAD ALL MOLECULES FROM FILE
/// Molecules stored in vector of Complex *
vector <Complex *> *MoleculeVector = new vector <Complex *>();
//ReadFrameinfoFile(MoleculeVector, Filename);
ReadSDF(MoleculeVector, Filename);
//cout << "Molecules read: " << MoleculeVector->size() << endl;
///// FOR EACH MOLECULE, PROCESS
/// Perform all computations allowed by the software
//
vector <Complex *>::iterator MolIt;
int Count = 0;
//cout << "Mols read: " << MoleculeVector->size() << endl;
for (MolIt = MoleculeVector->begin(); MolIt != MoleculeVector->end(); MolIt++)
{
Complex *Chemical = *(MolIt);
//char *CName = Chemical->GetCName();
//cout << "Processing " << CName << endl;
// TODO - RESTORE (with ExecMode argument)
MoleculeInfo *Molecule = PerformMCA(Chemical, ExecMode);
if (Molecule != NULL)
{
MMCA_Vector->push_back(Molecule);
Count++;
}
//else
//{
//cout << "Molecule failed to be read" << endl;
//}
}
/// ERASE MOLECULES (After analysis)
for (MolIt = MoleculeVector->begin(); MolIt != MoleculeVector->end(); MolIt++)
{
Complex *Chemical = *(MolIt);
delete Chemical;
}
delete MoleculeVector;
}
/************
*
*/
| 19.426357 | 122 | 0.665204 | richardjgowers |
525f30084180d15cc0be1cec8c6b4f3cc4d13a28 | 745 | cpp | C++ | oop_ex24.cpp | 85105/HW | 2161a1a7ac1082a85454672d359c00f2d42ef21f | [
"MIT"
] | null | null | null | oop_ex24.cpp | 85105/HW | 2161a1a7ac1082a85454672d359c00f2d42ef21f | [
"MIT"
] | null | null | null | oop_ex24.cpp | 85105/HW | 2161a1a7ac1082a85454672d359c00f2d42ef21f | [
"MIT"
] | null | null | null | /* oop_ex24.cpp
dynamic 2D array using new and delete */
#include <iostream>
using namespace std;
void main()
{
// obtain the matrix size from user
int size;
cout << "Please input the size of the square matrix." << endl;
cin >> size;
// create the matrix using new
int** m = new int*[size];
for (int i = 0; i<size; i++)
m[i] = new int[size];
// assign the values to the created matrix
for (int i = 0; i<size; i++)
for (int j = 0; j<size; j++)
m[i][j] = i + j;
// show the matrix on the screen
for (int i = 0; i<size; i++)
{
for (int j = 0; j<size; j++)
cout << m[i][j] << " ";
cout << endl;
}
// release the matrix using delete
for (int i = 0; i<size; i++)
delete m[i];
delete m;
system("pause");
}
| 16.555556 | 63 | 0.575839 | 85105 |
5263bf24530cc7230166ab82f9e372d55ef2963c | 26 | cpp | C++ | source/vgraphics/opengl/unused/vix_glmodel.cpp | ritgraphics/VixenEngine | 294a6c69b015ec8bce7920f604176e4f92ffba23 | [
"MIT"
] | null | null | null | source/vgraphics/opengl/unused/vix_glmodel.cpp | ritgraphics/VixenEngine | 294a6c69b015ec8bce7920f604176e4f92ffba23 | [
"MIT"
] | 3 | 2015-10-28T01:29:03.000Z | 2015-11-10T15:20:02.000Z | source/vgraphics/opengl/unused/vix_glmodel.cpp | ritgraphics/VixenEngine | 294a6c69b015ec8bce7920f604176e4f92ffba23 | [
"MIT"
] | null | null | null | #include <vix_glmodel.h>
| 8.666667 | 24 | 0.730769 | ritgraphics |